Laravel excel export custom query

In this example we will discuss about import excel file In laravel framework PHP.

Follow the below step to import :

  1. Download the dependecy using composer for Import and export excel file.

    composer require maatwebsite/excel

    You may visit //packagist.org/packages/maatwebsite/excel for more details.

  2. Add providers and aliases in config/app.php

    'providers' => [
    		/*
             * Laravel Framework Service Providers...
             */
            ......,
            ......,
            Maatwebsite\Excel\ExcelServiceProvider::class,
    ]
    'aliases' => [
        .......,
        -------,
        'Excel' => Maatwebsite\Excel\Facades\Excel::class,
    ]
    

  3. Now publish the changes using vendor:publish.

    php artisan vendor:publish


  4. Make migration and migrate it using command.
  5. Add routes

    /*Excel import export*/
    Route::get['export', 'ImportExportController@export']->name['export'];
    Route::get['importExportView', 'ImportExportController@importExportView'];
    Route::post['import', 'ImportExportController@import']->name['import'];
    

  6. Create Import and Export class using import/export command

    Note: This command avaialble only if you download dependecy successfully using composer[step 1]

    php artisan make:export BulkExport --model=Bulk

  7. In app/Emports/BulkExport.php file

    namespace App\Exports;
    use App\Bulk;
    use Maatwebsite\Excel\Concerns\FromQuery;
    use Maatwebsite\Excel\Concerns\WithHeadings;
    
    class BulkExport implements FromQuery,WithHeadings
    {
        /**
        * @return \Illuminate\Support\Collection
        */  
        // use Exportable;
    
        public function headings[]: array
        {
            return [
                'Id',
                'name',
                'email',
                'createdAt',
                'updatedAt',
            ];
        }
        public function query[]
        {
            return Bulk::query[];
            /*you can use condition in query to get required result
             return Bulk::query[]->whereRaw['id > 5'];*/
        }
        public function map[$bulk]: array
        {
            return [
                $bulk->id,
                $bulk->name,
                $bulk->email,
                Date::dateTimeToExcel[$bulk->created_at],
                Date::dateTimeToExcel[$bulk->updated_at],
            ];
        }
    
    }
    

  8. In Bulk.php Model

Bài mới nhất

Chủ Đề