From Query

In the previous example, we did the query inside the export class. While this is a good solution for small exports, for bigger exports this will come at a hefty performance price.

By using the FromQuery concern, we can prepare a query for an export. Behind the scenes this query is executed in chunks.

In the InvoicesExport class, add the FromQuery concern and return a query. Be sure to not ->get() the results!

namespace App\Exports;

use App\Invoice;
use Nikazooz\Simplesheet\Concerns\Exportable;
use Nikazooz\Simplesheet\Concerns\FromQuery;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function query()
    {
        return Invoice::query();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

We can still download the export in the same way:

return (new InvoicesExport)->download('invoices.xlsx');
1

Customizing the query

It's easy to pass custom parameters to the query, by simply passing them as dependencies to the export class.

As constructor parameter

namespace App\Exports;

use App\Invoice;
use Nikazooz\Simplesheet\Concerns\Exportable;
use Nikazooz\Simplesheet\Concerns\FromQuery;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function __construct(int $year)
    {
        $this->year = $year;
    }

    public function query()
    {
        return Invoice::query()->whereYear('created_at', $this->year);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The year can now be passed as dependency to the export class:

return (new InvoicesExport(2018))->download('invoices.xlsx');
1

As setter

namespace App\Exports;

use App\Invoice;
use Nikazooz\Simplesheet\Concerns\Exportable;
use Nikazooz\Simplesheet\Concerns\FromQuery;

class InvoicesExport implements FromQuery
{
    use Exportable;

    public function forYear(int $year)
    {
        $this->year = $year;

        return $this;
    }

    public function query()
    {
        return Invoice::query()->whereYear('created_at', $this->year);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

We can adjust the year by using the forYear method:

return (new InvoicesExport)->forYear(2018)->download('invoices.xlsx');
1