Level 58
One solution to this problem is to use the Laravel Excel package. Here are the steps to follow:
- Install the Laravel Excel package by running the following command:
composer require maatwebsite/excel
- Create a new export class by running the following command:
php artisan make:export ProjectExport --model=Project
- In the
ProjectExportclass, define the columns that you want to export. You can also include the related data by using thewithmethod. Here's an example:
use App\Models\Project;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
class ProjectExport implements FromQuery, WithMapping, WithHeadings
{
public function query()
{
return Project::query();
}
public function map($project): array
{
return [
$project->id,
$project->name,
$project->description,
$project->projectObjectives->pluck('name')->implode(', '),
$project->projectActivities->pluck('name')->implode(', '),
];
}
public function headings(): array
{
return [
'ID',
'Name',
'Description',
'Objectives',
'Activities',
];
}
}
- In your controller, you can use the
downloadmethod to generate the Excel file and download it. Here's an example:
use App\Exports\ProjectExport;
use Maatwebsite\Excel\Facades\Excel;
class ProjectController extends Controller
{
public function export()
{
return Excel::download(new ProjectExport, 'projects.xlsx');
}
}
- Finally, create a route to your controller method and you're done!
Route::get('/projects/export', [ProjectController::class, 'export']);