Now, let's add a file upload field to the Tasks CRUD.
Prepare Back-End: Spatie Media Library
Let's install a well-known package spatie/laravel-medialibrary to handle the file data.
composer require "spatie/laravel-medialibrary"
Then, according to its documentation, we need to publish and run migrations:
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="medialibrary-migrations"php artisan migrate
Finally, we add the appropriate Traits to the Task Model file.
app/Models/Task.php:
use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; // ... class Task extends Model class Task extends Model implements HasMedia { use HasFactory; use InteractsWithMedia; // ...
Ok, the package installation/configuration is ready. Let's dive into the forms.
File Upload in Create Form: Front-End
This time, let's start with the front end. In create page we will add input with a type of file.
resources/views/livewire/tasks/create.blade.php:
<section class="max-w-5xl"> <form wire:submit="save" class="flex flex-col gap-6"> <flux:input wire:model="name" :label="__('Task Name')" required badge="required" /> <flux:input wire:model="due_date" type="date" :label="__('Due Date')" /> <flux:input wire:model="media" type="file" :label="__('Media')" /> <div> <flux:button variant="primary" type="submit">{{ __('Save') }}</flux:button> </div> </form></section>
Here's the visual result:
Now, what happens after we submit the form?
Submit the Create Form: Back-End
We need to modify the Livewire component. To enable file uploading, first, the...