Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

fast-excel
laravel
php

How to Download Your Database Table As An Excel Sheet in Laravel?

Chinweuba Elijah Azubuike

Overview

In a previous shot, we learnt how to export database table as an excel sheet (Look it up), it is exported into your application, in this shot we would look at how to download it to your devices from your web application.

Why Download your database table?

Most times you just need to send the report to your customers on how they’ve been performing or maybe you just need a list of registered users and their status for presentation. There are really numerous why you will want to download a database table as an excel sheet. In this sheet, we would be doing this using the Fast-Excel package, which will help us do this effectively.

Package Installation

We would install the package using composer command, like so;

composer require rap2hpoutre/fast-excel

after installing the package you can use it/implement it in your controller

Implementation and Example


<?php

namespace App\Http\Controllers;
use Rap2hpoutre\FastExcel\FastExcel;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class pdfDownloadController extends Controller
{

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

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

Example Explained

From the above example, you will notice that we imported the use Rap2hpoutre\FastExcel\FastExcel; class, which will throw an error if not imported. We made a controller execute this action but you can implement the function in any other controller so long as you import the fastExcel class. In the created controller I made an index function which will handle the download process, in the function we first retrieve all users of the database then we returned the downloaded file by calling the fastExcel package where we passed the $user and chained it to the download() method where I gave the file a name of my choosing(file.xlsx). Hope you learnt something new!

Output

widget

I use an IDM(Internet download manager) but you should receive a prompt from you browser to download the file

RELATED TAGS

fast-excel
laravel
php

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring