Home > Back-end >  Laravel export file with dynamic name
Laravel export file with dynamic name

Time:10-28

I am running a script that stores the collected data in csv. It's working like that:

$responce =  Excel::store(new UsersExport($formatted_data), 'fileName.csv', null, \Maatwebsite\Excel\Excel::CSV); 

And that's my class:

class UsersExport implements FromArray
{
    protected $invoices;

    public function __construct(array $invoices)
    {
        $this->invoices = $invoices;
    }

    public function array(): array
    {
        return $this->invoices;
    }
}

So far the filename is hardcoded and I want to make it dynamic. It should be changed with the year and the month every time I run new export (2020-01.csv or something like that) The script is running with two parameters - year and month.

protected $signature = 'select:values {--year=} {--month=}';

In the where clause I am filtering like that:

->whereMonth('ut', $this->option('month'))   
->whereYear('ut', $this->option('year'))

Tried with

Excel::store(new UsersExport($formatted_data)->withFilename()

But it does not work...I have not found something similar to my solution so far. Any ideas on how to fix that? Thanks!

CodePudding user response:

Can you try this one?

$responce = Excel::store(new UsersExport($formatted_data), now()->format('Y-m').'.csv', null, \Maatwebsite\Excel\Excel::CSV);

CodePudding user response:

My solution is: With simple php concatenation...

$fileName = $this->option('year')."-".$this->option('month').".csv";

And putting the variable in the export like this: $responce = Excel::store(new UsersExport($formatted_data), $fileName ,null, \Maatwebsite\Excel\Excel::CSV);

  • Related