Courses

React Laravel 12 Starter Kit: CRUD Project

File Upload with Spatie Media Library

Summary of this lesson:
- Add file uploads to tasks using Spatie Media Library
- Configure backend file handling with proper database relationships
- Implement file upload fields in create/edit forms with progress indicators
- Display uploaded files as thumbnails in task listing table

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.

For reference, here's the Inertia documentation on File Uploads.

Let's see how our Create.tsx file needs to change.

  • We add media to the CreateTaskForm and useForm
  • We add a progress indicator from Inertia
  • We add the <Input> for the file picker

We start with the TypeScript changes.

resources/js/pages/Tasks/Create.tsx:

type CreateTaskForm = {
name?: string,
due_date?: string,
media?: string,
}
 
// ...
 
// We also add `progress` from the Inertia useForm()
const { data, setData, errors, post, reset, processing } = useForm<Required<CreateTaskForm>>({
const { data, setData, errors, post, reset, processing, progress } = useForm<Required<CreateTaskForm>>({
name: '',
due_date: '',
media: '',
});
 
// ...
<div className="grid gap-2">
<Label htmlFor="media">Media</Label>
 
<Input
id="media"
onChange={(e) => setData('media', e.target.files[0])}
className="mt-1 block w-full"
type="file"
/>
 
{progress && (
<progress value={progress.percentage} max="100">
{progress.percentage}%
</progress>
)}
 
<InputError message={errors.media} />
</div>

Here's the visual result:

Now, what happens after we submit the form?


Submit the Create Form: Back-End

We need to modify the Controller and Form Request to accept the media file.

app/Http/Controllers/TaskController.php:

public function store(StoreTaskRequest $request)
{
Task::create($request->validated() + ['is_completed' => false]);
$task = Task::create($request->validated() + ['is_completed' => false]);
 
if ($request->hasFile('media')) {
$task->addMedia($request->file('media'))->toMediaCollection();
}
 
return redirect()->route('tasks.index');
}

Also, we need to add a validation rule to the Form Request.

app/Http/Requests/StoreTaskRequest.php:

return [
'name' => ['required', 'string', 'max:255'],
'due_date' => ['nullable', 'date'],
'media' => ['nullable', 'file', 'max:10240'],
];

Showing File in the Table

In the Controller, we need to just eager load the media() relationship:

app/Http/Controllers/TaskController.php:

public function index()
{
return Inertia::render('Tasks/Index', [
'tasks' => Task::paginate(20)
'tasks' => Task::with('media')->paginate(20)
]);
}

But we also need to change one default behavior of the package.

By default, Spatie Media Library returns multiple files per record. To overcome that and auto-load what we actually need, let's create a special method to return the first media file for each Task. This is a bit tricky advanced Eloquent operation:

  • We need to auto-load the file with $appends Eloquent property
  • However, to avoid N+1 query performance issues, we need to check for eager loading

app/Models/Task.php:

class Task extends Model implements HasMedia
{
// ...
 
protected $appends = [
'mediaFile'
];
 
public function getMediaFileAttribute()
{
if ($this->relationLoaded('media')) {
return $this->getFirstMedia();
}
 
return null;
}
}

Now, we can reference the mediaFile on the front end in TypeScript.

We need to add that mediaFile key to the Task type.

resources/js/types/index.d.ts:

export interface Task {
id: number;
name: string;
is_completed: boolean;
due_date?: string;
mediaFile?: MediaFile;
created_at: string;
updated_at: string;
}

Now, what's that MediaFile type? We need to create it in the same index.d.ts file. It's the structure returned by the Media Library package.

resources/js/types/index.d.ts:

export interface MediaFile {
id: number,
model_type: string,
model_id: number,
uuid: string,
collection_name: string,
name: string,
file_name: string,
mime_type: string,
disk: string,
conversions_disk: string,
size: number,
manipulations: string[],
custom_properties: string[],
generated_conversions: string[],
responsive_images: string[],
order_column: number,
created_at: string,
updated_at: string,
original_url: string,
preview_url: string,
}

And now, we can finally reference the task.mediaFile and show it in the table.

resources/js/pages/Tasks/Index.tsx:

<TableHeader>
<TableRow>
<TableHead>Task</TableHead>
<TableHead>File</TableHead>
<TableHead className="w-[100px]">Status</TableHead>
 
// ...
 
{tasks.data.map((task: Task) => (
<TableRow key={task.id}>
<TableCell>{task.name}</TableCell>
<TableCell>{
!task.mediaFile
? ''
: (
<a href={task.mediaFile.original_url} target="_blank">
<img src={task.mediaFile.original_url} className={'w-8 h-8'} />
</a>
)
}
</TableCell>
<TableCell className={task.is_completed ? 'text-green-600' : 'text-red-700'}>
{task.is_completed ? 'Completed' : 'In Progress'}
</TableCell>

As you can see, we've added a ternary operator logic:

  • If there's no task.mediaFile, we show an empty string
  • Otherwise, we show the link to the original file with the image

I've tried to upload files for a few tasks. Here's the result in the table:


Edit Form: Show the File

Finally, let's add the same input in the Edit Task form with the current file image shown.

First, we need to append some data in the Controller method. The default Route Model Binding with (Task $task) doesn't load those fields by default, so we need to do it manually.

app/Http/Controllers/TaskController.php:

public function edit(Task $task)
{
$task->load(['media']);
$task->append('mediaFile');
 
return Inertia::render('Tasks/Edit', [
'task' => $task,
]);
}

Then, we need to add that input to the form with similar changes we made to the Create.tsx file.

resources/js/pages/Tasks/Edit.tsx:

type EditTaskForm = {
name: string;
is_completed: boolean;
due_date?: string;
media?: string;
};
 
// ...
 
const { data, setData, errors, put, reset, processing } = useForm<Required<EditTaskForm>>({
const { data, setData, errors, put, reset, processing, progress } = useForm<EditTaskForm>({
name: task.name,
is_completed: task.is_completed,
due_date: task.due_date,
media: '',
});
 
// ...
 
<div className="grid gap-2">
<Label htmlFor="media">Media</Label>
 
<Input
id="media"
onChange={(e) => setData('media', e.target.files[0])}
className="mt-1 block w-full"
type="file"
/>
 
{progress && (
<progress value={progress.percentage} max="100">
{progress.percentage}%
</progress>
)}
 
<InputError message={errors.media} />
 
{!task.mediaFile ? '' : (
<a href={task.mediaFile.original_url} target="_blank" className="my-4 mx-auto"><img
src={task.mediaFile.original_url} className={'w-32 h-32'} /></a>)}
</div>

And now, if we visit the Edit page, it shows the current file thumbnail!


Submit the Edit Form

This part will be a little more tricky.

First, let's add the validation rule to the Form Request.

app/Http/Requests/UpdateTaskRequest.php:

public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'is_completed' => ['required', 'boolean'],
'due_date' => ['nullable', 'date'],
'media' => ['nullable', 'file', 'max:10240'],
];
}

Then, we update the Controller method for update.

app/Http/Controllers/TaskController.php:

public function update(UpdateTaskRequest $request, Task $task)
{
$task->update($request->validated());
 
if ($request->hasFile('media')) {
$task->getFirstMedia()?->delete();
$task->addMedia($request->file('media'))->toMediaCollection();
}
 
return redirect()->route('tasks.index');
}

Next, with our Edit, we have to be careful since the Inertia PUT method does not support file uploads:

Uploading files using a multipart/form-data request is not natively supported in some server-side frameworks when using the PUT, PATCH, or DELETE HTTP methods. The simplest workaround for this limitation is to simply upload files using a POST request instead.

Instead, we will use the Manual visits feature with the router.post() method.

resources/js/pages/Tasks/Edit.tsx

import { Head, useForm } from '@inertiajs/react';
import { Head, router, useForm } from '@inertiajs/react';
 
// ...
 
const editTask: FormEventHandler = (e) => {
e.preventDefault();
 
put(route('tasks.update', task.id), {
forceFormData: true,
preserveScroll: true,
onSuccess: () => {
reset();
},
onError: (errors) => {
if (errors.name) {
reset('name');
taskName.current?.focus();
}
},
});
};
 
const editTask: FormEventHandler = (e) => {
e.preventDefault();
 
router.post(
route('tasks.update', task.id),
{ ...data, _method: 'PUT' },
{
forceFormData: true,
preserveScroll: true,
onSuccess: () => {
reset();
},
onError: (errors) => {
if (errors.name) {
reset('name');
taskName.current?.focus();
}
},
},
);
};
 
// ...

And that's it. Now, we can replace the file with another file in the edit form!


Here's the GitHub commit for this lesson.

Previous: Due Date: Can't Use Shadcn Date Picker
avatar

Getting error from the resources/js/pages/tasks/create.tsx and the edit.tsx The files both work and I am getting the info on to the web page. When looking over the pages the only thang I can see that is being marked as ban are the <Input id="media" onChange={(e) => setData('media', e.target.files[0])} className="mt-1 block w-full" type="file" /> This is on both pages On the Edit.tsx you mentioned the put problem I am getting this as well.

PS. I am using PhpStorm as my editor.

avatar

Wait, so the files are working but you're worried about IDE warnings, only?

avatar

You can get rid of the linter error by applying a conditional to make sure e.target.files[0] is not null first:

onChange={(e) => {
    const files = e.target.files;
    if (files && files.length > 0) {
        setData('media', files[0]);
    }
}}
avatar
You can use Markdown
avatar

Not able to see File or Categories on the index.tsx page but can see both on the edit.tsx page and in the database; any suggestions?

avatar
You can use Markdown
avatar

I get error Add fillable property [media] to allow mass assignment on [App\Models\Task]. and if i remove media in form request, it will work. is there anyone like me ?

avatar
You can use Markdown
avatar
You can use Markdown