Exporting data from your MySQL database to Excel can be a valuable feature for generating reports and sharing data with others. Laravel, a popular PHP framework, makes this process straightforward using the "Maatwebsite Excel" package. In this tutorial, we'll walk you through the steps to export data from MySQL to Excel in a Laravel application.
Step 1: Install the Maatwebsite Excel Package
Begin by installing the "Maatwebsite Excel" package using Composer:
composer require maatwebsite/excel
Step 2: Create a New Export Class
Generate a new export class using the Artisan command:
php artisan make:export UsersExport --model=User
This command will create a new export class named UsersExport
in the Exports
directory. Modify the UsersExport.php
file to define the data you want to export.
Step 3: Define Exportable Data
In the export class (UsersExport.php
), implement the FromCollection
interface and define the data you want to export. For example:
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
Step 4: Create an Export Route
In your web.php
routes file, create a route to trigger the export:
use App\Exports\UsersExport;
Route::get('/export-users', function () {
return Excel::download(new UsersExport, 'users.xlsx');
});
Step 5: Create a Link to Trigger Export
In your Blade view, create a link that triggers the export route:
<a href="{{ url('/export-users') }}">Export Users to Excel</a>
Step 6: Run Your Application
Now you can run your Laravel application and access the link you created. Clicking the link will initiate the export process, and a file named users.xlsx
containing the exported data will be downloaded.
Customizing the Export:
You can customize the export by adding additional methods to your export class. For example, you can define column headers, control the export format, and modify the exported data.
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UsersExport implements FromCollection, WithHeadings
{
use Exportable;
public function collection()
{
return User::select('id', 'name', 'email')->get();
}
public function headings(): array
{
return ['ID', 'Name', 'Email'];
}
}
Exporting data from MySQL to Excel in a Laravel application is made simple by utilizing the "Maatwebsite Excel" package. By creating an export class, defining the data to be exported, and setting up a route, you can easily generate Excel files containing your database records. This feature is invaluable for generating reports and sharing data in a user-friendly format. Whether you're building administrative dashboards, data analysis tools, or any other application, Excel exports can enhance the usability and accessibility of your data.