How to export a database table to Excel in Laravel

Overview

In this shot, we will learn how to integrate the fast-excel package and quickly export our model.

First, you simply need to install the package to your application and Laravel will make it available when you import the Rap2hpoutre\FastExcel\FastExcel class to your controller. You can do so using the following command:

use Rap2hpoutre\FastExcel\FastExcel;

Package installation

You can install the required package by running the composer command:

composer require rap2hpoutre/fast-excel

Implementation and example

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Rap2hpoutre\FastExcel\FastExcel;//Ensure to import the class
use App\User;
class excelExportController extends Controller
{

 public function index(){
// Load users
$users = User::all();

// Export all users
(new FastExcel($users))->export('file.xlsx');
}
}

Explanation

In the example above, we import the use Rap2hpoutre\FastExcel\FastExcel; class. If you forget to import this class, your code will display a class not found error.

In this shot, we make a controller, but it can also be implemented in any of the existing controllers. We also make an index function that is responsible for carrying out the export of the database table. In this example, we exported the users table.

We first use $users = User::all(); to fetch all the users. Then, we instantiate new FastExcel($users)), which will call the fastexcel package. We also pass $user and chain it with ->export('file.xlsx');. The export method is responsible for exporting the model and accepts the name you prefer to give the exported model. In this case, we name it file.xlsx.

Output

The output will be an Excel sheet with the name file.xlsx. It can be found in your application.

Free Resources