0

I'm trying to export a csv file with Maatwebsite\Excel and Laravel 9.

As a response, I get my datas and headings in console > network , but no download occurs.

Here's my code :

Exports

namespace App\Exports;

use App\Models\Data;
use Illuminate\Support\Facades\Schema;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;


class DataExport implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Data::all();
    }

    public function headings():array{
        return[
           Schema::getColumnListing('data') 
        ];
    }
}

And my controller (1st try) :

public function download_file_csv()
{
    Excel::store(new DataExport, 'dataTemplate.csv');
    Excel::download(new DataExport,'dataTemplate.csv',\Maatwebsite\Excel\Excel::CSV, [
        'Content-Type' => 'text/csv',
    ]);
}

and 2nd try

public function download_file_csv()
{
    Excel::store(new DataExport, 'dataTemplate.csv');
    return Excel::download(new DataExport,'dataTemplate.csv');
}

The file with datas and headings is properly stored in my public folder...

Thanks in advance,

AdBess
  • 11
  • 5
  • The command looks okay. Is the return statement in `download_file_csv()` being sent as a response? If you are calling it from another method, it must be returned again, all the way until it is sent as a response. – matticustard Dec 16 '22 at 01:10
  • @matticustard , my datas are displayed in the network > response section of the console . So i think that yes. How can I be sure ? Thanks – AdBess Dec 19 '22 at 07:27
  • 1
    Are you trying to download an AJAX response? If so, this requires additional JS code on the client side, as downloading a file normally requires opening a new page. All of the code provided above is from the server side. See if this helps: https://stackoverflow.com/a/27563953/5309998 – matticustard Dec 19 '22 at 21:09
  • @matticustard, thanks ! Yes, close : i'm trying to download my file from a fetch response. I tried to download the file from a link and clicking on it with js without success (file not found although it's present in the folder). Can you help me with the code on the client side pls ? – AdBess Jan 02 '23 at 21:03

0 Answers0