Laravel with Packages | Laravel Image Upload with Spatie’s Media Library Example

I will show you an example of a laravel image upload with spatie media library. We will use the laravel spatie media library tutorial. let’s discuss the laravel spatie media library. you’ll learn laravel image upload spatie media library. Alright, let’s dive into the steps.

In this example, we will do an image upload using the spatie/laravel-medialibrary composer package. Spatie Media Library provides easy image uploading with laravel eloquent model. using this package you can easily store images, get an image, and generate a thumbnail image. you can use this example with laravel 6, laravel 7, laravel 8, and laravel 9 versions.

Here, we will create a post table and we will add images of each post using spatie/laravel-medialibrary library and listing of posts with images.

Just let’s follow the below step and see the preview below:

first of all, we need to get a fresh Laravel 8 version application using the below command, So open your terminal OR command prompt and run the below command:

composer create-project laravel/laravel blog

in the first step, we need to install the spatie/laravel-medialibrary composer package so let’s use the below command to install:

composer require spatie/laravel-medialibrary

after installing successfully, we need to run the following command to create migration for the "media" table:

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

now let’s run the migration command:

php artisan migrate

in the first step, we need to create new migration for adding the “posts” table:

php artisan make:migration create_posts_table

database/migrations/2021_07_13_140744_create_posts_table.php

<?php

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

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

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

now let’s run the migration command:

php artisan migrate

now, create the post model and add code as below:

app/Models/Post.php

<?php

namespace App\Models;

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

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

protected $fillable = [
'title',
'body',
];
}

In this step, we need to create some routes for listing posts and creating posts.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;


Route::get('posts',[PostController::class,'index'])->name('posts.index');
Route::get('posts/create',[PostController::class,'create'])->name('posts.create');
Route::post('posts/store',[PostController::class,'store'])->name('posts.store');

in this step, we need to create PostController and add the following code to that file:

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$posts = Post::latest()->get();
return view('posts.index', compact('posts'));
}

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

/**
* Write code on Method
*
* @return response()
*/
public function store(Request $request)
{
$valiator = $request->validate([
'title' => 'required',
'body' => 'required',
'image' => 'required',
]);

$post = Post::create($request->all());

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

return redirect()->route('posts.index');
}
}

here, we need to create blade files for index and create. so let’s create one-by-one files:

resources/views/posts/index.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Laravel Image Upload with Spatie Medialibrary Example - raviyatechnical</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<div class="container">
<h1>Posts List</h1>
<div class="d-flex p-2 bd-highlight mb-3">
<a href="{{ route('posts.create') }}" class="btn btn-dark">Add</a>
</div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Body</th>
<th width="30%">Image</th>
</tr>
</thead>
<tbody>
@foreach($posts as $key=>$post)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->body }}</td>
<td><img src="{{$post->getFirstMediaUrl('images', 'thumb')}}" / width="120px"></td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>

</html>

resources/views/posts/create.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Laravel Image Upload with Spatie Medialibrary Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<div class="container">
<h1>Create Post</h1>
<div class="d-flex p-2 bd-highlight mb-3">
<a href="{{ route('posts.index') }}" class="btn btn-outline-danger btn-sm">Go Back</a>
</div>
<div>
<form action="{{ route('posts.store') }}" enctype="multipart/form-data" method="post">
@csrf
<div class="mb-3">
<label>Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="mb-3">
<label>Body</label>
<textarea class="form-control" name="body"></textarea>
</div>
<div class="mb-3">
<label>Image:</label>
<input type="file" name="image" class="form-control">
</div>
<div class="d-grid">
<button class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</body>

</html>

Now we need to do the following configuration. you need to link the storage folder to the public by using the following command:

php artisan storage:link

then make sure your .env URL path should be correct:

.env

APP_URL=https://localhost:8000

Now we are ready to run our example. so run the below command so quick run:

php artisan serve

Now you can open the below URL on your browser:

localhost:8000/posts

you can get more methods about Spatie Media Library.

I hope it can help you...

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store