Laravel 12 with Spatie Laravel-Medialibrary: A Complete Guide

Author

Kritim Yantra

Apr 16, 2025

Laravel 12 with Spatie Laravel-Medialibrary: A Complete Guide

In this blog post, we'll explore how to integrate and use the Spatie Laravel-Medialibrary package in Laravel 12 to manage file uploads, associate them with Eloquent models, and perform advanced media operations like conversions and responsive images.


Table of Contents

  1. Introduction to Spatie Laravel-Medialibrary
  2. Installation & Setup
  3. Basic Usage: Uploading & Attaching Media
  4. Working with Media Collections
  5. Image Manipulations & Conversions
  6. Generating Responsive Images
  7. Advanced Features & Tips
  8. Conclusion

1. Introduction to Spatie Laravel-Medialibrary

The Spatie Laravel-Medialibrary is a powerful package that simplifies file management in Laravel applications. It allows you to:

  • Associate files (images, PDFs, videos) with Eloquent models.
  • Organize files into collections (e.g., avatars, documents).
  • Generate thumbnails and optimized image versions.
  • Create responsive images for better performance.
  • Store files on different filesystems (local, S3, etc.).

2. Installation & Setup

Step 1: Install Laravel 12

If you don’t have Laravel 12 installed, create a new project:

composer create-project laravel/laravel laravel-media-app
cd laravel-media-app

Step 2: Install Spatie Laravel-Medialibrary

Install the package via Composer:

composer require spatie/laravel-medialibrary

Step 3: Publish & Run Migrations

Publish the migration and configuration file:

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"
php artisan migrate

Publish the config file (optional):

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="config"

Step 4: Configure Filesystem

Ensure your config/filesystems.php has a public disk (for local storage):

'disks' => [
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
],

Create a symbolic link:

php artisan storage:link

3. Basic Usage: Uploading & Attaching Media

Step 1: Prepare a Model

Add the InteractsWithMedia trait to your model (e.g., User or Post):

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements HasMedia
{
    use InteractsWithMedia;
}

Step 2: Upload a File

Upload and attach a file to a model:

$post = Post::find(1);
$post->addMedia($request->file('image'))->toMediaCollection('images');

This will:

  • Store the file in storage/app/public.
  • Create a record in the media table.

Step 3: Retrieve Media

Get the media URL:

$post->getFirstMediaUrl('images'); // Returns URL
$post->getFirstMediaPath('images'); // Returns storage path

4. Working with Media Collections

You can define multiple collections (e.g., images, documents):

public function registerMediaCollections(): void
{
    $this->addMediaCollection('images')
         ->acceptsMimeTypes(['image/jpeg', 'image/png'])
         ->singleFile(); // Only allow one file
}

Usage:

$post->addMedia($file)->toMediaCollection('images');

5. Image Manipulations & Conversions

Generate thumbnails and optimized images.

Step 1: Define Conversions

In your model:

use Spatie\MediaLibrary\MediaCollections\Models\Media;

public function registerMediaConversions(Media $media = null): void
{
    $this->addMediaConversion('thumb')
         ->width(150)
         ->height(150)
         ->sharpen(10);
}

Step 2: Use Conversions

$post->getFirstMediaUrl('images', 'thumb'); // Returns thumbnail URL

6. Generating Responsive Images

Serve optimized images for different screen sizes:

$this->addMediaConversion('responsive')
     ->withResponsiveImages();

In Blade:

<img 
    src="{{ $post->getFirstMediaUrl('images') }}" 
    srcset="{{ $post->getFirstMedia('images')->getSrcset('responsive') }}"
    sizes="(max-width: 768px) 100vw, 50vw"
/>

7. Advanced Features & Tips

  • Custom Properties: Store metadata with media files.
    $post->addMedia($file)
         ->withCustomProperties(['author' => 'John Doe'])
         ->toMediaCollection('images');
    
  • Using S3: Configure the media-library disk to use S3.
  • Queued Conversions: Process large files in the background.
    ->nonQueued() // Default
    ->queued() // Process in queue
    

8. Conclusion

The Spatie Laravel-Medialibrary is an essential tool for handling file uploads in Laravel 12. It provides:
✅ Easy file association with models.
✅ Image optimizations & conversions.
✅ Responsive image support.
✅ Flexible storage options (local, S3).

Start using it today to simplify file management in your Laravel projects!

Happy coding! 🚀

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts