Laravel Excel
1. Installation (if not already installed) If the package is not already installed, run the following in the terminal:
composer require maatwebsite/excel
2. Creating an Export Class Laravel Excel uses special classes to generate files.
Create it with the following command:
php artisan make:export DealsExport --model=Deal
Edit the created file app/Exports/DealsExport.php so that it exports only the necessary fields, not all:
namespace App\Exports;
use App\Models\Deal;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class DealsExport implements FromCollection, WithHeadings
{
public function collection()
{
// Выгружаем имя сделки и название стадии
return Deal::with('stage')->get()->map(function($deal) {
return [
'ID' => $deal->id,
'Name' => $deal->name,
'Stage' => $deal->stage->name,
'Created At' => $deal->created_at->format('d.m.Y'),
];
});
}
public function headings(): array
{
return ['ID', 'Deal Name', 'Stage', 'Date Created'];
}
}