Codementor Events

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

Published Jul 07, 2021
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

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,
]

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,
]

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

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

php artisan make:export UsersExport --model=User

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();
    }
}

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');
    }
}

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

Route::get('data/export/', 'ExportToExcelController@ExportRecords');

Thats IT! 😎

Discover and read more posts from John Samuel
get started
post commentsBe the first to share your opinion
Show more replies