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 File Upload Tutorial

Last Updated on June 7, 2024 by

In Laravel 11, Livewire provides traits for file upload, just import it in the component and use it for file upload, it makes file uploading easy

Let’s start creating the file upload component and import it in the blade view to upload the file to the server directory and database:

Step 1: Create Migration and Model

Run the following command to create migration and model file:

php artisan make:model Gallery -m

Edit database/migrations/galleries.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('galleries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('title');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('galleries');
    }
};

Edit app/models/Gallery.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 Gallery extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'title','name'
    ];
}

Run migration command to create tables in database:

php artisan migration

Step 2: Set Up Livewire

Run the following command to install livewire:

composer require livewire/livewire

Step 3: Create File Upload Component

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

php artisan make:livewire file-upload

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

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\File;
  
class FileUpload extends Component
{
    use WithFileUploads;
    public $file, $title;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function submit()
    {
        $validatedData = $this->validate([
            'title' => 'required',
            'file' => 'required',
        ]);
  
        $validatedData['name'] = $this->file->store('files', 'public');
  
        File::create($validatedData);
  
        session()->flash('message', 'File successfully Uploaded.');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        return view('livewire.file-upload');
    }
}

Edit resources/views/livewire/file-upload.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">
        <label for="exampleInputName">Title:</label>
        <input type="text" class="form-control" id="exampleInputName" placeholder="Enter title" wire:model="title">
        @error('title') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
    <div class="form-group">
        <label for="exampleInputName">File:</label>
        <input type="file" class="form-control" id="exampleInputName" wire:model="file">
        @error('name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
  
    <button type="submit" class="btn btn-success">Save</button>
</form>

Step 4: Create File Upload Route

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

<?php

use Illuminate\Support\Facades\Route;

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

Step 5: Create View File

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

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Example - 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 Livewire Example - ItcodStuff.com
      </div>
      <div class="card-body">
        @livewire('file-upload')
      </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/file-upload url on browser for testing.

Leave a Comment