Laravel Excel从具有自定义标题的模型导出

I'm trying to export some data from my Multiple Models into a single excel sheet with custom header names using http://www.maatwebsite.nl/laravel-excel/docs

using ->fromModel($model) method in Laravel Excel, would grab the headers from the attribute names given to the table, of only that particular selected model.

I've set my Users model with ->hasOne() relationship to 3 other models. Yet it displays content of only the main model in the excel. Is there any way to do this?

Since you haven't specified the model names, for this answer I'm assuming you have a User and Type models and the User model is something like this:

class User extends Authenticatable
{
    // ....

    public function type()
    {
        return $this->hasOne('App\UserType');
    }
}

I'm assuming you're trying to do something like the following to export your data:

$sheet->fromModel(User::with('type')->get());

If you perform a dd(User::with('type')->get()); you'll see that the attributes property on each item on the collection has only the attributes of the User model and this is why you only get the information about the User model.

To fix this you have a few solutions:

  1. Perform a query using Eloquent without the relations. Something like the following:

    $data = User::join('types', 'types.user_id', '=', 'users.id')->get();
    

    In this case you'll see that the attributes for each item on the collection have all the columns requested.

  2. Create a view on SQL/MySQL and create a model associated with that view. This way, for Laravel purposes, you're retrieving data from a single table.

My preferred way is the first, and here's an example on how you could export the data:

Excel::create('Filename', function($excel){
    $excel->sheet('Sheetname', function($sheet) {
        $data = User::join('types', 'types.user_id', '=', 'users.id')->get();
        $sheet->fromModel($data);
    });

})->export('xls');