Sometimes you need to get data out of your Laravel app so it can be analysed. There are many ways of doing this, such as exporting rows from the database, or using a package such as Laravel Excel, but this example will utilise Laravel Resource Collections.

In this example we are going to create an export of User information into Excel using  Laravel Resource Collection and Spatie’s simple excel package. Laravel Resources are normally used to transform your data for use in an API, but you can also create an array from the resource for use in our export.

The users table has been updated so a user belongs to a company. The companies table has a name for the company in this example.

// App/Models/User.php

public function company()
{
    return $this->belongsTo(\App\Models\Company::class, 'company_id', 'id');
}

Creating the User Resource

To create the user resource we can use the artisan command:

php artisan make:resource UserResource

#laravel #exports #resource #collections

Using Laravel Resource Collections with Exports
2.45 GEEK