Laravel-Excel: export Eloquent Models results easily

Today I want to briefly overview one package Laravel-Excel. I probably don't need to explain its purpose - the title says everything. But what I do want to show you is how easy it is to export data to Excel using Eloquent. Basically, Laravel-Excel package is using PHPExcel under the hood, just re-purposing it for Laravel specifically.

Laravel-Excel installation

Ok, boring part. Usual stuff: 1. composer.json:
"maatwebsite/excel": "~2.0.0"
When installing, we see the dependencies visually: 1111_laravel_composer 2. config/app.php:
Maatwebsite\Excel\ExcelServiceProvider::class
and
'Excel' => Maatwebsite\Excel\Facades\Excel::class
3. Publishing the config:
php artisan vendor:publish

Now, the magic

Let's say we have a usual users table - the default one from Laravel installation. And let's say we want to export that to Excel - but only some fields (we don't want to expose passwords, even hashed, do we?).
$users = User::select('id', 'name', 'email', 'created_at')->get();
Excel::create('users', function($excel) use($users) {
    $excel->sheet('Sheet 1', function($sheet) use($users) {
        $sheet->fromArray($users);
    });
})->export('xls');
The result is a downloaded file users.xls (filename comes from the parameter Excel::create('users' ...), which looks like this: 1111_laravel_excel Sweet, isn't it?
Want more articles like this every week? Subscribe!
Still not sure? Want to check out past newsletter issues? Here they are - just click this link!
Of course, Laravel-Excel has much more functions. You can style your sheets, also import data into your database from Excel and do various other stuff. Keep in mind that there are some requirements for the package to work properly - here's the list from the docs:
  • PHP version >= 5.3.7
  • Laravel >= 4.1
  • PHPOffice PHPExcel >= 1.8.0 (included by composer.json)
  • PHP extension php_zip enabled (required if you need PHPExcel to handle .xlsx .ods or .gnumeric files)
  • PHP extension php_xml enabled
  • PHP extension php_gd2 enabled (optional, but required for exact column width autocalculation)
You can find full documentation here: http://www.maatwebsite.nl/laravel-excel/docs

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord