Laravel 8 Tutorial - Livewire File Upload

In this tutorial, we are going to learn about Livewire File Upload. So, let's see how we can upload a file in Livewire.

First, let's create a model. To do this, switch to the command prompt and run the following command:


php artisan make:model Upload

Now, switch to the project and let's open the create_uploads_table migration file. Add the following code:


<?php

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

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

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

Next, let's open the Upload model and add the following code:


<?php

namespace App\Models;

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

class Upload extends Model
{
use HasFactory;

protected $fillable = ['title','filename'];
}

Now, let's migrate this migration. To do this, switch to the command prompt and run the following command:


php artisan migrate

After that, let's create the Livewire component. Run the following command:


php artisan make:livewire Uploads.

Now, switch to the project and let's create a route for the Uploads component. Go inside the routes directory, open web.php, and add the following route:


Route::get('/upload',Uploads::class);

Next, open the uploads component view file and create a form. Note that I have already added the Bootstrap CDN inside the default layout file.

Now, go to the Uploads.php component class file and write the following code:


<?php

namespace App\Http\Livewire;

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

class Uploads extends Component
{
use WithFileUploads;
public $title;
public $filename;

public function updated($fields)
{
$this->validateOnly($fields,[
'title' => 'required',
'filename' => 'required'
]);
}
public function fileUpload()
{
$validatedData = $this->validate([
'title' => 'required',
'filename' => 'required'
]);

$filename = $this->filename->store('files','public');
$validatedData['filename'] = $filename;
Upload::create($validatedData);
session()->flash('message','File successfully uploaded');
$this->emit('fileUploaded');
}
}

After that, let's open the uploads.blade.php view file and write the following code:


<div>
<section>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
@if(Session::has('message'))
<div class="alert alert-success" role="alert">{{Session::get('message')}}</div>
@endif
<div class="card">
<div class="card-header">
File Upload
</div>
<div class="card-body">
<form id="form-upload" wire:submit.prevent="fileUpload" enctype="multipart/form-data">
<div class="form-group">
<lable for="title">Ttile</lable>
<input type="text" name="title" class="form-control" wire:model="title" />
@error('title') <p class="text-danger">{{$message}}</p> @enderror
</div>

<div class="form-group">
<lable for="filename">File</lable>
<input type="file" name="filename" class="form-control" wire:model="filename" />
@error('filename') <p class="text-danger">{{$message}}</p> @enderror
</div>

<button type="submit" class="btn btn-success">Upload</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div>

Finally, go inside the app.blade.php layout file and add the following code just before the closing body tag:


<script>
window.livewire.on('fileUploaded',()=>{
            $('#form-upload')[0].reset();
        });
</script>

All done! Let's check this. Switch to the browser and go to the URL /uploads. Here, you can see the form. Now, just click on submit. You can see that validation is working. Let's enter the title and select any file. Now, click on submit. You can see the message "File uploaded". Let's check the uploaded file. Go inside the project directory, then storage/Public/Files, and here you can see the file. Upload one more file. Enter the title, choose the file, and you can see the file uploaded.

So, in this way, we can upload a file in Livewire.