if you are a laravel developer and want to know how to setup Spatie Media Library in Laravel 8. Spatie Media Library is easily manage files and images associated with your models.
Step 1: Install the package
Step 2: Publish the config file
Step 3: Add the Trait to model
Step 4: Migrate the database
Step 5: Store media files
Spatie Media Library is very popular media management library in Laravel.
Step 1: Install the package
To install Spatie Media Library, you need to have composer installed in your system. If you don’t have composer so you need visit on www.getcomposer.org. and download composer. open your terminal or command prompt and navigate to the root directory of your Laravel project. then run the following command:
composer require "spatie/laravel-medialibrary:^7.0.0"
This command will download and install the latest version of Spatie Media Library in your project.
Step 2: Publish the config file
After installation, you need to publish the configuration file. Run the following command in your terminal or command prompt:
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider"
Step 3: Add the Trait to model
To use Spatie Media Library, you need to add the HasMedia
trait to your model. Here’s an example:
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
class Customer extends Model implements HasMedia
{
use HasMediaTrait;
}
Step 4: Migrate the database
Spatie Media Library uses a database table to store the media files associated with your models. we need create the table and run the following command:
php artisan migrate
Step 5: Store media files
Spatie Media Library is set up, you can store media files associated with your models. we can use below code to store image in controller.
$customer=Customer::create($customer_data);
if ($request->hasFile('image'))
{
$customer
->addMedia($request->file('file'))
->toMediaCollection();
}
we are using the addMedia
method to store a file associated with a product. The toMediaCollection
method is used to store the media file in the default media collection.
you can expand knowledge and improve skills by learning from blog posts in Laravel section through online education in https://webdeveloperindia.in
Hello, Welcome to webdeveloperindia.in. I am a full-stack web developer. Email – [email protected] | Skype – azaruddin23. I have knowledge of PHP, Laravel, Magento 1/2, Codeigniter, WordPress, Joomla, Shopify, Git, Bitbuket, jQuery, Ajax, Javascript and ReactJS.