Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 7, 2021 12:20 pm GMT

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:

<?phpnamespace 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

<?phpnamespace 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!


Original Link: https://dev.to/adroitcoder/how-to-export-database-records-to-excel-using-php-laravel-1g30

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To