Laravel 10 Livewire Image Upload Tutorial with Example

Last Updated on by in Laravel

This tutorial helps you ascertain how to upload image in the Laravel application using the Laravel Livewire package.

Laravel Livewire is a profound library that allows you to build user interface components recklessly with exorbitant ease in a couple of minutes.

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.

Throughout this tutorial, you will build a simple image upload example using laravel livewire from scratch, equally important step by step.

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

Create Laravel Project

Laravel project needs to be created, make sure you have the composer set up on your development machine:

composer create-project --prefer-dist laravel/laravel todo

Add Database Configurations

Add database name, user name and password to make the database connection in .env configuration file:

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

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

Create Model and Migration

Create a model and migration file which is almost the archetype of Table that resides in the database.

php artisan make:model Todo -m

Open database/migrations/create_todos_table.php file, define the table values for uploading files:

<?php

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

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

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

Add the given properties inside the Model file as well within app/Models/Todo.php file:

<?php

namespace App\Models;

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

class Todo extends Model
{
    use HasFactory;
    protected $fillable = [
        'fileTitle', 
        'fileName'
    ];    
}

Run the migration with following command:

php artisan migrate

Install Livewire Package

Next, you have to install the livewire package inside your laravel application with given command:

composer require livewire/livewire

Create Livewire Component

In response to manage the file or image uploading via livewire, you need to create livewire file uploading components:

php artisan make:livewire upload-file

There are two files have been generated on the given paths:

app/Http/Livewire/UploadFile.php

resources/views/livewire/upload-file.blade.php

Add the following code in app/Http/Livewire/UploadFile.php config file:

<?php

namespace App\Http\Livewire;

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

class UploadFile extends Component
{
    use WithFileUploads;
    public $fileTitle, $fileName;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function submit()
    {
        $dataValid = $this->validate([
            'fileTitle' => 'required',
            'fileName' => 'required|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
        ]);
  
        $dataValid['fileName'] = $this->fileName->store('todos', 'public');
  
        Todo::create($dataValid);
  
        session()->flash('message', 'File uploaded.');
    }

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

Add the following code in resources/views/livewire/upload-file.blade.php config file:

<form wire:submit.prevent="submit" enctype="multipart/form-data">
  
    <div>
        @if(session()->has('message'))
            <div class="alert alert-success">
                {{ session('message') }}
            </div>
        @endif
    </div>
  
    <div class="form-group">
        <input type="text" class="form-control" placeholder="Enter title" wire:model="fileTitle">
        @error('fileTitle') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
    <div class="form-group">
        <input type="file" class="form-control" wire:model="fileName">
        @error('fileName') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-primary">Upload</button>
</form>

Define Route

Create route bind with blade view tempalte to enable the navigation for file uploading controller in routes/web.php file:

<?php

use Illuminate\Support\Facades\Route;

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

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

Create Blade View

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

<form wire:submit.prevent="submit" enctype="multipart/form-data">
  
    <div>
        @if(session()->has('message'))
            <div class="alert alert-success">
                {{ session('message') }}
            </div>
        @endif
    </div>
  
    <div class="form-group">
        <input type="text" class="form-control" placeholder="Enter title" wire:model="fileTitle">
        @error('fileTitle') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
    <div class="form-group">
        <input type="file" class="form-control" wire:model="fileName">
        @error('fileName') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-primary">Upload</button>
</form>

Start the application:

php artisan serve

Paste the link on the browser’s address bar to test the file upload with laravel livewire:

http://localhost:8000/file-upload

Summary

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.