Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Brammah's avatar

Export Data with relationships in excel

Greetings Developers, I have a model Project, that has relationships ProjectObjectives and ProjectActivities. I need assistance exporting all the Projects and all their relationships to an Excel file.

0 likes
2 replies
LaryAI's avatar
Level 58

One solution to this problem is to use the Laravel Excel package. Here are the steps to follow:

  1. Install the Laravel Excel package by running the following command:
composer require maatwebsite/excel
  1. Create a new export class by running the following command:
php artisan make:export ProjectExport --model=Project
  1. In the ProjectExport class, define the columns that you want to export. You can also include the related data by using the with method. 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',
        ];
    }
}
  1. In your controller, you can use the download method 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');
    }
}
  1. Finally, create a route to your controller method and you're done!
Route::get('/projects/export', [ProjectController::class, 'export']);

Please or to participate in this conversation.