Laravel 9 Livewire Image Upload Tutorial with Example

Throughout laravel 9 livewire image upload example; In this step by step guide tutorial help how to upload image in the Laravel application using the Laravel Livewire package with validation.

Image uploading is a common feature that needs to be implemented in almost every web or mobile app; this upload image in laravel livewire example will surely help you understand the nitty-gritty of it thoroughly.

This tutorial focuses on Laravel 9, notwithstanding you can create the laravel livewire image upload functionality with laravel 8, laravel 7 and laravel 6 from scratch.

Laravel 9 Livewire Image Upload Example

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel. Livewire relies solely on AJAX requests to do all its server communication.

Use to follow the following steps to upload images in laravel application using the livewire package;

Download Laravel App

First run the following command in terminal to download laravel fresh app:

composer create-project --prefer-dist laravel/laravel livewire-file-upload

Go into the app:

cd livewire-file-upload

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 & Run Migration

Here we create new model and migration file using the below command:

php artisan make:model Image -m

Now open the images migration and upate the below code on it.

database\migrations\2021_12_06_025934_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('title');
            $table->string('image');
            $table->timestamps();
        });
    }

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

Run the migrate command for generating image table.

php artisan migrate

We need to update fillable or guardian for storing in database. Just add the fillable property in your image model.

app/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 = [
        'title', 'image'
    ];
}

Make Routes

You can use your routes, otherwise you can follow the step by step guid of livewire image upload example tutorial.

routes/web.php

Route::get('file-upload', function () {
    return view('images');
});

Install Livewire

Now simply install the livewire package using the following command:

composer require livewire/livewire

Then install node js package:

npm install
npm run dev

Create Livewire File Upload Component

Here you may need to create your livewire component using the below command, this command generate two files on your project one works like controller and another is same as blade.

php artisan make:livewire image-upload

Now they created fies on both path:

app/Http/Livewire/ImageUpload.php
resources/views/livewire/image-upload.blade.php

First open the app\Http\Livewire\ImageUpload.php file and update the below code on it.

<?php

namespace App\Http\Livewire;

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

class ImageUpload extends Component
{
    use WithFileUploads;

    public $title;
    public $image;

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

    public function submit()
    {
        $data = $this->validate([
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,svg,jpg,gif|max:1024',
        ]);

        $imageName = $this->image->store("images",'public');
        $data['image'] = $imageName;

        Image::create($data);

        session()->flash('message', 'Image successfully Uploaded.');
        return redirect()->to('/images');
    }
}

Here is the another component of livewire you need to update below code on it.

resources\views\livewire\image-upload.blade.php

@if (session()->has('message'))
    <div class="alert alert-success">
        {{ session('message') }}
    </div>
@endif
<form wire:submit.prevent="submit" enctype="multipart/form-data">
    <div class="form-group">
        <label for="exampleInputTitle">Title</label>
        <input type="text" class="form-control" id="exampleInputTitle" wire:model="title">
        @error('title') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
    <div class="form-group">
        <label for="exampleInputName">Image</label>
        <input type="file" class="form-control" id="exampleInputName" wire:model="image">
        @error('image') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
     <button type="submit" class="btn btn-primary">Save</button>
</form>

Create Blade File

Its time to infuse the laravel livewire file uploading logic inside the blade view template, so open resources/views/images.blade.php file similarly add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>laravel livewire image ipload - codingdriver.com</title>
    @livewireStyles
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
    <div class="container ">
        <div class="row mt-5">
            <div class="col-md-8 offset-2">
                <div class="card mt-5">
                  <div class="card-header bg-success">
                    <h2 class="text-white">Laravel Livewire Image Ipload - codingdriver.com</h2>
                  </div>
                  <div class="card-body">
                    @livewire('image-upload')
                  </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="{{ asset('js/app.js') }}"></script>
@livewireScripts
</html>

Start Development Server

Execute the following command on the command prompt to start the development server for laravel 9 livewire image upload app:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/file-upload

Thats it for now; the Laravel Livewire Image Upload Tutorial is over. Now we have a basic understanding of creating file uploading feature in Laravel application with Livewire package.