Reputation: 21
This is my very first message here and I apologize if the question has been asked before.
Also, sorry for my english, I'm french...
I'm building a Laravel app and in one of my forms, I give the user the possibility to upload a file but it's not required.
However, once it's uploaded, there's no way to delete it in my Edit or Upload route.
Let's say a user uplaods a file and changes their mind, how can they remove it?
Here's a screenshot of the form :
Here's my controller :
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required|string',
'timing' => 'required',
'file' => 'file',
'lesson_id' => 'required',
'video' => 'required',
'description' => 'required'
]);
$lecture = Lecture::findOrFail($id);
$lecture->title = $request['title'];
$lecture->timing = $request['timing'];
$lecture->lesson_id = $request['lesson_id'];
$lecture->video = $request['video'];
$lecture->description = $request['description'];
// Fichier
$file = $request->file('file');
if ($request->hasFile('file')) {
$fileName = $file->getClientOriginalName();
$fileExtension = $file->getClientOriginalExtension();
$destinationPath = public_path('chapitres-files');
$file->move($destinationPath, $fileName);
$lecture->file = 'chapitres-files/' . $fileName;
}
So, can someone explain me what to do exactly in my controller, in my view file and also in my web.php?
Thank you very much!
Gastono
Upvotes: 2
Views: 2032
Reputation: 4032
You have 2 main scenarios to cover:
Scenario 1: Removing a file from a form object
I will point you at this question as a starting point as I am not a Javascript expert
How do I remove a file from the FileList
Scenario 2: Removing a file from storage
As mentioned in the comments, in this scenario you will want to remove the file as a seperate action rather than as part of your Edit / Update code.
This keeps your destructive actions seperate from your constructive actions
The way I would approach this is:
FileController
) with a destroy
method on itapi/files/destroy/{file_id}
)Note: I would suggest also adding an confirmation step to your "delete" button (like a modal or alert) to make the user confirm that they do indeed want to delete the file
Upvotes: 1