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

Filament Unsplash Picker Laravel Package

mansoor/filament-unsplash-picker

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mansoor/filament-unsplash-picker
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Mansoor\FilamentUnsplashPicker\FilamentUnsplashPickerServiceProvider"
    
  2. Configure Unsplash API Add your Unsplash client_id to .env:

    UNSPLASH_CLIENT_ID=your_unsplash_client_id_here
    

    Ensure it’s reflected in config/services.php:

    'unsplash' => [
        'client_id' => env('UNSPLASH_CLIENT_ID'),
    ],
    
  3. First Use Case Attach the picker to a Filament form field in a resource:

    use Mansoor\FilamentUnsplashPicker\Fields\UnsplashPicker;
    
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                UnsplashPicker::make('image')
                    ->label('Unsplash Image')
                    ->required(),
            ]);
    }
    

Implementation Patterns

Common Workflows

  1. Basic Image Selection Use the UnsplashPicker field directly in a Filament form:

    UnsplashPicker::make('hero_image')
        ->label('Hero Banner')
        ->columnSpanFull()
        ->required();
    
  2. Customizing Query Parameters Filter results by query terms or collections:

    UnsplashPicker::make('background')
        ->query('nature, landscape')
        ->collections(['123456', '789012']) // Unsplash collection IDs
        ->perPage(20);
    
  3. Handling Image Sizes Specify the desired image size (default: regular):

    UnsplashPicker::make('thumbnail')
        ->size('small') // Options: 'small', 'regular', 'large'
        ->previewHeight(150);
    
  4. Integration with Media Libraries Store the selected image URL in a model and display it:

    // In your model
    public function getImageUrlAttribute()
    {
        return $this->attributes['image_url'] ?? null;
    }
    
    // In your resource table
    TextColumn::make('image_url')
        ->label('Image URL')
        ->copyable();
    
  5. Validation and Defaults Add validation rules or set defaults:

    UnsplashPicker::make('logo')
        ->rules(['required', 'image'])
        ->default('https://source.unsplash.com/random/800x600');
    

Integration Tips

  • Filament Panels: Ensure you’ve set up a custom theme (as noted in the README) to avoid styling conflicts.
  • Caching: Unsplash API has rate limits. Cache responses if making frequent requests:
    UnsplashPicker::make('banner')
        ->cacheResults(3600); // Cache for 1 hour
    
  • Localization: Translate labels and placeholders:
    UnsplashPicker::make('icon')
        ->label(__('filament-unsplash-picker::fields.unsplash_picker.label'))
        ->placeholder(__('filament-unsplash-picker::fields.unsplash_picker.placeholder'));
    
  • Livewire/Alpine: Combine with Filament’s livewire components for dynamic updates:
    UnsplashPicker::make('dynamic_image')
        ->livewire(); // If supported in future updates
    

Gotchas and Tips

Pitfalls

  1. Unsplash API Limits

    • Free tier allows 50 requests/hour. Exceeding this may return 429 Too Many Requests.
    • Fix: Implement retries with exponential backoff or cache aggressively.
    • Example:
      UnsplashPicker::make('image')
          ->retryOnRateLimit(3); // Retry 3 times on 429
      
  2. Missing Custom Theme

    • If using Filament Panels without a custom theme, the picker may render incorrectly.
    • Fix: Follow Filament’s theme docs to create one.
  3. Image Size Mismatches

    • Unsplash’s size parameter may return unexpected dimensions (e.g., regular isn’t always 1024x1024).
    • Fix: Use ->previewHeight() to constrain the display and handle resizing client-side.
  4. CORS Issues

    • If embedding Unsplash images in a frontend app, ensure your Unsplash app settings allow your domain.
    • Fix: Configure CORS in Unsplash Developer Settings or proxy requests.
  5. Rate-Limited Searches

    • Searching with broad queries (e.g., " " or null) may trigger rate limits.
    • Fix: Default to a specific query or collection:
      UnsplashPicker::make('image')
          ->defaultQuery('photography');
      

Debugging

  1. API Errors

    • Check the browser’s Network tab for Unsplash API responses (look for 400, 401, or 429 errors).
    • Enable debug mode in config/filament.php:
      'debug' => env('FILAMENT_DEBUG', false),
      
  2. Field Not Rendering

    • Verify the client_id is set in .env and config/services.php.
    • Clear Filament’s cache:
      php artisan filament:cache-reset
      
  3. Styling Issues

    • Override CSS via your custom theme:
      /* resources/css/filament/unsplash-picker.css */
      .filament-unsplash-picker {
          --wp-preview-height: 200px;
      }
      

Extension Points

  1. Custom API Client Extend the underlying Unsplash client for additional features:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        $this->app->extend('unsplash', function ($client) {
            $client->withCustomHeader('X-Custom-Header', 'value');
            return $client;
        });
    }
    
  2. Add Metadata Fields Fetch and store additional Unsplash metadata (e.g., author, download_location):

    UnsplashPicker::make('featured_image')
        ->withMetadata(['author', 'download_location'])
        ->statePath('metadata');
    
  3. Local Storage Fallback Allow users to upload local files if Unsplash fails:

    UnsplashPicker::make('fallback_image')
        ->fallbackToFileUpload()
        ->fileUploadInstructions('Upload a local file if Unsplash fails.');
    
  4. Event Listeners Listen for image selection events to trigger actions:

    // In a service provider
    UnsplashPicker::listen('image.selected', function ($imageUrl, $field) {
        Log::info("Selected image: $imageUrl via field: {$field->getName()}");
    });
    
  5. Testing Mock the Unsplash API in tests:

    use Mansoor\FilamentUnsplashPicker\Testing\TestsUnsplashPicker;
    
    public function test_unsplash_picker()
    {
        TestsUnsplashPicker::fake([
            'https://api.unsplash.com/search/photos' => [
                'results' => [['urls' => ['regular' => 'fake-url.jpg']]],
            ],
        ]);
    
        // Test your form...
    }
    
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.
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
atriumphp/atrium