How to Create File Uploading Component Using Laravel Livewire?

In this livewire tutorial we will learn how simply we can create file uploading components in Laravel Livewire using blade templating language. By the end of this simple method you will fully grasp the gist of it.

Livewire actually sends AJAX based requests on runtime without using any AJAX script. It is fully PHP based. That is why people who are not very comfortable with JavaScript they can use Livewire.

In order to create Livewire File uploading component first create a brand new Laravel project. Then put this code in “files” migration to create “file” table.

Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('name');
            $table->timestamps();
 });

Then in our model “File.php”, we will write this code.

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

Then we will simply install Laravel Livewire using this composer command.

composer require livewire/livewire

After that we will create our Livewire component.

php artisan make:livewire file-upload

This will give us 2 files.

app/Http/Livewire/FileUpload.php
resources/views/livewire/file-upload.blade.php

Now in “app/Http/Livewire/FileUpload.php” file, we will write this code.

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');
    }
}

and then in “resources/views/livewire/file-upload.blade.php” file, we will write this 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">
        <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>

Now we will create a route in our “web.php” file.

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

After that we will just add this code in “default.blade.php” file.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Example - Laramatic</title>
    @livewireStyles
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
    
<div class="container">
    
    <div class="card">
      <div class="card-header">
        Laravel Livewire Example - Laramatic.com
      </div>
      <div class="card-body">
        @livewire('file-upload')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>

I hope this might help you. If you have any questions please write down in comments section. We really appreciate that.