Laravel 9 Upload Images with Spatie Media Library Tutorial (ok)

https://www.positronx.io/laravel-upload-images-with-spatie-media-library-tutorial/

Chú ý bài viết phia dưới này Laravel Media Library Full có đầy đủ cả responsive

C:\xampp82\htdocs\testen\config\filesystems.php

<?php
return [
  /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */
  'default' => env('FILESYSTEM_DISK', 'local'),
  /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been set up for each driver as an example of the required values.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3"
    |
    */
  'disks' => [
    'local' => [
      'driver' => 'local',
      'root' => storage_path('app'),
      'throw' => false,
    ],
    'public' => [
      'driver' => 'local',
      'root' => storage_path('app/public'),
      'url' => env('APP_URL') . '/storage',
      'visibility' => 'public',
      'throw' => false,
    ],
    's3' => [
      'driver' => 's3',
      'key' => env('AWS_ACCESS_KEY_ID'),
      'secret' => env('AWS_SECRET_ACCESS_KEY'),
      'region' => env('AWS_DEFAULT_REGION'),
      'bucket' => env('AWS_BUCKET'),
      'url' => env('AWS_URL'),
      'endpoint' => env('AWS_ENDPOINT'),
      'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
      'throw' => false,
    ],
    'media' => [
      'driver' => 'local',
      'root'   => public_path('media'),
      'url'    => env('APP_URL') . '/media',
    ],
  ],
  /*
    |--------------------------------------------------------------------------
    | Symbolic Links
    |--------------------------------------------------------------------------
    |
    | Here you may configure the symbolic links that will be created when the
    | `storage:link` Artisan command is executed. The array keys should be
    | the locations of the links and the values should be their targets.
    |
    */
  'links' => [
    public_path('storage') => storage_path('app/public'),
  ],
];

C:\xampp82\htdocs\testen\database\migrations\2023_05_18_054827_create_media_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  public function up(): void
  {
    Schema::create('media', function (Blueprint $table) {
      $table->id();
      $table->morphs('model');
      $table->uuid('uuid')->nullable()->unique();
      $table->string('collection_name');
      $table->string('name');
      $table->string('file_name');
      $table->string('mime_type')->nullable();
      $table->string('disk');
      $table->string('conversions_disk')->nullable();
      $table->unsignedBigInteger('size');
      $table->json('manipulations');
      $table->json('custom_properties');
      $table->json('generated_conversions');
      $table->json('responsive_images');
      $table->unsignedInteger('order_column')->nullable()->index();
      $table->nullableTimestamps();
    });
  }
};

C:\xampp82\htdocs\testen\database\migrations\2023_05_18_054915_create_clients_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateClientsTable extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('clients', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->text('email');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('clients');
  }
}

C:\xampp82\htdocs\testen\app\Models\Client.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 Client extends Model implements HasMedia
{
  use HasFactory, InteractsWithMedia;
  protected $fillable = [
    'name',
    'email',
  ];
}

C:\xampp82\htdocs\testen\app\Http\Controllers\ClientController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Client;
class ClientController extends Controller
{
  public function index()
  {
    $clients = Client::latest()->get();
    return view('index', compact('clients'));
  }
  public function create()
  {
    return view('create');
  }
  public function store(Request $request)
  {
    $input = $request->all();
    $client = Client::create($input);
    if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
      $client->addMediaFromRequest('avatar')->toMediaCollection('avatar');
    }
    return redirect()->route('client');
  }
}

C:\xampp82\htdocs\testen\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ClientController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
  return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('client', [ClientController::class, 'index'])->name('client');
Route::get('client/create', [ClientController::class, 'create'])->name('client.create');
Route::post('client/store', [ClientController::class, 'store'])->name('client.store');

C:\xampp82\htdocs\testen\resources\views\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>Add Spatie Medialibrary in Laravel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-info">
  <div class="container">
    <div class="d-flex p-2 bd-highlight mb-3">
      <a href="{{ route('client') }}" class="btn btn-outline-danger btn-sm">Go Back</a>
    </div>
    <div>
      <form action="{{ route('client.store') }}" enctype="multipart/form-data" method="post">
        @csrf
        <div class="mb-3">
          <label>Name</label>
          <input type="text" name="name" class="form-control">
        </div>
        <div class="mb-3">
          <label>Email</label>
          <input type="email" name="email" class="form-control">
        </div>
        <div class="mb-3">
          <label>Image:</label>
          <input type="file" name="avatar" class="form-control">
        </div>
        <div class="d-grid">
          <button class="btn btn-primary">Store</button>
        </div>
      </form>
    </div>
  </div>
</body>
</html>

C:\xampp82\htdocs\testen\resources\views\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>Integrate Spatie Medialibrary in Laravel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container">
    <div class="d-flex p-2 bd-highlight mb-3">
      <a href="{{ route('client.create') }}" class="btn btn-dark">Add</a>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Name</th>
          <th>Email</th>
          <th width="30%">Avatar</th>
        </tr>
      </thead>
      <tbody>
        @foreach($clients as $key=>$item)
        <tr>
          <td>{{ ++$key }}</td>
          <td>{{ $item->name }}</td>
          <td>{{ $item->email }}</td>
          <td><img src="{{$item->getFirstMediaUrl('avatar', 'thumb')}}" / width="120px"></td>
        </tr>
        @endforeach
      </tbody>
    </table>
  </div>
</body>
</html>

Laravel 9 Upload Images with Spatie Media Library Tutorial

In this Laravel 9 Spatie media-library tutorial, we will altogether learn how to integrate the spatie media library in the laravel app and show you the perfect example of how to use the Spatie media library in the Laravel application from scratch.

We will cover how to create a simple registration form with name, email and image (avatar) fields and upload avatar images with other form fields using the Laravel Spatie media library package.

Laravel is not a common framework, and it won’t be wrong to say it is a quintessential PHP framework. You can build robust web applications and web APIs with it; it comes with ready-made programming solutions which can exponentially enhance the web development speed.

However, it doesn’t come up with an image upload feature; in this guide, we will show you how to build an image or avatar upload with laravel form using spatie and medialibrary.

So, Let’s start implementing laravel media-library in laravel to upload the image using Spatie. This library comes with tons of features; you can explore more from the official documentation of Laravel Media Library. It is a gold mine of options that profoundly supports Laravel’s eloquent style.

Laravel 9 Upload Avatar Images using Spatie Media Library Example

  • Step 1: Download Laravel App

  • Step 2: Update Database Details

  • Step 3: Install Spatie Medialibrary in Laravel

  • Step 4: Set Up Migration and Model

  • Step 5: Build Controller File

  • Step 6: Build New Routes

  • Step 7: Set Up Blade View Files

  • Step 8: Add App URL

  • Step 9: Run Laravel App

Download Laravel App

Start the first step by using the Composer command to download the latest version of the Laravel app, get to the terminal and execute the command.

composer create-project laravel/laravel my-demo-app --prefer-dist

BashCopy

Update Database Details

Open the .env file and update your database details like database name, username and password as given below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

.propertiesCopy

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

BashCopy

Install Spatie Medialibrary in Laravel

Installing the Media library is easy and can be installed via Composer; if you want to use only the base package, please use the given command.

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

BashCopy

Let us prepare the database; you have to publish migration to create the media table for that.

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

BashCopy

Consequently, you have to execute a command to run migrations.

php artisan migrate

BashCopy

Set Up Migration and Model

Now, you have to generate “Client’s” migration and model files concurrently using the suggested command.

php artisan make:model Client -m

BashCopy

The suggested command generated, app/Models/Client.php, likewise you have to define the table schema into this model file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\HasMedia;

class Client extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia;
    
    protected $fillable = [
        'name',
        'email',
    ];
}

PHPCopy

Make sure to import InteractsWithMedia and HasMedia services, append HasMedia with implements, and define InteractsWithMedia right after HasFactory service in the model file.

Secondly, get into the app/database/migrations/create_clients_table.php, similarly you need to add the table values into this migration file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateClientsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('email');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('clients');
    }
}

PHPCopy

Build Controller File

Next, go to terminal and execute command to generate a controller.

php artisan make:controller ClientController

BashCopy

After running above command a new controller file created at app/Http/Controllers/ClientController.php path.

In this file, first import the Client model, we will use ClientController class to store client registeration form along with upload image into the database at the same time into the Medialibrary storage using the spatie media library.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Client;

class ClientController extends Controller
{
    public function index()
    {    
        $clients = Client::latest()->get();
        return view('index', compact('clients'));
    }
    public function create()
    {
        return view('create');
    }
    
    public function store(Request $request)
    {
        $input = $request->all();
        $client = Client::create($input);
        if($request->hasFile('avatar') && $request->file('avatar')->isValid()){
            $client->addMediaFromRequest('avatar')->toMediaCollection('avatar');
        }
        return redirect()->route('client');
    }
}

PHPCopy

Build New Routes

Now, the controller has been set, its time to build new routes to handle the controller’s functions; get inside the routes/web.php and define the three routes with Get and Post methods altogether.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ClientController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

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

PHPCopy

Set Up Blade View Files

Now, we are ready to create view files; create two view these files, we will build a form for user registration and create a file to show clients data after fetching from the database.

Import bootstrap 5, create the form tag, pass the action tag along with the route, which stores the name, email and avatar profile image into the database.

After that, make create.php and update code in the app/resources/views/create.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add Spatie Medialibrary in Laravel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-info">
    <div class="container">
        <div class="d-flex p-2 bd-highlight mb-3">
            <a href="{{ route('client') }}" class="btn btn-outline-danger btn-sm">Go Back</a>
        </div>
        <div>
            <form action="{{ route('client.store') }}" enctype="multipart/form-data" method="post">
                @csrf
                <div class="mb-3">
                    <label>Name</label>
                    <input type="text" name="name" class="form-control">
                </div>
                <div class="mb-3">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control">
                </div>
                <div class="mb-3">
                    <label>Image:</label>
                    <input type="file" name="avatar" class="form-control">
                </div>
                <div class="d-grid">
                    <button class="btn btn-primary">Store</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

PHPCopy

Create index.php and update code in the app/resources/views/index.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Integrate Spatie Medialibrary in Laravel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="d-flex p-2 bd-highlight mb-3">
            <a href="{{ route('client.create') }}" class="btn btn-dark">Add</a>
        </div>
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th width="30%">Avatar</th>
                </tr>
            </thead>
            <tbody>
                @foreach($clients as $key=>$item)
                <tr>
                    <td>{{ ++$key }}</td>
                    <td>{{ $item->name }}</td>
                    <td>{{ $item->email }}</td>
                    <td><img src="{{$item->getFirstMediaUrl('avatar', 'thumb')}}" / width="120px"></td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</body>
</html>

PHPCopy

Add App URL

In this step, you have to open the .env configuration file and look for the APP_URL variable and append the given url in-front.

...
...
...
APP_URL = http://localhost:8000
...
...
...

BashCopy

Run Laravel App

By default, the public disk utilizes the local driver and stores its files in storage/app/public.

To make these files accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

So, we can create the symbolic link to access the storage directory using the artisan command publicly.

php artisan storage:link

BashCopy

You have reached final at the end of the tutorial, now start the app using the php artisan command:

php artisan serve

BashCopy

Here is the link which will help you open the app on the browser and test.

http://localhost:8000/client

BashCopy

Conclusion

the best features of the Laravel framework, which is known as a Laravel file system and Laravel Spatie.

Laravel gives a compelling filesystem abstraction. In addition, it offers a great way to deal with simple drivers for working with local filesystems, SFTP, and Amazon S3.

If your storage requirement changes while developing, you can quickly switch between these storage options between your local development machine and production server as the API remains intact for every system.

Last updated