Laravel Livewire Multiple Images Upload with Preview

laravel 9 livewire multiple image upload example; In this tutorial you will learn step by step on how to upload multiple images with preview option in the Laravel application using Livewire package.

This tutorial will guide you from scratch about step by step Laravel Livewire Multiple Images upload with preview using the help of the livewire package in the laravel application. You can use livewire Multi image upload Example in laravel 6, laravel 7, laravel 8 and laravel 9 apps.

Laravel Livewire Upload Multiple Images Example

This quick and simple tutorial offers you a facile example of a Multiple File Upload with preview tutorial in laravel app with livewire library.

Use to the following steps to integrate upload multple images in laravel 9 app with livewire package:

  • Step 1: Install Laravel App
  • Step 2: Connect App to Database
  • Step 3: Create Model & Migration
  • Step 4: Make Routes
  • Step 5: Install Livewire Package
  • Step 6: Create Image Component for Multiple Image Upload
  • Step 7: Render Livewire Component in Blade View
  • Step 8: Run Development Server

Install Laravel App

First run the following command in terminal to install laravel fresh app for laravel livewire pagination with search example app.

composer create-project --prefer-dist laravel/laravel laravel-multiple-images

Go into the app:

cd laravel-multiple-images

Configure Database Credentials

Open the .env file and add your database credentials such as database name, username equally important password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Create Model & Migration

Now generate model and migration file just adding the below command in your terminal which is generate a model file and migration which will show your database table after running the migration command.

php artisan make:model Image -m

Now you can see in your database migration directory created a new file same as below, here you need to add you database columns.

database\migrations\2020_09_13_071913_create_images_table.php

<?php

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

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

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

After adding the columns now run the below command which is generate table in your database.

php artisan migrate

Add Fillable Property: In your app/models inside generated a new file Image.php file where you need to add fillable properties.

app\Models\Image.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    protected $fillable = [
      'name', 'path'
    ];
}

Make Routes

To open web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Livewire\Image;
Route::get('images', Image::class);

Install Livewire Package

In this step, we need to install livewire package to laravel application using the following command:

composer require livewire/livewire

Create Image Component for Multiple Image Upload

Go to console run the artisan command to create the livewire components for laravel livewire upload multiple images:

php artisan make:livewire images

The above command generated two files on the following path:

app/Http/Livewire/Image.php
resources/views/livewire/images.blade.php

Go ahead and place the below code in the app/Http/Livewire/Image.php file:

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Image;
class Image extends Component
{
    use WithFileUploads;
    public $images = [];
    public function render()
    {
        return view('livewire.home');
    }
    public function store()
    {
        $this->validate([
            'images.*' => 'image|max:1024', // 1MB Max
        ]);
        foreach ($this->images as $key => $image) {
            $name = $image->getClientOriginalName();
            $path = $image->storeAs('uploads', $name, 'public');

            Image::create([
              'name' => $name,
              'path' => '/storage/'.$path
            ]);
        }
        
        session()->flash('message', 'Images has been successfully Uploaded.');
        return redirect()->to('/images');
    }
}

Next, open images.blade.php, which is located inside resources/views/livewire/ directory and add the following code into it:

<div>
    <form>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <input type="file" class="form-control" wire:model="images" multiple>
                    @error('image.*') <span class="text-danger error">{{ $message }}</span>@enderror
                </div>
            </div>
            <div class="col-md-12 text-center">
                <button class="btn text-white btn-success" wire:click.prevent="store">Save</button>
            </div>
        </div>
    </form>
</div>

Render Livewire Component in Blade View

Add below code in resources/views/welcome.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Multiple Image Upload Example </title>
    @livewireStyles
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.9.0/tailwind.min.css" integrity="sha512-wOgO+8E/LgrYRSPtvpNg8fY7vjzlqdsVZ34wYdGtpj/OyVdiw5ustbFnMuCb75X9YdHHsV5vY3eQq3wCE4s5+g==" crossorigin="anonymous" />
</head>
<body>
    
<div class="container">
    
    <div class="card">
      <div class="card-header">
        Laravel Livewire  Multiple Image Upload
      </div>
      <div class="card-body">
        @livewire('images')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>

Start Development Server

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

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

php artisan serve

Last, open browser and fire the following url into browser:

http://127.0.0.1:8000/images

The Laravel Livewire CRUD operation Example Tutorial is over; in this tutorial, we learned the easiest way to buid CRUD operation example in laravel application using the livewire library.