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.

Comments

Submitted by luis orozco (not verified) on Fri, 06/18/2021 - 18:05 Permalink

Thanks for the info.
Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon