how to unlink file in laravel

Pinterest LinkedIn Tumblr

In Laravel, you can use the unlink function to delete a file from the file system. The unlink function is a built-in PHP function that deletes a file by its path.

Here’s an example of how you might use the unlink function in a Laravel controller to delete a file:

Copy codepublic function deleteFile($id)
    $file = File::find($id);
    $path = public_path().'/'.$file->path;
        return redirect()->back()->with('success', 'File has been deleted successfully');
    return redirect()->back()->with('error', 'File could not be deleted');

In this example, the deleteFile method takes in an $id parameter and uses it to find the file in the database using the File model. It stores the file’s path in the $path variable. Then, it uses the unlink function to delete the file from the file system, passing in the $path variable. If the file is deleted successfully, it will delete the file record from the database and redirect the user back with a success message. If the file could not be deleted, it will redirect the user back with an error message.

It’s important to note that the unlink function will only delete a file if the file exists and the user has permission to delete the file. If the file does not exist or the user does not have permission to delete the file, the unlink function will return an error.

You can also use the Storage facade to delete a file, this facade is built on top of the Flysystem filesystem abstraction library.

Copy codeuse Illuminate\Support\Facades\Storage;


You can also use the Storage::disk method to delete a file from a specific disk,

Copy codeStorage::disk('s3')->delete('file.jpg');

This way you can delete a file from a specific disk.

Write A Comment