In this shot, we will learn how to export multiple models from a database to an Excel sheet, and also name the sheet.
We will use the FastExcel
package to carry out this task.
You can use a composer command to install the package:
composer require rap2hpoutre/fast-excel
<?php
namespace use App\Models\User;
use App\Models\Project;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Rap2hpoutre\FastExcel\FastExcel;
use
class exportModels extends Controller
{
public function index(){
$sheets = new SheetCollection([// creating a sheet collection
'Users' => User::all(),//Fetch users model with sheet name as user
'Second sheet' => Project::all()//Fetch project model with sheet name as project
]);
(new FastExcel($sheets))->export('file.xlsx');// passing the created sheet model and saving the file as `*file.xlsx*
}
}
In the example above, we create a sheet collection that helps save both the users
and projects
models. Then, we pass the models to FastExcel
, which fetches the model data to the Excel sheet alongside the export
method, which allows us to name the file and save it.
RELATED TAGS
CONTRIBUTOR
View all Courses