Search

How to export data as excel in laravel?

  • Share this:
post-title

welcome guys, In this article Here, we will know how to export excel in laravel. Making a export file and download in Laravel is simple and easy. if you have question about laravel export then i will give simple example with solution.

Step 1: Building a New Application

You can ignore this step if you already have an application downloaded or else, run the following command to create a brand new laravel project.

composer create-project laravel/laravel laravel-excel --prefer-dist

After downloaded new application or already installed then moved our application directory run the following command or using your own method

cd laravel-excel

Step 2: Configure Database Connection

In this type of project, we must give precedence to the database connection, generically it should be configured before getting started. Incorporate the following code in .env file with your database details.

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

Step 3: Create a Model with Migration

Run this command to create a modal with migration

php artisan make:model Item -m
<? php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    use HasFactory;
}

Step 4: Install maatwebsite/exel Package

Now, we will install the maatwebsite/excel package using the composer command.

composer require maatwebsite/excel

After install maatwebsite/excel package we have adding the service provider in config/app.php file and add the following code.

The Excel facade is also auto-discovered.

'providers' => [
   /*
    * Package Service Providers...
    */
   Maatwebsite\Excel\ExcelServiceProvider::class,
]

If you want to add it manually, add the Facade in config/app.php:

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

To publish the config, run the vendor publish command:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

Step 5: Create Dummy Data Using Tinker

After adding aliases and providers are adding some dummy records in the database using the below command.

php artisan tinker

factory(App\Item::class, 50)->create();

Step 6: Create ItemController

php artisan make:controller ItemController

After running this command we will add the following code to the controller.

App/Http/Controllers/ItemController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Excel;
use App\Models\Item;
use App\Exports\ItemsExport;

class ItemController extends Controller
{   
    /**
     * THis method use for exports as excel files 
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function itemExportExcel(Request $request){
        $fileName = Carbon::now()->toDateTimeString().'items-list.xlsx';
        return Excel::download(new ItemsExport($request), $fileName);
    }
}

Step 7: Create ItemsExport Class

Now, we will create the export class using the below command.

php artisan make:export ItemsExport --model=Item

After running this command you will find the app/Exports/ItemsExport.php file.

<?php

namespace App\Exports;

use App\Models\Item;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ItemsExport implements FromCollection,WithMapping,WithHeadings
{    
    use Exportable;

    protected $request;

    public function __construct($request)
    {
        $this->request = $request;
    }
   /**
    * @return \Illuminate\Support\Collection
    */
    public function headings(): array
    {
        return[
            'Sr',
            'Name',
            'Serial Number',
            'Part Number',
            'Model Number',
        ];
    }

    public function map($data): array
    {   
         return $data;
    }
    // set the collection of members to export
    public function collection()
    {   
        $request = $this->request;  

        $items = Item::query();
        $items = $items->get();
        
        return $items->map(function($data,$key){
            return [
                'item_serial'       =>  $key + 1,
                'item_name'         =>  $data->item_name,
                'item_serial_number'=>  $data->item_serial_number,
                'item_part_number'  =>  $data->item_part_number,
                'item_model_number' =>  $data->item_model_number,
            ];
        });
    }
}

Step 8: Add Route

Open routes/web.php file and add the following route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ItemController;

Route::group(['prefix'=>'export/excel'], function(){
    Route::get('/item', [ItemController::class, 'itemExportPdf'])->name('item.export.pdf');
});
Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/export/excel/item
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (53)