Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Livewire Image Upload Tutorial

Last Updated on June 5, 2024 by

Livewire package provides a traits called WithFileUploads, which allows users to upload images to Laravel 11 applications.

Let’s start to create image upload feature using livewire in application:

Step 1: Create Migration and Model

Run the following command to create migration and model file:

php artisan make:model Photo -m

Edit database/migrations/Photos.php file and add the following fields in it:

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

Edit app/models/Photo.php file, and add the following property in it:

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Photo extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'title','name'
    ];
}

Run migration command to create tables in database:

php artisan migration

Step 2: Install Livewire

Run the following command to install livewire:

composer require livewire/livewire

Step 3: Create Image Upload Component

Run the following command to create the component for image uploading:

php artisan make:livewire upload-file

Edit app/Livewire/UploadFile.php file and implement image upload logic in it:

<?php

namespace App\Http\Livewire;

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

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

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

Edit resources/views/livewire/upload-file.blade.php and create form with input field that allow users to select file for upload:

<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="title">
        @error('title') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
    <div class="form-group">
        <input type="file" class="form-control" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-primary">Upload</button>
</form>

Step 4: Create Image Upload Route

In routes/web.php file, create routes for image upload form:

<?php

use Illuminate\Support\Facades\Route;


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

Step 5: Create View File

Create a view file named welcome.blade.php in resources/views directory, and import livewire image upload component in it:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Livewire Image Upload Tutorial - ItcodStuff.com</title>
    @livewireStyles
   <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    
<div class="container">
    
    <div class="card">
      <div class="card-header">
        Laravel 11 Livewire Image Upload Example - ItcodStuff.com
      </div>
      <div class="card-body">
        @livewire('upload-file')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>

Step 6: Test Application

Run the following command to start laravel application server:

php artisan serve

Enter http://localhost:8000/upload-image url on browser for testing.

Leave a Comment