Laravel 8 Create Excel File From Database Rows

Share this Article
Reading Time: 5 minutes
683 Views

Inside this article we will see how to create Excel File from database rows. We will take database values into an array and then easily we will convert array value to a Excel file.

This tutorial will be super easy to understand and implement in your code. We will see the concept of Laravel 8 create Excel file from database rows.

Learn More –

Let’s get started.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Learn Composer Installation Steps. Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at system.


Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Database Table Rows

Suppose you have a database table named as countries. In that table you have some kind of data.

For this tutorial you can take any table from your application. The table we have taken, it’s only for demonstration.


Install maatwebsite/excel Package & Configuration

Open project into terminal and run this composer command to install package.

$ composer require maatwebsite/excel

After package installation, open app.php file from /config folder. Search for providers and aliases add these –

'providers' => [
        ....
        Maatwebsite\Excel\ExcelServiceProvider::class,
],

'aliases' => [
         ....
         'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

Create Export Class

Once you will install the above package. You will see we should have a command available in artisan list i.e make:export. We will use this command to create export class.

Open terminal and run this command –

$ php artisan make:export CountryExport

It will create a file CountryExport.php file inside /app/Exports folder.

Open CountryExport.php and write this complete code into it.

<?php
  
namespace App\Exports;
  
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
  
class CountryExport implements FromCollection, WithHeadings
{
    protected $data;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function __construct($data)
    {
        $this->data = $data;
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function collection()
    {
        return collect($this->data);
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function headings() :array
    {
        return [
            'id',
            'name',
            'sortname',
            'phoneCode'
        ];
    }
}

Create Controller

Next, we need to create a controller file.

$ php artisan make:controller DataExportController

It will create a file DataExportController.php at /app/Http/Controllers folder.

Open DataExportController.php and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\CountryExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Country;

class DataExportController extends Controller
{
    public function export() 
    {
        $countries = Country::select(["id", "name", "sortname", "phonecode"])->get();
          
        return Excel::download(new CountryExport($countries), 'countries.xlsx');
    }
}

Create Route

Open web.php from /routes folder and add these route into it.

//...

use App\Http\Controllers\DataExportController;

Route::get('export', [DataExportController::class, 'export']);

//...

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL: http://127.0.0.1:8000/export

Once you hit this URL, it will download the excel file with all rows from countries table.

We hope this article helped you to learn Laravel 8 Create Excel File From Database Rows Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on Laravel 8 Articles here