Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Unsplash Laravel Package

mahdimajidzadeh/laravel-unsplash

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mahdimajidzadeh/laravel-unsplash
    

    For Laravel <5.5, add the service provider to config/app.php:

    MahdiMajidzadeh\LaravelUnsplash\LaravelUnsplashServiceProvider::class
    
  2. Publish Config:

    php artisan vendor:publish --provider="MahdiMajidzadeh\LaravelUnsplash\LaravelUnsplashServiceProvider"
    

    Configure your Unsplash API credentials in config/unsplash.php (default: APP_UNSPLASH_ACCESS_KEY).

  3. 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
    

Implementation Patterns

Core Workflows

  1. Photo Retrieval:

    • Collections: Use photos($params) for search results (e.g., ['query' => 'nature']).
    • Single Photo: Fetch by ID with single($id) (e.g., for a detail page).
    • Random Photos: Ideal for placeholders or dynamic backgrounds:
      $randomPhoto = (new Photo())->random(['collections' => 123])->get();
      
  2. 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
    
  3. Download Links: Generate direct download URLs for user uploads (e.g., in a media manager):

    $downloadLink = (new Photo())->download($photoId);
    
  4. Statistics: Track engagement for a specific photo (e.g., analytics dashboard):

    $stats = (new Photo())->statistic($photoId)->get();
    

Advanced Patterns

  • 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);
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

  2. Missing alt_description:

    • ~10% of photos lack descriptive alt text. Handle this gracefully:
      $altText = $photo->alt_description ?? 'Beautiful image';
      
  3. Deprecated Methods:

    • The package lacks type hints and may not support newer Unsplash API endpoints (last updated 2022). Verify endpoints against Unsplash’s docs.
  4. Configuration Overrides:

    • The published config file (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',
      ],
      

Debugging Tips

  1. Inspect Raw API Responses: Use getArray() to debug the raw response structure:

    $rawData = (new Photo())->photos(['query' => 'test'])->getArray();
    dd($rawData);
    
  2. 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()]);
    });
    
  3. 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()]
    );
    

Extension Points

  1. 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);
        }
    }
    
  2. 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();
    }
    
  3. 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);
    }
    
  4. Collection Macros: Add custom methods to Unsplash collections:

    // In a service provider
    Unsplash::macro('filterByColor', function ($color) {
        return $this->where('color', $color);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle