Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cooperino's avatar

Can I redirect to a page after a download?

Using the following code to download a file:

public function download_file(Request $request)
{
    return Storage::disk('s3')->download($request->file_path);
}

The download_file method is being called from the front end with JavaScript using

window.location.href = url_to_download_file_method;

I want to redirect to another page after the download is triggered. Is it possible?

0 likes
9 replies
Sinnbeck's avatar

No and yes. You would need to handle the download in Javascript and then redirect in Javascript as well. But downloads with js is tricky

1 like
cooperino's avatar

@sinnbeck So right now I'm basically in a loop: The page calls my controller download method using location.href and the controller returns a download trigger which means none of these 2 can redirect.

Is there a simple way to change the logic so that my page will trigger Storage::disk('s3')->download($request->file_path); and make it redirect as well? (Doesn't have to be JavaScript)

MohamedTammam's avatar

If you are using Javascript, you can open a tab for the download and then redirect the user in the current window.

window.open(url_to_download_file_method, '_blank'); // Opens a new tab

// Redirect the user
// ...
cooperino's avatar

@MohamedTammam I tried that, but the problem is that the browsers today recognize it as a pop up and block it :/

MohamedTammam's avatar

@cooperino Use that trick.

let a = document.createElement('a');
a.href = url_to_download_file_method;
a.target = '_blank';
a.click();
1 like
MohamedTammam's avatar

@cooperino Try to add first in the page.

let a = document.createElement('a');
a.href = url_to_download_file_method;
a.target = '_blank';
document.body.appendChild(a);
setTimeout(() => {
	a.click();
	document.body.removeChild(a);
}, 500);
1 like
cooperino's avatar

@MohamedTammam I found another solution, using JS fetch API (from SO):

fetch(downloadUrl)
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    window.location = redirectUrl; //redirect
  })
  .catch(() => alert('error));

Please or to participate in this conversation.