Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Maatwebsite excel array

Tags:

php

laravel

I'm a newbie in Laravel, but I'm using laravel's Maatwebsite\Excel Library v3 to export excel. But I'm having some problems exporting my array data.

here is my code

    <?php

namespace App\Exports;
use App\Team;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;

class RegisteredMemberExport implements FromCollection, WithHeadings
{
    use Exportable;

    public function collection()
    {

     $data = Team::where('reg', 1)->get();       

        return collect([
            [
                'name' => $data->name,
                'email' => $data->email
            ]
        ]);
    }

    public function headings(): array
    {
        return [
            'name',
            'email'
        ];
    }

}

the collect should be

return collect
([
            [
                'name' => 'Povilas',
                'email' => '[email protected]'
            ],
            [
                'name' => 'Taylor',
                'email' => '[email protected]'
            ]
        ]);

I can't use a loop inside the collect method return. Can I please have some help?

like image 312
Anni Eder Avatar asked Jun 15 '26 01:06

Anni Eder


1 Answers

You can directly filter the values you need from your Eloquent model using a list of attributes as a parameter for the get method.

$data = Team::where('reg', 1)->get(['name', 'email']);

return collect($data->toArray());
like image 134
Reda Bezzerrouki Avatar answered Jun 17 '26 21:06

Reda Bezzerrouki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!