Installation:
composer require mahdimajidzadeh/laravel-unsplash
For Laravel <5.5, add the service provider to config/app.php:
MahdiMajidzadeh\LaravelUnsplash\LaravelUnsplashServiceProvider::class
Publish Config:
php artisan vendor:publish --provider="MahdiMajidzadeh\LaravelUnsplash\LaravelUnsplashServiceProvider"
Configure your Unsplash API credentials in config/unsplash.php (default: APP_UNSPLASH_ACCESS_KEY).
First Use Case: Fetch curated photos (e.g., for a "Featured Images" section):
use MahdiMajidzadeh\LaravelUnsplash\Photo;
$photos = (new Photo())->curated(['per_page' => 5])->get();
// Returns a collection of curated photo models
Photo Retrieval:
photos($params) for search results (e.g., ['query' => 'nature']).single($id) (e.g., for a detail page).$randomPhoto = (new Photo())->random(['collections' => 123])->get();
Integration with Blade:
// In a controller
$featuredPhotos = (new Photo())->curated(['per_page' => 3])->get();
// In Blade
@foreach($featuredPhotos as $photo)
<img src="{{ $photo->urls->raw }}" alt="{{ $photo->alt_description }}">
@endforeach
Download Links: Generate direct download URLs for user uploads (e.g., in a media manager):
$downloadLink = (new Photo())->download($photoId);
Statistics: Track engagement for a specific photo (e.g., analytics dashboard):
$stats = (new Photo())->statistic($photoId)->get();
Caching Responses: Cache API responses for 1 hour (adjust TTL as needed):
$photos = Cache::remember("unsplash_curated_{$params}", now()->addHours(1), function() use ($params) {
return (new Photo())->curated($params)->getArray();
});
Service Layer Abstraction: Create a dedicated service class to encapsulate Unsplash logic:
class UnsplashService {
public function getFeaturedImages(int $limit = 5) {
return (new Photo())->curated(['per_page' => $limit])->get();
}
}
Error Handling: Wrap API calls in a try-catch to handle rate limits or invalid responses:
try {
$photo = (new Photo())->single($id)->get();
} catch (\Exception $e) {
Log::error("Unsplash API Error: " . $e->getMessage());
return response()->view('errors.unsplash', [], 500);
}
Rate Limiting:
photos() or random().Missing alt_description:
$altText = $photo->alt_description ?? 'Beautiful image';
Deprecated Methods:
Configuration Overrides:
config/unsplash.php) may not include all possible params. Extend it manually if needed:
'default_params' => [
'client_id' => env('APP_UNSPLASH_ACCESS_KEY'),
'w' => 1080, // Default width for images
'fit' => 'crop',
],
Inspect Raw API Responses:
Use getArray() to debug the raw response structure:
$rawData = (new Photo())->photos(['query' => 'test'])->getArray();
dd($rawData);
Logging API Calls: Add a middleware to log Unsplash requests (useful for debugging rate limits):
// In AppServiceProvider
Unsplash::onRequest(function ($request) {
Log::debug('Unsplash Request:', ['params' => $request->query(), 'url' => $request->url()]);
});
Handling Pagination:
The package returns a simple Collection. For complex pagination, use Laravel’s Paginator:
$photos = (new Photo())->photos(['page' => 1, 'per_page' => 12])->getArray();
$paginated = new LengthAwarePaginator(
collect($photos['results']),
$photos['total'],
$photos['per_page'],
$photos['page'],
['path' => request()->url()]
);
Custom Endpoints:
Extend the Photo class to support unsupported endpoints (e.g., users/photos):
namespace App\Services;
use MahdiMajidzadeh\LaravelUnsplash\Photo as BasePhoto;
class ExtendedPhoto extends BasePhoto {
public function userPhotos(string $username, array $params = []) {
return $this->get("users/{$username}/photos", $params);
}
}
Model Binding: Bind Unsplash photos to Eloquent models for seamless ORM integration:
// In a model
public function getUnsplashPhotoAttribute() {
return (new Photo())->single($this->unsplash_id)->get();
}
WebP Support:
Add WebP format support by extending the urls property:
// In a service or accessor
public function getWebpUrlAttribute() {
return str_replace('jpg', 'webp', $this->urls->raw);
}
Collection Macros: Add custom methods to Unsplash collections:
// In a service provider
Unsplash::macro('filterByColor', function ($color) {
return $this->where('color', $color);
});
How can I help you explore Laravel packages today?