### Install Laravel-Unsplash Package Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Installs the Laravel-Unsplash package using Composer. This is the first step to integrate Unsplash API functionalities into your Laravel application. ```bash composer require xchimx/laravel-unsplash ``` -------------------------------- ### Search Photos with Laravel-Unsplash Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md An example controller method that searches for photos based on a user-provided query, defaulting to 'Nature'. It utilizes the Unsplash facade for searching. ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Xchimx\UnsplashApi\Facades\Unsplash; class UnsplashController extends Controller { public function search(Request $request) { $query = $request->input('query', 'Nature'); $photos = Unsplash::searchPhotos($query); return view('unsplash.search', compact('photos', 'query')); } } ``` -------------------------------- ### GET /collections Source: https://context7.com/xchimx/laravel-unsplash/llms.txt List all public collections with pagination. ```APIDOC ## GET /collections ### Description List all public collections with pagination. ### Method GET ### Endpoint `/collections` ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number of results to retrieve. - **per_page** (integer) - Optional - The number of results per page (defaults to 15). ### Response #### Success Response (200) - **id** (integer) - The collection's unique identifier. - **title** (string) - The title of the collection. - **description** (string) - A description of the collection. - **total_photos** (integer) - The total number of photos in the collection. - **cover_photo** (object) - Information about the cover photo of the collection. - **user** (object) - Information about the user who created the collection. - **name** (string) - The user's name. #### Response Example ```json [ { "id": 296, "title": "I like a man with a beard.", "description": "Beards, bears, and men.", "total_photos": 12, "cover_photo": { ... }, "user": { "name": "Jane Doe" } } // ... more collections ] ``` ``` -------------------------------- ### Handle Unsplash API Errors Gracefully (PHP) Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Provides an example of how to implement error handling for Unsplash API calls using a try-catch block. This allows for logging errors or displaying user-friendly messages when communication with the API fails. ```php public function search(Request $request) { try { $photos = Unsplash::searchPhotos('Nature'); } catch (\Exception $e) { // Log the error or display a user-friendly message return back()->withErrors('There was a problem communicating with the Unsplash API.'); } return view('unsplash.search', compact('photos')); } ``` -------------------------------- ### GET /photos/{id}/download Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Get the download URL for a photo (triggers Unsplash download tracking). ```APIDOC ## GET /photos/{id}/download ### Description Get the download URL for a photo. This endpoint triggers Unsplash's download tracking mechanism. It's recommended to use this before initiating a download to comply with API guidelines. ### Method GET ### Endpoint `/photos/{id}/download` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the photo to download. ### Response #### Success Response (200) - **photo_id** (string) - The unique identifier of the photo. - **download_url** (string) - The URL from which the photo can be downloaded. #### Response Example ```json { "photo_id": "Dwu85P9SOIk", "download_url": "https://unsplash.com/photos/Dwu85P9SOIk/download?force=true" } ``` ``` -------------------------------- ### Get Photo Download Link Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Generates a direct download link for a specific photo using its ID. This controller fetches the download URL via the Unsplash facade and then redirects the user to that URL. It requires a photo ID as input. ```php namespace App\Http\Controllers; use Xchimx\UnsplashApi\Facades\Unsplash; class UnsplashController extends Controller { public function download($id) { $downloadUrl = Unsplash::getPhotoDownloadLink($id); return redirect($downloadUrl); } } ``` -------------------------------- ### GET /photos/{id} Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Retrieve a single photo by its unique ID with full metadata. ```APIDOC ## GET /photos/{id} ### Description Retrieve a single photo by its unique ID with full metadata. ### Method GET ### Endpoint `/photos/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the photo. ### Response #### Success Response (200) - **id** (string) - The photo's unique identifier. - **width** (integer) - The photo's width in pixels. - **height** (integer) - The photo's height in pixels. - **color** (string) - The dominant color of the photo. - **description** (string) - The photo's description. - **alt_description** (string) - Alternative description for accessibility. - **urls** (object) - Object containing different URL formats for the photo. - **raw** (string) - URL for the original image. - **full** (string) - URL for the full-size image. - **regular** (string) - URL for a regular-size image. - **small** (string) - URL for a small-size image. - **thumb** (string) - URL for a thumbnail image. - **user** (object) - Information about the photo's uploader. - **name** (string) - The user's name. - **username** (string) - The user's username. - **portfolio_url** (string) - The user's portfolio URL. - **exif** (object) - Exchangeable image file format data. - **make** (string) - Camera manufacturer. - **model** (string) - Camera model. - **location** (object) - The location where the photo was taken. - **city** (string) - The city. - **country** (string) - The country. #### Response Example ```json { "id": "Dwu85P9SOIk", "width": 2448, "height": 3264, "color": "#6E633A", "description": "A scenic view...", "alt_description": "Mountain landscape", "urls": { "raw": "https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max", "full": "https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max", "regular": "https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max", "small": "https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max", "thumb": "https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max" }, "user": { "name": "John Doe", "username": "johndoe", "portfolio_url": "https://example.com/johndoe" }, "exif": { "make": "Canon", "model": "EOS 5D" }, "location": { "city": "Denver", "country": "USA" } } ``` ``` -------------------------------- ### GET /photos/random Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Fetch a random photo, optionally filtered by query, collections, or topics. ```APIDOC ## GET /photos/random ### Description Fetch a random photo, optionally filtered by query, collections, or topics. ### Method GET ### Endpoint `/photos/random` ### Parameters #### Query Parameters - **query** (string) - Optional - Search term to filter random photos. - **collections** (string) - Optional - Comma-separated list of collection IDs to filter by. - **content_filter** (string) - Optional - Filter for 'low' or 'high' quality adult content. - **orientation** (string) - Optional - Orientation of the photo (e.g., 'landscape', 'portrait', 'squarish'). ### Response #### Success Response (200) - **id** (string) - The photo's unique identifier. - **urls** (object) - Object containing different URL formats for the photo. - **regular** (string) - URL for a regular-size image. - **user** (object) - Information about the photo's uploader. - **name** (string) - The user's name. - **links** (object) - Links related to the photo. - **download_location** (string) - URL to get the download location. #### Response Example (Filtered) ```json { "id": "some_random_photo_id", "urls": { "regular": "https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max" }, "user": { "name": "Random Photographer" }, "links": { "download_location": "https://api.unsplash.com/photos/some_random_photo_id/download" } } ``` ``` -------------------------------- ### Get User Information Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Fetches information about a specific Unsplash user based on their username. This controller utilizes the Unsplash facade and passes the user data to a 'user' Blade view. It requires the username as a parameter. ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Xchimx\UnsplashApi\Facades\Unsplash; class UserController extends Controller { public function user($username, Request $request) { $user = Unsplash::getUser($name); // Note: 'name' should likely be '$username' return view('user', compact('user')); } } ``` -------------------------------- ### Get User Photos Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Retrieves a list of photos uploaded by a specific Unsplash user, with pagination support. It takes the username, a limit per page (hardcoded to 15), and the page number as input. The photos and username are passed to a Blade view. Requires the Request and Unsplash facades. ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Xchimx\UnsplashApi\Facades\Unsplash; class UserController extends Controller { public function photos($username, Request $request) { $page = $request->input('page', 1); $photos = Unsplash::getUserPhotos($username, 15, $page); return view('users.photos', compact('photos', 'username')); } } ``` ```bladehtml @extends('layouts.app') @section('content')
{{ $photo['description'] ?? 'No description' }}
{{ $photo['description'] ?? 'No description available.' }}
@endsection ``` -------------------------------- ### Get a Random Photo Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Retrieves a random photo from Unsplash. This function uses the Unsplash facade to fetch the photo and then renders it using a dedicated Blade view. No specific input is required, and the output is a single photo object. ```php namespace App\Http\Controllers; use Xchimx\UnsplashApi\Facades\Unsplash; class RandomPhotoController extends Controller { public function show() { $photo = Unsplash::getRandomPhoto(); return view('photos.random', compact('photo')); } } ``` ```bladehtml @extends('layouts.app') @section('content')Photo by {{ $photo['user']['name'] }}
@endsection ``` -------------------------------- ### Get a Specific Collection by ID Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Retrieves details for a specific Unsplash collection using its ID. This controller uses the Unsplash facade to fetch the collection data and then renders it in a dedicated Blade view. It requires the collection ID as a parameter. ```php namespace App\Http\Controllers; use Xchimx\UnsplashApi\Facades\Unsplash; class CollectionController extends Controller { public function show($id) { $collection = Unsplash::getCollection($id); return view('collections.show', compact('collection')); } } ``` ```bladehtml @extends('layouts.app') @section('content'){{ $collection['description'] ?? 'No description available.' }}
@endsection ``` -------------------------------- ### Get Photo Download Link (PHP) Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Provides the download URL for a specific photo, which is essential for triggering Unsplash's download tracking mechanism. This method must be used before initiating a download to comply with Unsplash API guidelines. It includes error handling for cases where the download URL cannot be retrieved. ```php withErrors('Download URL not available.'); } catch (\Exception $e) { return back()->withErrors('Failed to get download link.'); } } public function getDownloadInfo(string $id) { $downloadUrl = Unsplash::getPhotoDownloadLink($id); return response()->json([ 'photo_id' => $id, 'download_url' => $downloadUrl ]); } } ``` -------------------------------- ### Get Collection Details by ID (PHP) Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Fetches detailed information about a specific Unsplash collection using its unique ID. It handles potential exceptions and returns a view with the collection data or a 404 error if not found. Dependencies include the Unsplash facade. ```php 296, // 'title' => 'I like a man with a beard.', // 'description' => 'Beards, bears, and men.', // 'published_at' => '2016-01-12T18:16:09-05:00', // 'total_photos' => 12, // 'private' => false, // 'cover_photo' => [...], // 'user' => ['name' => 'Jane Doe', 'username' => 'janedoe', ...], // 'links' => ['self' => '...', 'html' => '...', 'photos' => '...'] // ] return view('collections.show', compact('collection')); } catch (\Exception $e) { abort(404, 'Collection not found'); } } } ``` -------------------------------- ### Get User Profile by Username (PHP) Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Retrieves the public profile information for a given Unsplash user identified by their username. This function includes error handling for cases where the user is not found, returning a 404 error. It depends on the Unsplash facade for API interaction. ```php 'pXhwzz1JtQU', // 'username' => 'johndoe', // 'name' => 'John Doe', // 'bio' => 'Photographer based in NYC', // 'location' => 'New York', // 'total_photos' => 45, // 'total_collections' => 3, // 'profile_image' => ['small' => '...', 'medium' => '...', 'large' => '...'], // 'links' => ['self' => '...', 'html' => '...', 'photos' => '...'] // ] return view('users.show', compact('user')); } catch (\Exception $e) { abort(404, 'User not found'); } } } ``` -------------------------------- ### Basic Unsplash Service Usage in Laravel Controller Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Demonstrates how to use the UnsplashService in a Laravel controller by injecting it via Dependency Injection. It fetches nature photos and passes them to a view. ```php use Xchimx\UnsplashApi\UnsplashService; class UnsplashController extends Controller { protected $unsplashService; public function __construct(UnsplashService $unsplashService) { $this->unsplashService = $unsplashService; } public function search() { $photos = $this->unsplashService->searchPhotos('Nature'); return view('unsplash.search', compact('photos')); } } ``` -------------------------------- ### Unsplash Facade Usage in Laravel Controller Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Shows an alternative way to use the Unsplash API in a Laravel controller using the provided Unsplash facade. This method simplifies direct access to Unsplash functionalities. ```php use Xchimx\UnsplashApi\Facades\Unsplash; class UnsplashController extends Controller { public function search() { $photos = Unsplash::searchPhotos('Nature'); return view('unsplash.search', compact('photos')); } } ``` -------------------------------- ### Configure Unsplash API Key and Rate Limiting Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Sets the Unsplash API Access Key and optional rate limiting settings in the .env file. Ensure you replace 'your_unsplash_access_key' with your actual key. ```php UNSPLASH_ACCESS_KEY=your_unsplash_access_key UNSPLASH_RATE_LIMITING_ENABLED=true UNSPLASH_RATE_LIMITING_THRESHOLD=10 ``` -------------------------------- ### Apply Rate Limiting Middleware to Routes (PHP) Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Illustrates how to apply the 'unsplash.rate_limit' middleware to specific routes within a Laravel application. This ensures that routes protected by this middleware will adhere to the configured Unsplash API rate limits. ```php Route::middleware(['unsplash.rate_limit'])->group(function () { Route::get('/unsplash/search', [UnsplashController::class, 'search'])->name('unsplash.search'); // Other routes... }); ``` -------------------------------- ### Configure Unsplash API Rate Limiting (PHP) Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Shows how to configure the rate limiting middleware for the Unsplash API package. This includes enabling/disabling the middleware and setting a threshold for remaining requests before intervention. ```php 'rate_limiting' => [ 'enabled' => env('UNSPLASH_RATE_LIMITING_ENABLED', true), 'threshold' => env('UNSPLASH_RATE_LIMITING_THRESHOLD', 10), ] ``` -------------------------------- ### Search Photos with Custom Timeout (PHP) Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Demonstrates how to search for photos using the Unsplash API facade and set a custom timeout option for the HTTP request. This is useful for controlling the maximum time spent waiting for a response from the API. ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Xchimx\UnsplashApi\Facades\Unsplash; class CollectionController extends Controller { public function searchWithTimeout(Request $request) { // Use withOptions to set custom Guzzle options, e.g., timeout $photos = Unsplash::withOptions(['timeout' => 2])->searchPhotos('Nature'); return view('unsplash.search', compact('photos')); } } ``` -------------------------------- ### Publish Laravel-Unsplash Configuration Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Publishes the configuration file for the Laravel-Unsplash package using the Artisan CLI. This allows you to customize package settings. ```php php artisan vendor:publish --provider="Xchimx\UnsplashApi\UnsplashServiceProvider" --tag="config" ``` -------------------------------- ### List Collections Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md Fetches a list of Unsplash collections, allowing for pagination. It takes an optional page number and a limit per page (hardcoded to 15). The results are passed to a Blade view for display. Requires the Request facade and Unsplash facade. ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Xchimx\UnsplashApi\Facades\Unsplash; class CollectionController extends Controller { public function index(Request $request) { $page = $request->input('page', 1); $collections = Unsplash::listCollections(15, $page); return view('collections.index', compact('collections')); } } ``` ```bladehtml @extends('layouts.app') @section('content'){{ $photo['description'] ?? 'No description available.' }}
@endsection ``` -------------------------------- ### Use Unsplash Service via Dependency Injection in Laravel Controller Source: https://context7.com/xchimx/laravel-unsplash/llms.txt Demonstrates how to inject the UnsplashService into a Laravel controller for accessing Unsplash API functionalities. This approach promotes cleaner code and better testability compared to using facades. ```php unsplash = $unsplash; } public function search(Request $request) { $query = $request->input('query', 'nature'); $photos = $this->unsplash->searchPhotos($query, 15, 1); return view('photos.search', ['photos' => $photos['results']]); } public function featured() { // Access rate limit headers from the last request $photos = $this->unsplash->searchPhotos('featured', 10); $headers = $this->unsplash->getLastResponseHeaders(); $rateLimit = $headers['X-Ratelimit-Limit'][0] ?? 'unknown'; $remaining = $headers['X-Ratelimit-Remaining'][0] ?? 'unknown'; return response()->json([ 'photos' => $photos['results'], 'rate_limit' => $rateLimit, 'remaining' => $remaining ]); } } ``` -------------------------------- ### Display Search Results for Collections (Blade) Source: https://github.com/xchimx/laravel-unsplash/blob/main/readme.md A Blade template snippet for displaying search results of Unsplash collections. It iterates through the 'results' array, showing the collection title, description, and a link to view associated photos. ```bladehtml @extends('layouts.app') @section('content'){{ $collection['description'] ?? 'No description' }}
View Photos @endforeach @endsection{{ $collection['description'] ?? 'No description' }}
View Photos @endforeach @endsection