Laravel Spatie Medialibrary Example Tutorial

May 26, 2021 . Admin

Hi Dev,

Today, I will learn you how to use spatie medialibrary in laravel 8 application,we will show example of laravel spatie medialibrary.you can easliy use spatie media library laravel 8.this package use to upload a photo or an avatar. In this tutorial we will show you an easy way to add it, using Spatie’s Media Library package.

In this blog, let’s move over the well-known laravel medialibrary package deal evolved by way of Spatie. This package deal can companion all varieties of documents together with your Eloquent models.

Here, I will give you full example for spatie media library laravel 8 as bellow.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

>In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install Spatie Medialibrary

In this step, we need laravel/Spatie Medialibrary package. you can install Spatie Medialibrary package using bellow command so let's run bellow command

composer require "spatie/laravel-medialibrary:^9.6.0"

After the package is installed, run the following command to copy the migration file from to package directory to your project directory and also to run the fresh migration command.

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

php artisan migrate
Step 4: Create Model and Migration

here this step, we will create one model and migration name Blog. Use the below following command and create it

php artisan make:model Blog -m

Next,Open Blog migration file and put the below code. here following path of migration file

Path: /database/migrations/2020_05_27_095534_create_blogs_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Next, go to app/Blog.php and open Blog model file and put the below code. here following path of model fille

Path:/app/Models/Blog.php
<?php

namespace App\Models;

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

class Blog extends Model implements HasMedia
{
    use HasFactory,InteractsWithMedia;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'body',
    ];
}
Step 5: Create Route

Create two routes one for show form and the second route send data to the server:

here following path of route fille

Path:/routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('blog',[BlogController::class,'index'])->name('blog');
Route::get('blog/create',[BlogController::class,'create'])->name('blog.create');
Route::post('blog/store',[BlogController::class,'store'])->name('blog.store');
Step 6:Create Controller

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller BlogController 

Here this step,we will create two methods inside the controller first index method is used to display blog form and second store method is used to store data in the mysql database and image upload Medialibrary to storge folder

here following path of Controller fille.

Path:/app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Blog;

class BlogController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {    
        $blogs = Blog::latest()->get();

        return view('blog.index',compact('blogs'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('blog.create');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $blog = Blog::create($input);

        if($request->hasFile('image') && $request->file('image')->isValid()){
            $blog->addMediaFromRequest('image')->toMediaCollection('images');
        }

        return redirect()->route('blog');
    }
}
Step 7:Create a blade view

In this step, we will create two blade file name blog/index.blade.php and blog/create.blade.php.

here following path of index.blade fille

Path:/resources/views/blog/index.blade.php

<html>
<head>
    <title>Laravel Spatie Medialibrary Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" />
</head>
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Laravel Spatie Medialibrary Example</h5>
                        </div>
                        <div class="col-md-2 text-center">
                            <a href="{{ route('blog.create') }}" class="btn btn-success btn-sm">Create</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Title</th>
                                <th width="25%">Image</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($blogs as $key=>$blog)
                                <tr>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $blog->title }}</td>
                                    <td><img src="{{$blog->getFirstMediaUrl('images', 'thumb')}}" / width="100%"></td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Next following path create a create.blade fille

Path:/resources/views/blog/create.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Spatie Medialibrary Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" />
</head>
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-2">
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">
                            <h5>Laravel Spatie Medialibrary Example</h5>
                        </div>
                        <div class="col-md-2 text-center">
                            <a href="{{ route('blog') }}" class="btn btn-info btn-sm">Back</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('blog.store') }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <div class="form-group">
                                    <label for="">Title:</label>
                                    <input type="" name="title" class="form-control" placeholder="Enter Title">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="">Body:</label>
                                <textarea name="body" id="" class="form-control" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="">Image:</label>
                                <input type="file" name="image" class="form-control">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 mb-3 text-center">
                                <button class="btn btn-success btn-block">Submit</button>
                            </div>
                        </div>    
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

After Note that to view the files in the browser you need to make the files public that is stored in the storage directory, you need to run the following command on your project root in terminal/command-line.

php artisan storage:link
next change .env file in APP_URL path
......
APP_URL=http://localhost:8000
......

Now, we will use the php artisan serve command.

php artisan serve

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/blog
OutPut

It will help you...

#Laravel