maltekiefer's avatar

Can't delete files

Hello,

this is how I handle a file upload:

        $fileModel = new File;

        if ($request->file()) {
            $fileName = time() . '_' . uniqid() . '_' . $request->file->getClientOriginalName();
            $filePath = $request->file('file')->storeAs('assets', $fileName, 'local');

            $fileModel->name = $request->file->getClientOriginalName();
            $fileModel->file_path = '/storage/' . $filePath;
            $fileModel->save();

            $data = ['filename' => $fileName];

            $fileDB = File::where('name', $fileModel->name)->first();

            if ($request->addressid) {
                $address = Address::find($request->addressid);
                $address->files()->attach($fileDB->id);

            } elseif ($request->salestaskid) {
                $salestask = Salestask::find($request->salestaskid);
                $salestask->files()->attach($fileDB->id);
            }

            return response()->json($data, 200);
        }

That's works like a charm. Now I want to delete a file:

        $path = File::where('name', $filename)->first();

        $filename_new = str_replace('/storage/assets/', '', $path->file_path);

        if (!Storage::disk('local')->exists('assets/'.$filename_new)){
            return response()->json('', 404);
        }
        File::find($path->id)->address()->detach($path->id);
        File::destroy($path->id);

From the file the entry is deleted but not from the pivot table and not from the file system. What I am doing wrong?

0 likes
4 replies
vincent15000's avatar

Hello, I have tested too with no success ... if somebody has a solution, I'd like to have it too.

To delete a file, I use the unlink() php function.

neilstee's avatar

@maltekiefer should you delete the file this way:

Storage::disk('local')->delete('assets/'.$filename_new);

And for the File model I think the easy way is to cascade on delete on your migration file?

neilstee's avatar
neilstee
Best Answer
Level 34

For detach, I think you should detach an address ID?

If I'm correct, your files has many address, so it means you are detaching an address to the file. So was it supposed to be an address ID that you need to pass on ->detach() and not the $path->id?

1 like
maltekiefer's avatar

That was it. Now it looks like this and it works:

    public function fileDelete($filename, $addressid){

        $path = File::where('name', $filename)->first();

        $filename_new = str_replace('/storage/assets/', '', $path->file_path);

        if (!Storage::disk('local')->exists('assets/'.$filename_new)){
            return response()->json('', 404);
        }
        File::find($path->id)->address()->detach($addressid);
        File::destroy($path->id);

        Storage::disk('local')->delete('assets/'.$filename_new);
    }
1 like

Please or to participate in this conversation.