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

Ligonsker's avatar

How to export to excel using Laravel Fast-Excel and JavaScript's fetch?

Hello,

I am currently using Laravel Fast-Excel with the Chunks method: https://github.com/rap2hpoutre/fast-excel?tab=readme-ov-file#export-large-collections-with-chunk

I have the following in my controller:

public function download_excel(Request $request)
{
    return (new FastExcel(usersGenerator()))->download('file.xlsx');
}
    
public function usersGenerator() {
    foreach (User::cursor() as $user) {
        yield $user;
    }
}

In order to actually trigger the download from the browser, I have a button that opens the route in a new tab:

document.querySelector("#excel-download-button").addEventListener("click", function(event) {
    window.open('/excel-download', '_blank');
});

So the tab is opened for a split second, the download starts and the tab closes.

But I want to skip this behavior of using the new tab.

Is it possible to download it directly from a fetch request?

Something like this:

    fetch('/excel-download')
      .then(response => {
        // ... download ...
      });

I couldn't find the way to do that

Thanks

0 likes
3 replies
DanteB918's avatar

Have you tried wrapping your button with an anchor tag?


<a href=“/excel-download”><button>Download</button></a>

Could probably even remove the button tag altogether and just change it to an anchor. Might mess with some styling though

1 like
Ligonsker's avatar

@DanteB918 Oh yes I also have that. I was just wondering if it has to be done via opening a new link (either by JavaScript window.open, or by an <a> tag

Or I can do it in a way that won't open a new link to the user, even if it's just for a split second

1 like
DanteB918's avatar

@Ligonsker that can also be done, but you’d need to use a POST request. Change the route to be Route::post, and change the fetch to use the post method rather than window.open()

fetch('/excel-download', {
  Method: 'POST',
});

You may also need to download the file to your temp dir and then use response->download(“path/to/download”); in your controller.

Please or to participate in this conversation.