n Deleting a File from Storage after Download in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Deleting a File from Storage after Download in Laravel

 

Let's assume you have a file in storage/app/download.zip:

Because Laravel uses Symfony's HttpFoundation internally, you can use the deleteFileAfterSend method:

public function download()
{
    return response()
        ->download(storage_path('app/download.zip'))
        ->deleteFileAfterSend(true);
}

 

or you can  create a Terminable Middleware that deletes the file after the download response was prepared.

class StorageDownload
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        \Storage::delete('download.zip');
    }
}

 

As for triggering the download using JavaScript, something as trivial as setting the window location will work:

axios.post('files/export/' + file.id, formData)
    .then(function() {
        window.location = 'files/download/' + file.id
    });

Don't worry, this will not navigate away from your current page, it will just trigger the download.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook