How to Upload Image Full CRUD with Spatie MediaLibrary Package Laravel 9
Hello, my friend!
This tutorial will show you how to upload an image using the Spatie MediaLibrary package. You will also learn how to upload images, edit images, and delete images. Today, you will see everything in one place. I’m sure many of you have found yourself in a situation where you don’t edit or remove the image from the post.
Visit : https://laraveltuts.com for more laravel tutorial.
How to Upload Image Full CRUD with Spatie MediaLibrary Package Laravel 9
Step 1: Set Up Laravel Project
Step 2: Set Up Database Details in ENV
Step 3: Create Model and Migration
Step 4: Install laravel-medialibrary
Step 5: Set Up laravel-medialibrary
Step 6: Perform Crud Operations
Set Up Laravel Project
Installing a new Laravel app, so go to the terminal, type the command, and create a new Laravel app.
Now, You have to move to the project folder:
Set Up Database Details in ENV
You must now connect the Laravel app to the database, so open the .env configuration file and enter the database credentials as shown below.
.env
Create Model and Migration
To generate model and migration files, type the recommended command into the terminal screen and press Enter.
You must include the $fillable array and the table values in the app/Models/Image.php file.
Now, add name in migration file
Install laravel-medialibrary
We are using v10 in this project, but you can use an older version if you prefer.
Website : https://spatie.be/docs/laravel-medialibrary/v10/introduction
Set Up laravel-medialibrary
Now, You need to publish the migration to create the media table:
Now, we to migrate
Output:
you can see we got new table media database/migrations/create_media_table.php file.
Set Up laravel-medialibrary
You must now add a few classes to laravel-medialibrary (HasMediaTrait , HasMedia, InteractsWithMedia)
Now , you need to link storage, so type the command in the terminal and run the command.
Notice: we need to set url path like 8000, or your current server
.env
You must have your Domain in production or your image will not be seen.
Perform Crud Operations
Next, type the command in the terminal and run it to generate the Controller and routes.
Create routes
We use the resource route to save time and write much shorter code.
Let Implements Code:
On Image Store, you can see that we are saving the image to MediaCollection.
On Update Image you can see we are clear old image using clearMediaCollection first then store new image
Now,let see blade file view/images/index.blade.php
Now, let see blade file view/images/create.blade.php
Now,let see blade file view/images/edit.blade.php
Completed! You can now run the application.
Orignal Post at : LaravelTuts.com