├── .styleci.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── composer.json
├── config
└── unsplash.php
├── database
└── migrations
│ ├── create_unsplash_assets_table.php.stub
│ └── create_unsplashables_table.php.stub
└── src
├── API
└── UnsplashAPI.php
├── Endpoints
├── Collections.php
├── Photos.php
├── Search.php
├── Stats.php
├── Topics.php
└── Users.php
├── Facades
└── Unsplash.php
├── Http
└── HttpClient.php
├── Models
└── UnsplashAsset.php
├── Queries
└── QueryBuilder.php
├── Traits
└── HasUnsplashables.php
├── Unsplash.php
└── UnsplashServiceProvider.php
/.styleci.yml:
--------------------------------------------------------------------------------
1 | preset: laravel
2 |
3 | disabled:
4 | - single_class_element_per_statement
5 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to `laravel-unsplash` will be documented in this file
4 |
5 | ## 1.0.0 - 201X-XX-XX
6 |
7 | - initial release
8 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Mark Sitko
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Powerful Unsplash package for Laravel
2 |
3 | Provides a fluent api to use the Unsplash within Larvel applications. Use public actions or store images directly in your storage and persists all copyright informations automatically with the databse connector.
4 |
5 | [](https://packagist.org/packages/marksitko/laravel-unsplash)
6 | [](https://travis-ci.org/marksitko/laravel-unsplash)
7 | [](https://scrutinizer-ci.com/g/marksitko/laravel-unsplash)
8 | [](https://packagist.org/packages/marksitko/laravel-unsplash)
9 |
10 |
11 | ## Install
12 |
13 | ``` bash
14 | $ composer require marksitko/laravel-unsplash
15 | ```
16 |
17 | Laravel-Unsplash comes with package discovery and Laravel will register the service provider and facade automatically. Just in case you wanna add it manually, you should provide it in `config/app.php`
18 |
19 | **Service provider**
20 | ``` php
21 | 'providers' => [
22 | //...
23 | MarkSitko\LaravelUnsplash\UnsplashServiceProvider::class,
24 | ];
25 | ```
26 |
27 | **Facade**
28 | ``` php
29 | 'aliases' => [
30 | //...
31 | 'Unsplash' => MarkSitko\LaravelUnsplash\Facades\Unsplash::class,
32 | ];
33 | ```
34 |
35 | Next you should publish the configuration.
36 | ``` bash
37 | $ php artisan vendor:publish --tag=config
38 | ```
39 |
40 | ###### Optional
41 | If you wanna use Laravel-Unsplash with the database connector you have to publish the migration files.
42 | ``` bash
43 | $ php artisan vendor:publish --tag=migrations
44 | ```
45 | It creates 2 migrations. One to store additional informations about stored image and one morph table to use it with the `HasUnsplashables` trait.
46 |
47 | ## Configuration
48 | You have to provide a unsplash api access key in your `.env` file.
49 | [Read how to generate a Unsplash API key](https://unsplash.com/documentation#creating-a-developer-account)
50 | ```
51 | UNSPLASH_ACCESS_KEY=YOUR_GENERATED_API_KEY_FROM_UNSPLASH
52 | ```
53 |
54 | Optional configurations:
55 | ```
56 | # default is false
57 | UNSPLASH_STORE_IN_DATABASE=BOOLEAN
58 |
59 | # default is local
60 | UNSPLASH_STORAGE_DISK=YOUR_STORAGE_DISC
61 | ```
62 |
63 |
64 | ## Basic Usage
65 |
66 | Take a look at the full Unsplash API documentation https://unsplash.com/documentation
67 |
68 | **Random Photos**
69 | ``` php
70 | // Returns the http response body.
71 | $twoRandomPhotosOfSomePeoples = Unsplash::randomPhoto()
72 | ->orientation('portrait')
73 | ->term('people')
74 | ->count(2)
75 | ->toJson();
76 |
77 | // Store the image in on your provided disc
78 | $theNameFromTheStoredPhoto = Unsplash::randomPhoto()
79 | ->orientation('landscape')
80 | ->term('music')
81 | ->randomPhoto()
82 | ->store();
83 | ];
84 | ```
85 |
86 | **Photos**
87 | ``` php
88 | $photos = Unsplash::photos()->toJson();
89 | $photo = Unsplash::photo($id)->toJson();
90 | $photosStatistics = Unsplash::photosStatistics($id)->toJson();
91 | $trackPhotoDownload = Unsplash::trackPhotoDownload($id)->toJson();
92 | ```
93 |
94 | **Users**
95 | ``` php
96 | $user = Unsplash::user($username)->toJson();
97 | $userPortfolio = Unsplash::userPortfolio($username)->toJson();
98 | $userPhotos = Unsplash::userPhotos($username)->toJson();
99 | $userLikes = Unsplash::userLikes($username)->toJson();
100 | $userCollections = Unsplash::userCollections($username)->toJson();
101 | $userStatistics = Unsplash::userStatistics($username)->toJson();
102 | ```
103 |
104 | **Search**
105 | ``` php
106 | $search = Unsplash::search()
107 | ->term('buildings')
108 | ->color('black_and_white')
109 | ->orientation('squarish')
110 | ->toJson();
111 |
112 | $searchCollections = Unsplash::searchCollections()
113 | ->query('events')
114 | ->page($pageNumber)
115 | ->toJson();
116 |
117 | $searchUsers = Unsplash::searchUsers()
118 | ->query('search_term')
119 | ->toJson();
120 | ```
121 |
122 | **Collections**
123 | ``` php
124 | $collectionsList = Unsplash::collectionsList()
125 | ->page($pageNumber)
126 | ->perPage($itemsPerPage)
127 | ->toJson();
128 |
129 | $featuredCollection = Unsplash::featuredCollection()
130 | ->page($pageNumber)
131 | ->perPage($itemsPerPage)
132 | ->toJson();
133 |
134 | $showCollection = Unsplash::showCollection()
135 | ->id($collectionId)
136 | ->toJson();
137 |
138 | $showCollectionPhotos = Unsplash::showCollectionPhotos()
139 | ->id($collectionId)
140 | ->toJson();
141 |
142 | $showCollectionRelatedCollections = Unsplash::showCollectionRelatedCollections()
143 | ->id($collectionId)
144 | ->toJson();
145 | ```
146 |
147 | **Topics**
148 | ``` php
149 | $topicsList = Unsplash::topicsList()
150 | ->page($pageNumber)
151 | ->perPage($itemsPerPage)
152 | ->toJson();
153 |
154 | $showTopic = Unsplash::showTopic()
155 | ->id($topicIdOrSlug)
156 | ->toJson();
157 |
158 | $showTopicPhotos = Unsplash::showTopicPhotos()
159 | ->id($topicIdOrSlug)
160 | ->toJson();
161 | ```
162 |
163 |
164 | **Stats**
165 | ``` php
166 | $totalStats = Unsplash::totalStats()->toJson();
167 | $monthlyStats = Unsplash::monthlyStats()->toJson();
168 | ```
169 |
170 | ## Usage with Database
171 |
172 | If you wanna persist automaticly some informations (i.e. Copyrights) about you stored images you have to run the published migrations. In case you dont have ran the optional command, we start at the beginning:
173 |
174 | ``` bash
175 | $ php artisan vendor:publish --tag=migrations
176 | ```
177 |
178 | ``` bash
179 | $ php artisan migrate
180 | ```
181 |
182 | When migration is successfull, you have to adjust the `.env`
183 | ```
184 | UNSPLASH_STORE_IN_DATABASE=true
185 | ```
186 |
187 | Now when you execute `store()` on the Unsplash client, the image is stored in your provided disc and informations like
188 | - the unsplash photo id
189 | - the stored image name
190 | - author name
191 | - author link
192 |
193 | However, these informations are all required to use a unsplash photo on your website.
194 |
195 | **Example with Unsplash Client**
196 | ``` php
197 | // Returns the created unsplash asset record
198 | $databaseRecord = Unsplash::randomPhoto()->store();
199 | ```
200 |
201 | You are now also able to use the build in `UnsplashAsset` Model
202 | **Example with UnsplashAsset Model**
203 | ``` php
204 | // Returns the created unsplash asset record
205 | $databaseRecord = UnsplashAsset::api()->randomPhoto()->store();
206 |
207 | // Get an stored unsplash asset
208 | $unsplashAsset = UnsplashAsset::find($id);
209 | ```
210 |
211 | You can also use the `HasUnsplashables` Trait on any model.
212 |
213 | **Example with HasUnsplashables Trait on the User Model**
214 | ``` php
215 | use Illuminate\Foundation\Auth\User as Authenticatable;
216 | use MarkSitko\LaravelUnsplash\Traits\HasUnsplashables;
217 |
218 | class User extends Authenticatable
219 | {
220 | use HasUnsplashables;
221 |
222 | // ...
223 | }
224 | ```
225 |
226 | Now you are able to use it like:
227 | ``` php
228 | // store the unsplash asset in a morphToMany relation
229 | $unsplashAsset = Unsplash::randomPhoto()->store();
230 | User::unsplash()->save($unsplashAsset);
231 |
232 | // retrive all related unsplash assets
233 | User::find($userId)->unsplash();
234 | ```
235 |
236 | ## License
237 |
238 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
239 |
240 | ## Laravel Package Boilerplate
241 |
242 | This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).
243 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "marksitko/laravel-unsplash",
3 | "description": "Provides a fluent Unsplash API for Laravel",
4 | "keywords": [
5 | "marksitko",
6 | "laravel-unsplash"
7 | ],
8 | "homepage": "https://github.com/marksitko/laravel-unsplash",
9 | "license": "MIT",
10 | "type": "library",
11 | "authors": [
12 | {
13 | "name": "Mark Sitko",
14 | "email": "hey@marksitko.de",
15 | "role": "Developer"
16 | }
17 | ],
18 | "require": {
19 | "php": "^8.0",
20 | "guzzlehttp/guzzle": "^7.0",
21 | "illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0"
22 | },
23 | "require-dev": {
24 | "orchestra/testbench": "^7.0|^8.0|^9.0",
25 | "phpunit/phpunit": "^9.0|^10.0|11.5.10"
26 | },
27 | "autoload": {
28 | "psr-4": {
29 | "MarkSitko\\LaravelUnsplash\\": "src"
30 | }
31 | },
32 | "autoload-dev": {
33 | "psr-4": {
34 | "MarkSitko\\LaravelUnsplash\\Tests\\": "tests"
35 | }
36 | },
37 | "scripts": {
38 | "test": "vendor/bin/phpunit",
39 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage"
40 | },
41 | "config": {
42 | "sort-packages": true
43 | },
44 | "extra": {
45 | "laravel": {
46 | "providers": [
47 | "MarkSitko\\LaravelUnsplash\\UnsplashServiceProvider"
48 | ],
49 | "aliases": {
50 | "Unsplash": "MarkSitko\\LaravelUnsplash\\Facades\\Unsplash"
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/config/unsplash.php:
--------------------------------------------------------------------------------
1 | env('UNSPLASH_ACCESS_KEY'),
5 | 'store_in_database' => env('UNSPLASH_STORE_IN_DATABASE', false),
6 | 'disk' => env('UNSPLASH_STORAGE_DISK', 'local'),
7 | ];
8 |
--------------------------------------------------------------------------------
/database/migrations/create_unsplash_assets_table.php.stub:
--------------------------------------------------------------------------------
1 | bigIncrements('id');
18 | $table->uuid('unsplash_id');
19 | $table->string('name')->unique();
20 | $table->string('author');
21 | $table->string('author_link');
22 | $table->timestamps();
23 | });
24 | }
25 |
26 | /**
27 | * Reverse the migrations.
28 | *
29 | * @return void
30 | */
31 | public function down()
32 | {
33 | Schema::dropIfExists('unsplash_assets');
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/database/migrations/create_unsplashables_table.php.stub:
--------------------------------------------------------------------------------
1 | unsignedBigInteger('unsplash_asset_id');
18 | $table->unsignedBigInteger('unsplashables_id');
19 | $table->string('unsplashables_type');
20 | });
21 | }
22 |
23 | /**
24 | * Reverse the migrations.
25 | *
26 | * @return void
27 | */
28 | public function down()
29 | {
30 | Schema::dropIfExists('unsplashables');
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/API/UnsplashAPI.php:
--------------------------------------------------------------------------------
1 | apiCall = [
15 | 'endpoint' => 'collections',
16 | ];
17 |
18 | return $this;
19 | }
20 |
21 | /**
22 | * List featured collections
23 | * Get a single page from the list of featured collections.
24 | * @link https://unsplash.com/documentation#list-featured-collections
25 | */
26 | public function featuredCollection(): self
27 | {
28 | $this->apiCall = [
29 | 'endpoint' => 'collections/featured',
30 | ];
31 |
32 | return $this;
33 | }
34 |
35 | /**
36 | * Get a collection
37 | * Retrieve a single collection. To view a user’s private collections, the read_collections scope is required.
38 | * @link https://unsplash.com/documentation#get-a-collection
39 | *
40 | * @param int|string $id The collections’s ID. Required.
41 | */
42 | public function showCollection($id): self
43 | {
44 | $this->apiCall = [
45 | 'endpoint' => "collections/{$id}",
46 | ];
47 |
48 | return $this;
49 | }
50 |
51 | /**
52 | * Get a collection’s photos
53 | * Retrieve a collection’s photos.
54 | * @link https://unsplash.com/documentation#get-a-collections-photos
55 | *
56 | * @param int|string $id The collections’s ID. Required.
57 | */
58 | public function showCollectionPhotos($id): self
59 | {
60 | $this->apiCall = [
61 | 'endpoint' => "collections/{$id}/photos",
62 | ];
63 |
64 | return $this;
65 | }
66 |
67 | /**
68 | * List a collection’s related collections
69 | * Retrieve a list of collections related to this one.
70 | * @link https://unsplash.com/documentation#list-a-collections-related-collections
71 | *
72 | * @param int|string $id The collections’s ID. Required.
73 | */
74 | public function showCollectionRelatedCollections($id): self
75 | {
76 | $this->apiCall = [
77 | 'endpoint' => "collections/{$id}/related",
78 | ];
79 |
80 | return $this;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/Endpoints/Photos.php:
--------------------------------------------------------------------------------
1 | apiCall = [
15 | 'endpoint' => 'photos',
16 | ];
17 |
18 | return $this;
19 | }
20 |
21 | /**
22 | * Get a photo
23 | * Retrieve a single photo.
24 | * @link https://unsplash.com/documentation#get-a-photo
25 | *
26 | * @param string $id
27 | */
28 | public function photo($id): self
29 | {
30 | $this->apiCall = [
31 | 'endpoint' => "photos/{$id}",
32 | ];
33 |
34 | return $this;
35 | }
36 |
37 | /**
38 | * Get a random photo.
39 | * @link https://unsplash.com/documentation#get-a-random-photo
40 | */
41 | public function randomPhoto(): self
42 | {
43 | $this->apiCall = [
44 | 'endpoint' => 'photos/random',
45 | ];
46 |
47 | return $this;
48 | }
49 |
50 | /**
51 | * Get a photo’s statistics.
52 | * @link https://unsplash.com/documentation#get-a-photos-statistics
53 | *
54 | * @param string $id
55 | */
56 | public function photosStatistics($id): self
57 | {
58 | $this->apiCall = [
59 | 'endpoint' => "photos/{$id}/statistics",
60 | ];
61 |
62 | return $this;
63 | }
64 |
65 | /**
66 | * Track a photo download.
67 | * @link https://unsplash.com/documentation#track-a-photo-download
68 | *
69 | * @param string $id
70 | */
71 | public function trackPhotoDownload($id): self
72 | {
73 | $this->apiCall = [
74 | 'endpoint' => "photos/{$id}/download",
75 | ];
76 |
77 | return $this;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/Endpoints/Search.php:
--------------------------------------------------------------------------------
1 | apiCall = [
15 | 'endpoint' => 'search/photos',
16 | ];
17 |
18 | return $this;
19 | }
20 |
21 | /**
22 | * Search collections
23 | * Get a single page of collection results for a query.
24 | * @link https://unsplash.com/documentation#search-collections
25 | */
26 | public function searchCollections(): self
27 | {
28 | $this->apiCall = [
29 | 'endpoint' => 'search/collections',
30 | ];
31 |
32 | return $this;
33 | }
34 |
35 | /**
36 | * Search users
37 | * Get a single page of user results for a query.
38 | * @link https://unsplash.com/documentation#search-users
39 | */
40 | public function searchUsers(): self
41 | {
42 | $this->apiCall = [
43 | 'endpoint' => 'search/users',
44 | ];
45 |
46 | return $this;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Endpoints/Stats.php:
--------------------------------------------------------------------------------
1 | apiCall = [
15 | 'endpoint' => 'stats/total',
16 | ];
17 |
18 | return $this;
19 | }
20 |
21 | /**
22 | * Month
23 | * Get the overall Unsplash stats for the past 30 days.
24 | * @link https://unsplash.com/documentation#month
25 | */
26 | public function monthlyStats(): self
27 | {
28 | $this->apiCall = [
29 | 'endpoint' => 'stats/month',
30 | ];
31 |
32 | return $this;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/Endpoints/Topics.php:
--------------------------------------------------------------------------------
1 | apiCall = [
15 | 'endpoint' => 'topics',
16 | ];
17 |
18 | return $this;
19 | }
20 |
21 | /**
22 | * Get a topic
23 | * Retrieve a single topic.
24 | * @link https://unsplash.com/documentation#get-a-topic
25 | *
26 | * @param int|string $id The topic’s ID or slug. Required.
27 | */
28 | public function showTopic($id): self
29 | {
30 | $this->apiCall = [
31 | 'endpoint' => "topics/{$id}",
32 | ];
33 |
34 | return $this;
35 | }
36 |
37 | /**
38 | * Get a topic photos
39 | * Retrieve a topic’s photos.
40 | * @link https://unsplash.com/documentation#get-a-topics-photos
41 | *
42 | * @param int|string $id The topic’s ID or slug. Required.
43 | */
44 | public function showTopicPhotos($id): self
45 | {
46 | $this->apiCall = [
47 | 'endpoint' => "topics/{$id}/photos",
48 | ];
49 |
50 | return $this;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Endpoints/Users.php:
--------------------------------------------------------------------------------
1 | apiCall = [
17 | 'endpoint' => "users/{$username}",
18 | ];
19 |
20 | return $this;
21 | }
22 |
23 | /**
24 | * Get a user’s portfolio link
25 | * Retrieve a single user’s portfolio link.
26 | * @link https://unsplash.com/documentation#get-a-users-portfolio-link
27 | *
28 | * @param string $username The user’s username. Required.
29 | */
30 | public function userPortfolio($username): self
31 | {
32 | $this->apiCall = [
33 | 'endpoint' => "users/{$username}/portfolio",
34 | ];
35 |
36 | return $this;
37 | }
38 |
39 | /**
40 | * List a user’s photos
41 | * Get a list of photos uploaded by a user.
42 | * @link https://unsplash.com/documentation#list-a-users-photos
43 | *
44 | * @param string $username The user’s username. Required.
45 | */
46 | public function userPhotos($username): self
47 | {
48 | $this->apiCall = [
49 | 'endpoint' => "users/{$username}/photos",
50 | ];
51 |
52 | return $this;
53 | }
54 |
55 | /**
56 | * List a user’s liked photos
57 | * Get a list of photos liked by a user.
58 | * @link https://unsplash.com/documentation#list-a-users-liked-photos
59 | *
60 | * @param string $username The user’s username. Required.
61 | */
62 | public function userLikes($username)
63 | {
64 | $this->apiCall = [
65 | 'endpoint' => "users/{$username}/likes",
66 | ];
67 |
68 | return $this;
69 | }
70 |
71 | /**
72 | * List a user’s collections
73 | * Get a list of collections created by the user.
74 | * @link https://unsplash.com/documentation#list-a-users-collections
75 | *
76 | * @param string $username The user’s username. Required.
77 | */
78 | public function userCollections($username)
79 | {
80 | $this->apiCall = [
81 | 'endpoint' => "users/{$username}/collections",
82 | ];
83 |
84 | return $this;
85 | }
86 |
87 | /**
88 | * Get a user’s statistics
89 | * Retrieve the consolidated number of downloads, views and likes of all user’s photos,
90 | * as well as the historical breakdown and average of these stats in a specific timeframe (default is 30 days).
91 | * @link https://unsplash.com/documentation#get-a-users-statistics
92 | *
93 | * @param string $username The user’s username. Required.
94 | */
95 | public function userStatistics($username)
96 | {
97 | $this->apiCall = [
98 | 'endpoint' => "users/{$username}/statistics",
99 | ];
100 |
101 | return $this;
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/Facades/Unsplash.php:
--------------------------------------------------------------------------------
1 | initalizeConfiguration()
23 | ->createClient();
24 |
25 | return $this;
26 | }
27 |
28 | /**
29 | * Initalize and store configuration values in class properties.
30 | */
31 | private function initalizeConfiguration(): self
32 | {
33 | $this->accessKey = config('unsplash.access_key');
34 |
35 | if (! $this->accessKey) {
36 | throw new Exception('A Unsplash-API access key must be provided');
37 | }
38 |
39 | return $this;
40 | }
41 |
42 | /**
43 | * Instantiate the GuzzleHttp Client.
44 | */
45 | private function createClient(): self
46 | {
47 | $this->client = new Client([
48 | 'base_uri' => self::API_URL,
49 | 'headers' => [
50 | 'Content-Type' => 'application/x-www-form-urlencoded',
51 | 'Authorization' => "Client-ID {$this->accessKey}",
52 | ],
53 | ]);
54 |
55 | return $this;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/Models/UnsplashAsset.php:
--------------------------------------------------------------------------------
1 | exists("{$unsplashAsset->name}")) {
29 | Storage::disk(config('unsplash.disk', 'local'))->delete("{$unsplashAsset->name}");
30 | }
31 |
32 | DB::delete('delete from unsplashables where unsplash_asset_id = ?', [$unsplashAsset->id]);
33 | });
34 | }
35 |
36 | /**
37 | * Get all unsplashables by given model.
38 | */
39 | public function assets(Model $model): \Illuminate\Database\Eloquent\Relations\MorphToMany
40 | {
41 | return $this->morphedByMany($model, 'unsplashables');
42 | }
43 |
44 | /**
45 | * Creates a new instance of the unsplash api client.
46 | */
47 | public static function api(): Unsplash
48 | {
49 | return new Unsplash();
50 | }
51 |
52 | /**
53 | * Returns a complete copyright link for a given data set.
54 | */
55 | public function getFullCopyrightLink(): string
56 | {
57 | return "Photo by {$this->author} on Unsplash";
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/Queries/QueryBuilder.php:
--------------------------------------------------------------------------------
1 | query['page'] = $param ?? null;
18 |
19 | return $this;
20 | }
21 |
22 | /**
23 | * Number of items per page.
24 | * @param int|string $param
25 | */
26 | public function perPage($param = null): self
27 | {
28 | $this->query['per_page'] = $param ?? null;
29 |
30 | return $this;
31 | }
32 |
33 | /**
34 | * How to sort the photos.
35 | * @param int|string $param Valid values: latest, oldest, popular
36 | */
37 | public function orderBy($param = null): self
38 | {
39 | $this->query['order_by'] = $param ?? null;
40 |
41 | return $this;
42 | }
43 |
44 | /* ###### Random photos params ###### */
45 |
46 | /**
47 | * Public collection ID(‘s) to filter selection. If multiple, comma-separated.
48 | * @param string $param
49 | */
50 | public function collections($param = null): self
51 | {
52 | $this->query['collections'] = $param ?? null;
53 |
54 | return $this;
55 | }
56 |
57 | /**
58 | * Limit selection to featured photos.
59 | * @param string $param
60 | */
61 | public function featured($param = null): self
62 | {
63 | $this->query['featured'] = $param ?? null;
64 |
65 | return $this;
66 | }
67 |
68 | /**
69 | * Limit selection to a single user.
70 | * @param string $param
71 | */
72 | public function username($param = null): self
73 | {
74 | $this->query['username'] = $param ?? null;
75 |
76 | return $this;
77 | }
78 |
79 | /**
80 | * Filter search results by photo orientation.
81 | * @param string $param Valid values: landscape, portrait, and squarish
82 | */
83 | public function orientation($param = null): self
84 | {
85 | $this->query['orientation'] = $param ?? null;
86 |
87 | return $this;
88 | }
89 |
90 | /**
91 | * Limit selection to photos matching a search term.
92 | * @param string $param
93 | */
94 | public function term($param = null): self
95 | {
96 | $this->query['query'] = $param ?? null;
97 |
98 | return $this;
99 | }
100 |
101 | /**
102 | * The number of photos to return.
103 | * @param int|string $param min 1, max 30
104 | */
105 | public function count($param = null): self
106 | {
107 | $this->query['count'] = $param ?? null;
108 |
109 | return $this;
110 | }
111 |
112 | /* ###### Photos Statistics params ###### */
113 |
114 | /**
115 | * The public id of the photo.
116 | * @param int|string $param required
117 | */
118 | public function id($param = null): self
119 | {
120 | $this->query['id'] = $param ?? null;
121 |
122 | return $this;
123 | }
124 |
125 | /**
126 | * The frequency of the stats.
127 | * @param string $param default days
128 | */
129 | public function resolution($param = null): self
130 | {
131 | $this->query['resolution'] = $param ?? null;
132 |
133 | return $this;
134 | }
135 |
136 | /**
137 | * The amount of for each stat.
138 | * @param int|string $param
139 | */
140 | public function quantity($param = null): self
141 | {
142 | $this->query['quantity'] = $param ?? null;
143 |
144 | return $this;
145 | }
146 |
147 | /* ###### Search photos params ###### */
148 |
149 | /**
150 | * Filter results by color.
151 | * @param string $param Valid values are: black_and_white, black, white, yellow, orange, red, purple, magenta, green, teal, and blue.
152 | */
153 | public function color($param = null): self
154 | {
155 | $this->query['color'] = $param ?? null;
156 |
157 | return $this;
158 | }
159 |
160 | /**
161 | * Query for search terms.
162 | * @param string $param
163 | */
164 | public function query($param = null): self
165 | {
166 | $this->query['query'] = $param ?? null;
167 |
168 | return $this;
169 | }
170 |
171 | /* ###### Topics params ###### */
172 |
173 | /**
174 | * Query for ids.
175 | * @param string $param
176 | */
177 | public function ids($param = null): self
178 | {
179 | $this->query['ids'] = $param ?? null;
180 |
181 | return $this;
182 | }
183 |
184 | public function getQuery(): string
185 | {
186 | return http_build_query($this->query, '', '&');
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/src/Traits/HasUnsplashables.php:
--------------------------------------------------------------------------------
1 | unsplash()->detach();
19 | });
20 | }
21 |
22 | /**
23 | * Model may have multiple unsplash assets.
24 | */
25 | public function unsplash(): \Illuminate\Database\Eloquent\Relations\MorphToMany
26 | {
27 | return $this->morphToMany(UnsplashAsset::class, 'unsplashables');
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/Unsplash.php:
--------------------------------------------------------------------------------
1 | initalizeConfiguration();
50 |
51 | return $this;
52 | }
53 |
54 | /**
55 | * Checks if the accessed property exists as a method
56 | * if exists, call the get() method and return the complete response.
57 | */
58 | public function __get($param)
59 | {
60 | if (method_exists($this, $param)) {
61 | return $this->$param()->get();
62 | }
63 | }
64 |
65 | /**
66 | * Returns the full http response.
67 | */
68 | public function get(): \GuzzleHttp\Psr7\Response
69 | {
70 | $this->buildResponse();
71 |
72 | return $this->response;
73 | }
74 |
75 | /**
76 | * Returns the http response body.
77 | */
78 | public function toJson(): mixed
79 | {
80 | $this->buildResponse();
81 |
82 | return json_decode($this->response->getBody()->getContents());
83 | }
84 |
85 | /**
86 | * Returns the http response body.
87 | */
88 | public function toArray(): array
89 | {
90 | $this->buildResponse();
91 |
92 | return json_decode($this->response->getBody()->getContents(), true);
93 | }
94 |
95 | /**
96 | * Returns the http response body as collection.
97 | */
98 | public function toCollection(): \Illuminate\Support\Collection
99 | {
100 | $this->buildResponse();
101 |
102 | return collect(json_decode($this->response->getBody()->getContents(), true));
103 | }
104 |
105 | /**
106 | * Stores the retrieving photo in the storage.
107 | *
108 | * @param string $name If no name is provided, a random 24 Charachter name will be generated
109 | * @param string $key Defines the size of the retrieving photo
110 | * @return string|UnsplashAsset If UNSPLASH_STORE_IN_DATABASE is set to true it returns an instance of UnsplashAsset otherwise a string of the name of the stored image
111 | */
112 | public function store($name = null, $key = 'small'): string | UnsplashAsset
113 | {
114 | $response = $this->toArray();
115 | if (! array_key_exists('urls', $response)) {
116 | throw new Exception('Photo can not be stored. Certainly the "urls" key is missing or you try to store an photo while retrieving multiple photos.');
117 | }
118 |
119 | if (! in_array($key, self::PHOTO_KEYS)) {
120 | throw new Exception("Your provided key \"{$key}\" is an undefined accessor.");
121 | }
122 |
123 | $name = $name ?? Str::random(24);
124 | $image = file_get_contents($response['urls'][$key]);
125 |
126 | while ($this->storage->exists("{$name}.jpg")) {
127 | $name = Str::random(24);
128 | }
129 |
130 | $this->storage->put("{$name}.jpg", $image);
131 |
132 | if ($this->storeInDatabase) {
133 | return UnsplashAsset::create([
134 | 'unsplash_id' => $response['id'],
135 | 'name' => "{$name}.jpg",
136 | 'author' => $response['user']['name'],
137 | 'author_link' => $response['user']['links']['html'],
138 | ]);
139 | }
140 |
141 | return $name;
142 | }
143 |
144 | /**
145 | * Builds the http request.
146 | */
147 | protected function buildResponse(): self
148 | {
149 | $verb = $this->apiCall['verb'] ?? 'get';
150 | $this->response = $this->client->$verb("{$this->apiCall['endpoint']}?{$this->getQuery()}");
151 |
152 | return $this;
153 | }
154 |
155 | /**
156 | * Initalize storage.
157 | */
158 | private function initalizeConfiguration(): self
159 | {
160 | $this->storage = Storage::disk(config('unsplash.disk', 'local'));
161 | $this->storeInDatabase = config('unsplash.store_in_database', false);
162 |
163 | return $this;
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/src/UnsplashServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->runningInConsole()) {
18 | $this->publishes([
19 | __DIR__.'/../config/unsplash.php' => config_path('unsplash.php'),
20 | ], 'config');
21 |
22 | $this->publishes([
23 | __DIR__.'/../database/migrations/create_unsplashables_table.php.stub' => database_path('migrations').'/'.date('Y_m_d_His').'_create_unsplashables_table.php',
24 | ], 'migrations');
25 | $this->publishes([
26 | __DIR__.'/../database/migrations/create_unsplash_assets_table.php.stub' => database_path('migrations').'/'.date('Y_m_d_His').'_create_unsplash_assets_table.php',
27 | ], 'migrations');
28 | }
29 | }
30 |
31 | /**
32 | * Register the application services.
33 | */
34 | public function register()
35 | {
36 | // Automatically apply the package configuration
37 | $this->mergeConfigFrom(__DIR__.'/../config/unsplash.php', 'unsplash');
38 |
39 | // Bind main class to service container
40 | $this->app->bind(Unsplash::class, function () {
41 | return new Unsplash();
42 | });
43 | }
44 | }
45 |
--------------------------------------------------------------------------------