File Upload & Delete helper function for Laravel

File Upload & Delete helper function for Laravel

Here is a quick helper function to upload the file in laravel application.

if (!function_exists('upload_file')) {
    function upload_file($request, $name, $path)
        // //handle file upload
        if ($request->hasFile($name)) {
            //Get file name with extension
            $fileNameWithExt = $request->file($name)->getClientOriginalName();

            //Get just filename
            $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
            //Get just extension
            $fileextension = $request->file($name)->getClientOriginalExtension();

            $fileNameToStore = md5($fileName . '_' . time()) . '.' . $fileextension;
            $pathToStore = $request->file($name)->storeAs('public/' . $path, $fileNameToStore);
            return "storage/" . $path . $fileNameToStore;


  • $request is the instance of Illuminate\Http\Request which contains all the request post informations.

  • $name is the identifier of the file to be uploaded. This is generally the name value of the file input field.

  • $path is the writable directory to where the file should be uploaded.

That's it, add this function to the helper.php and use anywhere through out the laravel project.

Here is a function to delete the file

if (!function_exists('delete_file')) {
    function delete_file($path)


  • $path is the path of the file to be deleted.

That's it. Thanks for reading. Happy Coding!