Effortlessly generate Excel files for reliable data sharing
I think we’ve gotten to a good point with Imports in the previous 8 articles. It’s time to switch to exporting data into Excel sheets. Laravel-Excel is pretty amazing. It simplifies all of this for us.
Since we’ve been working with our User
model this whole time, let’s create a quick export. First thing is to create our Exporter and specify that we want to use the User
model.
php artisan make:export UsersExport --model=User
This generates a new file and a new directory under the app
directory called app/Exports/UsersExport.php
.
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::all();
}
}
As you can see, it returns all of our users as a collection
. We now have to call the export. We’ll create our export_users
method in our UserController
and then create a route that calls that method.
<?php
namespace App\Http\Controllers;
//...
use App\Exports\UsersExport;
use App\Models\User;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class UserController extends Controller
{
//...
public function export_users() {
return Excel::download(
new UsersExport,
'users.xlsx'
);
}
}
First thing to note is that we are using the download
method from Excel
. Next thing to note is that we’re returning it. The return
triggers the download to occur. The download will be named users.xlsx
.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Artisan;
//...
Route::get(
'/export-users',
[UserController::class, 'export_users']
);
Look at all those users. This was just a quick intro. Once you get it going, we’ll continue with some more advanced stuff like creating multiple sheets.
Laravel Series
Continue your Laravel Learning.
Scale up data imports with queue-based execution.
Laravel-Excel — P8: Queued Import
In the eighth installment of our Laravel-Excel series, discover how to utilize queued imports to handle large and complex data loads without blocking your application. Learn how to combine job management, chunk reading, and parallel processing for fast, reliable data ingestion.
Effortlessly generate Excel files for reliable data sharing
In the ninth installment of our Laravel-Excel series, discover how to efficiently generate Excel files from your application’s data. Learn best practices for handling large datasets, customizing export structures, and ensuring consistent, secure file delivery.
Generate visually rich Excel files directly from your Blade views.
Laravel-Excel — P10: Export from View
In the tenth installment of our Laravel-Excel series, discover how to export data directly from Blade views. Learn to incorporate dynamic HTML content into your spreadsheets, preserving the styling and layout for custom, visually appealing Excel files.