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

M.Yanis's avatar

API how to download file

Hello everyone,

I have created an Endpoint Api and I would like it to download an .xls file (.xls export). here is my endpoint :

public function exportXls(Request $request): Response|BinaryFileResponse
    {
        return (new UserExport())->forCustomer($request->id)->download('user.xlsx', Excel::XLSX);
    }

I can download the file when the function isn't in the api controller but when I switch to Api I can't, I have to retry a response()->download but I don't know how someone to help me please

0 likes
4 replies
Sinnbeck's avatar

Are you using session anywhere in the code (like the export) ?

What exactly happens?

M.Yanis's avatar

When I click on the export .xls button I get access to my endpoint and I have a status code 200. with a strange response like this:

PK�r�UG�D�Z�[Content_Types].xml���N�0E�|E�-J��@5��*Q>`�'�UǶl���L����@�nbE�gr=��tW�d�>(k
6�r��V*�,���)�cI�`$hk�`{l:�/�CBb
.....

I know where is the problem, I have to return a response, but I don't know how, if I do response()->(new UserExport())->forCustomer($request->id)->download('user.xlsx', Excel::XLSX); it is underline in red

Sinnbeck's avatar

@M.Yanis The button ? What does the button do ? Is it a link ?

What if you open the url directly in a browser tab ?

M.Yanis's avatar

@Sinnbeck I'm sorry I didn't explain it well So in my front-end page I have a button named "export .xls". The purpose of this button is to download an .xls file.

here is the code of the button on the front end

 <Button
        variant="outlined"
        size="small"
        onClick={(e) => handleClick(e)}
        startIcon={<GridOnIcon />}>
         Export .XLS
  </Button>

And here is the route in api.php :

Route::get('/user/export', 'UserController@exportXls')->name('users.export');

when I click on the button I access well in the function (i tested with a dd()) but nothing happens and when i inspect element > network in the response there is the weird code i sent you before.

What if you open the url directly in a browser tab ? => nothing happens

Please or to participate in this conversation.