Skip to main content

File Upload with Spatie Media Library

Premium
3:55

Text Version of the Lesson

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...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

RA
Richard A. Hoyle ✓ Link copied!

Question Say some one wonted to add more images what would they have to add or change in order to be able to do that?

M
Modestas ✓ Link copied!

To change from single to multiple files, you will have to:

  • Change the forms to accept multiple files
  • Change the controller to add/update/delete the media that was uploaded
  • Change the display from single file to multiple files

It's not that simple, but also not horribly complicated

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.