Gastono
Gastono

Reputation: 21

Laravel - Remove uploaded file in a form

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 :

Upload file field

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

Answers (1)

Spholt
Spholt

Reputation: 4032

You have 2 main scenarios to cover:

  1. A user adds file to the form but the decides to remove it before upload
  2. A user has already uploaded a file and now wants to delete it

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:

  1. Create an API Controller for your files (FileController) with a destroy method on it
  2. Create an API Route for your files (api/files/destroy/{file_id})
  3. Use javascript to fire an AJAX request to your API Route with the identifier for the file you want to delete

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

Related Questions