How to export excel from database in laravel?

by edmond_brakus , in category: PHP Frameworks , 7 months ago

How to export excel from database in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 6 months ago

@edmond_brakus 

To export data from a database to an Excel file in Laravel, you can use the Laravel Excel package, which provides a simple way to export data to various formats, including Excel.


Here's a step-by-step guide on how to export data to an Excel file in Laravel using the Laravel Excel package:

  1. Install the Laravel Excel package by running the following Composer command in your terminal:
1
composer require maatwebsite/excel


  1. Once the package is installed, publish the configuration file by running the following artisan command in your terminal:
1
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"


  1. Create a new controller in your Laravel application by running the following artisan command in your terminal:
1
php artisan make:controller ExportController


  1. In the ExportController controller, add a method to export data to an Excel file. For example, you can add the following method to export data from a database table named users:
1
2
3
4
5
6
use MaatwebsiteExcelFacadesExcel;

public function exportUsers()
{
    return Excel::download(new UsersExport, 'users.xlsx');
}


  1. Create an export class to define the data and format for the Excel file. You can generate an export class by running the following artisan command in your terminal:
1
php artisan make:export UsersExport --model=User


  1. Update the UsersExport export class with the data and format for the Excel file. For example, you can define the columns to export in the collection method:
1
2
3
4
5
6
7
8
9
use MaatwebsiteExcelConcernsFromCollection;

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


  1. Finally, create a route to access the export functionality in your Laravel application. For example, you can add the following route to the routes/web.php file:
1
Route::get('/export/users', 'ExportController@exportUsers');


Now you can access the export functionality by visiting the /export/users URL in your Laravel application, which will generate an Excel file containing the data from the users table.