Laravel Livewire: Multiple Images Upload with Preview

Laravel Livewire: Multiple Images Upload with Preview

Admin
Admin・ 16 September 2021
9 min read ・ 18371 views
Series: Laravel Livewire

Laravel Livewire Multiple Image Upload - In this article, I will share the steps or ways to create a multiple image upload feature with images preview using laravel 8 and livewire. The multiple image upload feature is usually used or needed to add images or photos of more than one file for data such as products, properties, or others.

Okay, let's get straight to the steps 👇 👨‍💻

Step 1: Install Laravel

//via Laravel Installer
composer global require laravel/installer
laravel new livewire-multiple-image-upload

//via Composer
composer create-project laravel/laravel livewire-multiple-image-upload

In this first step, we need to install the latest version of laravel (currently version 8) which we will try to implement to create a multiple image upload feature. For laravel installation, you can use the laravel installer or use composer like the example above.

Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate or generate a laravel project with the name livewire-multiple-image-upload.

Wait until the installation process is complete and when it's finished, don't forget to enter the project directory using the command cd livewire-multiple-image-upload.

Step 2: Setup Database

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

Next, create a new database to experiment with making multiple image upload features with laravel 8 and livewire. If you use xampp as local server, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name livewire_multiple_image_upload. Then don't forget to also adjust the DB_DATABASE in the .env file as in the example above.

Step 3: Create Model & Migration File

php artisan make:model Image -m

Okay, then in the third step we need to create model and migration files for Image. Please run the command as above to generate Image model and migration files.

 public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('image');
            $table->timestamps();
        });
    }

Next, open the file database/migrations/xxxx_xx_xx_xxxxxx_create_images_table.php. We add an image field in the images table like the code above. If so, save and run the php artisan migrate command to migrate all migration files.

protected $guarded = [];

Don't forget, in the Models/Image.php file, we need to add protected $guarded = []; like the code above.

Step 4: Install Livewire

composer require livewire/livewire

After installing laravel and creating a database, we continue by installing livewire in our laravel project. Run the command as above to install livewire.

Step 5: Create Livewire Components

php artisan make:livewire MultipleImageUpload

Okay, next we need to create a livewire component to create a view and logic for uploading multiple images. Please run the artisan command as above. From this command, it will generate two files located in the directory as below.

CLASS: app/Http/Livewire/MultipleImageUpload.php
VIEW:  resources/views/livewire/multiple-image-upload.blade.php

Step 5.1: MultipleImageUpload.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Image;

class MultipleImageUpload extends Component
{
    use WithFileUploads;
 
    public $images = [];

    public function save()
    {
        $this->validate([
            'images.*' => 'image|max:1024', // 1MB Max
        ]);
 
        foreach ($this->images as $key => $image) {
            $this->images[$key] = $image->store('images');
        }
    
        $this->images = json_encode($this->images);

        Image::create(['image' => $this->images]);
 
        session()->flash('success', 'Images has been successfully Uploaded.');
 
        return redirect()->back();
    }

    public function render()
    {
        return view('livewire.multiple-image-upload');
    }
}

We have created the livewire components, then we need to update the code in those components to our needs. For that, please open the file in app/Http/Livewire/MultipleImageUpload.php and change the existing code to be like the code above.

To add the file upload feature in the livewire component, we need to add the use Livewire\WithFileUploads; trait. In the code above, we add the $images method with an array data to retrieve or read input from wire:model="images" in the view file (livewire components). In addition, we also use a foreach loop to save all uploaded files to the images folder (in the storage/app directory) and save them as JSON format (using json_encode()) in the image field in the images table.

Step 5.2: multipe-image-upload.blade.php

<div class="card">
    <div class="card-body">
        <form wire:submit.prevent="save">   
            @if (session()->has('success'))
                <div class="alert alert-success">
                    {{ session('success') }}
                </div>
            @endif 
            @if ($images)
                Photo Preview:
                <div class="row">
                    @foreach ($images as $images)
                    <div class="col-3 card me-1 mb-1">
                        <img src="{{ $images->temporaryUrl() }}">
                    </div>
                    @endforeach
                </div>
            @endif
            <div class="mb-3">
                <label class="form-label">Image Upload</label>
                <input type="file" class="form-control" wire:model="images" multiple>
                <div wire:loading wire:target="images">Uploading...</div>
                @error('images.*') <span class="error">{{ $message }}</span> @enderror
            </div>
            <button type="submit" class="btn btn-primary">Save Image</button>
            <div wire:loading wire:target="save">process...</div>
        </form>
    </div>
</div>

Livewire handles multiple file uploads automatically by detecting the multiple attribute in the <input> tag. In this livewire component multiple-image-upload.blade.php file, we add a form with an action to the save method in the MultipleImageUpload.php file. Then we add a success session that displays a success message when we successfully upload multiple images.

In the form, we add only one input field, which is to upload multiple images with an additional loading display when uploading multiple images. In addition, we also add code to display or preview the image for the selected image file and before submitting it, use ->temporaryUrl(). So, overall, the code in the multiple-image-upload.blade.php file will be like the code above.

Step 6: Create Master View

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">

        <title>Livewire - Multiple Image Upload</title>
        
        @livewireStyles
    </head>
    <body>
        <div class="container mt-5">
            <div class="row">
                <h1 class="text-center my-2">Livewire - Multiple Image Upload</h1>
                @livewire('multiple-image-upload')
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
        @livewireScripts
    </body>
</html>

Then we create a master view file with additional scripts @livewireStyles, @livewireScripts and don't forget @livewire('multiple-image-upload'). So, please create a new view file with the file name master.blade.php, and add the code as above.

Step 7: Define Route

Route::view('multiple-image-upload','master');

In the last step, we need to register a new route in the routes/web.php file. For example, here we register Route::view('multiple-image-upload','master');.

Step 7: Testing

livewire multiple upload

We have come to the end of the tutorial article on how to create a multiple image upload feature with preview using laravel and livewire. To test it, please run the server using the php artisan serve command, then open the project in a browser with a URL like 127.0.0.1:8000/multiple-image-upload.

Next, click the input field and select some image files and click save image, then the image files will be stored in the storage/app/images folder and add new data in the images table.

That's it for this tutorial article, until here we have both learned how to make the multiple image upload feature with laravel 8 and livewire. Good luck, hopefully this article can be useful and see you in the next article.👋 

 

📖 Full Documentation: Livewire Multiple Files

Tinggalkan Komentar
Loading Comments