DEV Community

Cover image for How to Export Database Records to Excel using PHP(Laravel)
John Samuel Obinna
John Samuel Obinna

Posted on

How to Export Database Records to Excel using PHP(Laravel)

Have you encountered a challenge where you need to export records from the database to excel using Laravel?

We will be using Maatwebsite Laravel package

Installation

First require the Maatwebsite laravel package in your composer.json

composer require maatwebsite/excel
Enter fullscreen mode Exit fullscreen mode

The Maatwebsite\Excel\ExcelServiceProvider is registered by default. But you can manually register the ServiceProvider in your config/app.php

'providers' => [
    /*
     * Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]

Enter fullscreen mode Exit fullscreen mode

The Excel Facade is discovered and registered by default. But you can add it manually to your config/app.php

'aliases' => [
    ....
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]


Enter fullscreen mode Exit fullscreen mode

Publish config by running the vendor command

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

This will create a new config file named config/excel.php. and your setup is completed.

Exporting

On our already seeded database, we will be exporting those records to an excel file.Checkout how to seed in laravel First we create a controller using:

 php artisan make:controller ExportToExcelController
Enter fullscreen mode Exit fullscreen mode

then we create an export class in the app\Export using the:

php artisan make:export UsersExport --model=User
Enter fullscreen mode Exit fullscreen mode

the UsersExport is the Export class while the flag --model=User is referencing the model class in use.

The result of the command php artisan make:export UsersExport --model=User:


<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}


Enter fullscreen mode Exit fullscreen mode

Head over to your ExportToExcelController you can export records


<?php

namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;

class ExportToExcelController extends Controller 
{
    public function ExportRecords() 
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
}


Enter fullscreen mode Exit fullscreen mode

Ooh one more thing, add a route to be able to access ExportRecords:

Route::get('data/export/', 'ExportToExcelController@ExportRecords');
Enter fullscreen mode Exit fullscreen mode

Thats IT! ๐Ÿ˜Ž

Top comments (0)