Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I associate files with Eloquent models using Laravel Media Library
    Laravel Service Provider


How do I associate files with Eloquent models using Laravel Media Library


Here is how you can associate files with Eloquent models using the Laravel Media Library package:

1. Install the package via Composer:


composer require spatie/laravel-medialibrary

2. Publish the package's configuration file and migration:


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

3. Run the migration to create the necessary database tables:


php artisan migrate

4. Add the `InteractsWithMedia` trait to your Eloquent model:

php
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class YourModel extends Model
{
    use InteractsWithMedia;

    // ...
}

5. Define the media collections you want to use in your model:

php
public function registerMediaCollections(): void
{
    $this->addMediaCollection('images')
         ->singleFile();

    $this->addMediaCollection('documents')
         ->acceptsMimeTypes(['application/pdf']);
}

6. Add media to your model:

php
$yourModel = YourModel::find(1);
$yourModel->addMedia($pathToFile)->toMediaCollection('images');

You can also add media directly from user uploads:

php
$yourModel->addMedia($request->file('image'))->toMediaCollection('images');

7. Retrieve media associated with your model:

php
$images = $yourModel->getMedia('images');
foreach ($images as $image) {
    echo $image->getUrl();
}

8. (Optional) Configure additional settings like file conversions, custom file names, and more in the package's configuration file.

That's the basic workflow for associating files with Eloquent models using the Laravel Media Library package. The package provides a lot of flexibility and features to manage media files, so be sure to check the official documentation for more advanced usage.

Citations:
[1] https://github.com/spatie/laravel-medialibrary
[2] https://laraveldaily.teachable.com/courses/393790/lectures/6329191
[3] https://cloudinary.com/blog/associating_media_files_with_laravel_s_eloquent_models
[4] https://codebrisk.com/blog/laravel-medialibrary-associate-files-with-eloquent-models
[5] https://naxon.dev/blog/laravel-media-library-load-only-1st-picture-efficiently