Laravel выгрузка в excel

Introduction

We have seen a few Laravel tutorials for beginners and through one of our blog posts, we received a query- Laravel 8 export data excel file with example. So here we are with another Laravel tutorial!

In this step-by-step guideline of Laravel 8 export data as excel file, we will build a demo application in which we will use the maatwebsite/excel package for exporting data. You might be familiar with the package; it provides the best way for exporting the data as a CSV file or Excel file.

We will build a demo application where we will see how to implement Excel export functionality in Laravel using the maatwebsite/excel package.

Before starting the development part, let’s see the below video so that you can have an idea of what are we going to build in this blog.

Create a Model with Migration

Run this command to create a modal


Copy Text

php artisan make:model Student -m

// Student.php


Copy Text


Here we have to store the student data to create a table and define the table’s fields.

Create a Data Table

Go to the database/migration folder, then open the migration file and write the following code.

// 2021_07_16_041455_create_students_table


Copy Text

id();
            $table->string('name');
            $table->string('email');
            $table->string('city');
            $table->timestamps();
        });
    } 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

We will create a table using the above fields.

Now run this command. This command is useful for creating actual tables in the GUI and migrating tables in the database.


Copy Text

php artisan migrate

Install maatwebsite/excel package

To install maatwebsite/excel, run the below-mentioned command


Copy Text

composer require maatwebsite/excel.

With the help of this package, we can export data into an excel file.

Now open config/app.php and add service provider and alias.


Copy Text

'providers' => [
      ....
     MaatwebsiteExcelExcelServiceProvider::class,
],
'aliases' => [
      ....
     'Excel' => MaatwebsiteExcelFacadesExcel::class,
],

Define the routes

Routes are required for navigating the web pages for defining routes in our demo app, open routes/web.php, and use the following code.

// web.php


Copy Text

Route::resource('student', StudentController::class);
Route::get('student_export',[StudentController::class, 'get_student_data'])->name('student.export');

Create an Export Class

In this section, we will create an export class and define the model to which it is connected. The maatwebsite package offers a way for building an export class so that we can further use it in the controller.

Run the below command for the same.


Copy Text

php artisan make:export StudentExport --model=Student

Here StudentExport class will define the data that we want to export in our excel file.

Go to app/Exports/ StudentExport.php and make the following changes in your code

// StudentExport.php


Copy Text


The heading() function will define the heading, which would be displayed in an excel file.

The collection() method will return the data which we have to export. Here in our demo app, we will export all student data using the Student Model.

Create Controller

Before creating the controller we have to make a request.

The command for creating a request.


Copy Text

php artisan make::request StoreStudentRequest

Here are the validation rules applied for entering student data.


Copy Text

public function rules()
    {
        return [
            'name' => 'bail|required|string|max:255',
            'email' => 'bail|required|string|email|max:255',
            'city' => 'bail|required|string|max:255'
        ];
    }
}

Run this command to create a resource controller for writing the logic.


Copy Text

php artisan make:controller StudentController –resource

Go to app/Http/Controllers/StudentController.php and write a code.

// StudentController.php


Copy Text

name = $request->name;
        $student->email = $request->email;
        $student->city = $request->city;
        $student->save();
        return redirect(route('student.index'))->with('success','Data submited successfully!');
    } 
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function show($id)
    {
        //
    } 
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function edit($id)
    {
        //
    } 
    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, $id)
    {
        //
    }
 
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return IlluminateHttpResponse
     */
    public function destroy($id)
    {
        //
    } 
    public function get_student_data()
    {
        return Excel::download(new StudentExport, 'students.xlsx');
    }
}

Now we will use the download method of the Laravel excel package within the get_student_data() function. It will accept two parameters: export class and name of the file (you can name it anything you want)

The second parameter is the name of the file in which we want to export the data.

  • The create() function is used to create the form.
  • The store() method is used to store the data in the database
  • The index() method is used to display the data.

Create a View to Add Records and Display Details

Go to the resources/views folder. Create a new folder layout with a file named a main.blade.php

// main.blade.php


Copy Text


  
    
    
     
    
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> 
    @yield('title')
  
  
     @yield('content')    
     

Now create another folder within the views folder named student. We have to add the records of the student, and for that, we will need forms. Forms are defined in the view file.

Here main.blade.php is the parent layout file containing all the common header and footer.

In the Student folder, create two files, namely: create.blade.php and index.blade.php.

The create.blade.php file is required to create the form so that students can enter the data. Open create.blade.php and write the following code.

//create.blade.php


Copy Text

@extends('layout.main')
 
@section('title')
    Registration form
@endsection
 
@section('content') 

Student Registration Form

@csrf
Name @error('name')
{{ $message }}
@enderror
Email @error('email')
{{ $message }}
@enderror
City @error('city')
{{ $message }}
@enderror
Submit
@endsection

In the index.blade.php file, we have displayed the Student data in the table format, and we can easily download the data and export it as an excel file by clicking the Export button.

// index.blade.php


Copy Text

@extends('layout.main')
 
@section('title')
    Student Data
@endsection
 
@section('content')
@if ($message = session('success'))
{{ $message }}
@endif

Student Data

Export Data Add Data
@foreach ($students as $student) @endforeach
ID Name Email City
{{ $student->id }} {{ $student->name }} {{ $student->email }} {{ $student->city }}
{{ $students->links() }}
@endsection

Develop. Maintain. Optimize. Deploy – with Bacancy!
Are you looking for proficient developers to build highly-optimized applications? Get in touch with us to hire Laravel developer. Contact the best, to get the best! Period!

Run the Demo Application

The last section of the tutorial- laravel 8 export data as excel file is to run the app. Now it’s time to run our demo. Run the below command.


Copy Text

php artisan serve

After running the server successfully you can see the app working on

http://localhost:8000/student/create

GitHub Repository

The entire source code is available here: laravel-excel-export-example. Feel free to clone the repo and play around with the code.

Conclusion

So, I hope the tutorial of laravel 8 export data as excel file was helpful to you. Are you a laravel enthusiast and find it difficult for basic tutorials? If yes, then the Laravel tutorials page is for you! Feel free to visit and explore more such laravel tutorials.

Bacancy has dedicated, skilled, and experienced laravel developers with problem-solving skills. If you are looking for laravel developers who can help you with your requirements and project then without wasting your time contact Bacancy and hire laravel developer.

Laravel Excel logo

Supercharged Excel exports and imports

A simple, but elegant Laravel wrapper around PhpSpreadsheet
exports and imports.

Quickstart
·
Documentation
·
Video Course
·
Nova
·
Blog
·
Contributing
·
Support

Github Actions

StyleCI

Latest Stable Version

Total Downloads

License

✨ Features

  • Easily export collections to Excel. Supercharge your Laravel collections and export them directly to an Excel or CSV document. Exporting has never been so easy.

  • Supercharged exports. Export queries with automatic chunking for better performance. You provide us the query, we handle the performance. Exporting even larger datasets? No worries, Laravel Excel has your back. You can queue your exports so all of this happens in the background.

  • Supercharged imports. Import workbooks and worksheets to Eloquent models with chunk reading and batch inserts! Have large files? You can queue every chunk of a file! Your entire import will happen in the background.

  • Export Blade views. Want to have a custom layout in your spreadsheet? Use a HTML table in a Blade view and export that to Excel.

banner

🎓 Learning Laravel Excel

You can find the full documentation of Laravel Excel on the website.

We welcome suggestions for improving our docs. The documentation repository can be found at https://github.com/SpartnerNL/laravel-excel-docs.

Some articles and tutorials can be found on our blog: https://medium.com/maatwebsite/laravel-excel/home

📬 License & Postcardware

1_5nblgs68uarg0wxxejozdq

Laravel Excel is created with love and care by Spartner (formerly known as Maatwebsite) to give back to the Laravel community. It is completely free (MIT license) to use, however the package is licensed as Postcardware. This means that if it makes it to your production environment, we would very much appreciate receiving a postcard from your hometown.

Spartner
Markt 2
6231 LS Meerssen
The Netherlands.

More about the license can be found at: https://docs.laravel-excel.com/3.1/getting-started/license.html

Created by Spartner (formerly Maatwebsite)

We are a strategic development partner, creating web-based custom built software from Laravel. In need of a digital solution for your challenge? Give us a call.

https://spartner.software
info@spartner.nl
+31 (0) 10 — 7449312

🔧 Supported Versions

Versions will be supported for a limited amount of time.

Version Laravel Version Php Version Support
2.1 <=5.6 <=7.0 Unsupported since 15-5-2018
3.0 ^5.5 ^7.0 Unsupported since 31-12-2018
3.1 >=5.8 | <=10.x ^7.2 | ^8.0 New features

Cover image for How to Export Data To Excel file in Laravel 8

Export Laravel Excel

Export Data to Excel Files in Laravel 8

Today I am Going To Explain you about how you can Export Excel Files in Laravel 8.

I am going to use Tech-Admin Panel for this.

For Exporting excel file i am using Laravel Excel.

You can read about Laravel Import From CSV/ Excel Files Here!

Step 1 — Installation

To Install the Laravel Excel Package via composer run command below.

composer require maatwebsite/excel

Enter fullscreen mode

Exit fullscreen mode

Next to export config file you need run command below.

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config

Enter fullscreen mode

Exit fullscreen mode

Step 2 — Create an Exports Class inside app/Exports

Create Exports Class by using artisan command

php artisan make:export UsersExport --model=User

Enter fullscreen mode

Exit fullscreen mode

Step 3 — Handle Export To Excel Function

public function export() 
{
   return Excel::download(new UsersExport, 'users.xlsx');
}

Enter fullscreen mode

Exit fullscreen mode

You can watch the explanation video for more clarity.

Thank You for Reading

In case of any query related to LARAVEL.
Reach Out To me.
Twitter
Instagram

In your admin side, you need to download data in excel format. You also want to import data in database from the excel file. Excel export and import is basic requirement in the admin panel.

Maatwebsite/Laravel-Excel is simple and easy to implement Laravel package. In this article, we will share you how you can export and import data in excel format. We will create Laravel application from the scratch and implement excel export and import.

We will go through step by step. So let’s get started below step by step:

  • Create fresh Laravel application
  • Create database migration
  • Install Maatwebsite/Laravel-Excel Package
  • Create routes and controller class.
  • Create excel export/import classes file.
  • Create blade file
     

Step: 1. Create Laravel application

In the first step, we will create new Laravel application using bellow command, So open your Terminal or command prompt and run bellow command:

composer create-project laravel/laravel excel

Step 2. Database migration

In your .env file, set the database name and MySQL users data.

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

Laravel default have migration for users table. So we will use users data for excel export and import. Run the migration command to run create the table in database.

php artisan migrate

Step: 3. Install Maatwebsite/Laravel-Excel Package

In the third step, we will install Maatwebsite/Laravel-Excel package using below command.

composer require maatwebsite/excel

Now open config/app.php file and register package class in $providers array.

'providers' => [
    ...
    MaatwebsiteExcelExcelServiceProvider::class,
]

In the same file add the class in $aliases array.

'aliases' => [
    ...
    'Excel' => MaatwebsiteExcelFacadesExcel::class,
]

Now publish the package config file. This will add config/excel.php file. You can change the settings for the excel from this file.

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config

Step: 4. Create routes and controller class.

Now  we need to create routes of import export file. so open your routes/web.php file and add below routes.

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersExcelController;

Route::get('excel/view', [ExcelController::class, 'index'])->name('index');
Route::get('excel/export', [ExcelController::class, 'export'])->name('export');
Route::post('excel/import', [ExcelController::class, 'import'])->name('import');

Now create the controller to handle the routes.

php artisan make:controller ExcelController

This will create controller file at app/Http/Controllers/ExcelController.php. Open the file add the methods as we have defined in route file.

<?php
   
namespace AppHttpControllers;
  
use IlluminateHttpRequest;
use AppExportsUsersExport;
use AppImportsUsersImport;
use MaatwebsiteExcelFacadesExcel;
  
class ExcelController extends Controller
{
    /**
    * @return IlluminateSupportCollection
    */
    public function index()
    {
       return view('index');
    }
   
    /**
    * @return IlluminateSupportCollection
    */
    public function export() 
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
   
    /**
    * @return IlluminateSupportCollection
    */
    public function import() 
    {
        Excel::import(new UsersImport,request()->file('excel'));
           
        return back();
    }
}

Step: 5. Create excel export/import classes file.

We have defined controller file. From the controller we will call excel class and make export and import. So we need to create export and import class.

Create import class using below command.

php artisan make:import UsersImport --model=User

Open app/Imports/UsersImport.php and add the below codes.

<?php
  
namespace AppImports;
  
use AppModelsUser;
use MaatwebsiteExcelConcernsToModel;
  
class UsersImport implements ToModel
{
    /**
    * @param array $data
    *
    * @return IlluminateDatabaseEloquentModel|null
    */
    public function model(array $data)
    {
        return new User([
            'name'     => $data[0],
            'email'    => $data[1], 
            'password' => Hash::make($data[2]),
        ]);
    }
}

Same way run command for export

php artisan make:export UsersExport --model=User
<?php
  
namespace AppExports;
  
use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;
  
class UsersExport implements FromCollection
{
    /**
    * @return IlluminateSupportCollection
    */
    public function collection()
    {
        return User::all();
    }
}

Step: 6. Create blade file.

In this last step we will create view file where we will export and import excel file.

Create resources/views/index.blade.php file and add the HTML code.

<!DOCTYPE html>
<html>
    <head>
        <title>Excel Export/Import</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <div class="row mt-3">
                <div class="col-12">
                    <form action="{{ route('import') }}" method="post" enctype="multipart/form-data">
                        @csrf
                        <div class="mb-3">
                            <label for="excel" class="form-label"></label>
                            <input type="file" name="excel" class="form-control">
                        </div>
                        <button class="btn btn-success">Import User Data</button>
                        <a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

Now run the artisan command to start Laravel application.

php artisan serve

Open your browser and go to https://localhost:8000/excel/view You can simply upload the data and import.

Thanks for giving time in reading article. I hope you liked this article and will help you.

In this tutorial, we will see Laravel Export In Excel and CSV Data Example using the maatwebsite/excel 3.1 packages. In the general Laravel project, we always need to import or export the rows from the database. The maatwebsite/excel makes it very easy to import-export data in Laravel.

To export data in excel and csv in Laravel, use the maatwebsite/excel 3.1 package. Laravel Excel package is intended at being Laravel-flavoured PhpSpreadsheet: a simple but elegant wrapper around PhpSpreadsheet to simplify the exports and imports. PhpSpreadsheet is the library written in pure PHP and provides the set of classes that allow us to read from and write to different types of spreadsheet file formats, like Excel and LibreOffice Calc.

If you want to get up and running with basic laravel functionality, go to my other article on this web blog called Laravel 7 Crud Example From Scratch

If you want to Generate PDF In Laravel, check out Laravel Generate PDF From View Example. For this example, we use the package called maatwebsite/excel version 3.1. So, our Laravel 9 and maatwebsite/excel 3.1.

When using the package in your application, it’s good to understand how it functions behind the scenes. Following the behind-the-scenes will make you feel more comfortable and confident using the maximum potential of the tool.

Laravel Excel Features

  1. We can easily export collections to Excel.
  2. We can export queries with automatic chunking for better performance.
  3. We can queue exports for better performance.
  4. We can easily export Blade views to Excel.
  5. We can easily import it to collections.
  6. We can read the Excel file in chunks.
  7. We can handle the import inserts in batches.

Requirements

  1. PHP: ^7.0
  2. Laravel: ^5.5
  3. PhpSpreadsheet: ^1.6
  4. PHP extension php_zip enabled
  5. PHP extension php_xml enabled
  6. PHP extension php_gd2 enabled

Step 1: Installation

Require the following package in the composer.json of your Laravel 9 project. The following command will download the package and PhpSpreadsheet.

composer require maatwebsite/excel
➜  laravel6 git:(master) ✗ composer require maatwebsite/excel
Using version ^3.1 for maatwebsite/excel
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Installing markbaker/matrix (1.1.4): Downloading (100%)
  - Installing markbaker/complex (1.4.7): Downloading (100%)
  - Installing phpoffice/phpspreadsheet (1.9.0): Downloading (100%)
  - Installing maatwebsite/excel (3.1.17): Downloading (100%)
phpoffice/phpspreadsheet suggests installing mpdf/mpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing tecnickcom/tcpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing jpgraph/jpgraph (Option for rendering charts, or including charts with PDF or HTML Writers)
Writing lock file
Generating optimized autoload files
> IlluminateFoundationComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: maatwebsite/excel
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
➜  laravel6 git:(master) ✗

Step 2: Configure package

The MaatwebsiteExcelExcelServiceProvider is auto-discovered and registered by default.

If you want to register by yourself, then add the ServiceProvider in config/app.php:

'providers' => [
    /*
     * Package Service Providers...
     */
    MaatwebsiteExcelExcelServiceProvider::class,
]

Excel facade is auto-discovered.

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

'aliases' => [
    ...
    'Excel' => MaatwebsiteExcelFacadesExcel::class,
]

If you want to publish a config, run the vendor publish command:

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
➜  laravel6 git:(master) ✗ php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
Copied File [/vendor/maatwebsite/excel/config/excel.php] To [/config/excel.php]
Publishing complete.
➜  laravel6 git:(master) ✗

This will create the new config file named config/excel.php.

Step 3: Create model and migration files

Type the following command.

php artisan make:model Disneyplus -m

Now, go to the [timestamp].create_disneypluses_table.php file and add the columns.

public function up()
{
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
}

Now, migrate the database using the following command.

php artisan migrate

Step 4: Create a controller and routes

The next step is to create a DisneyplusController.php file.

php artisan make:controller DisneyplusController

Now, add the two routes inside the routes >> web.php file.

// web.php

Route::get('disneyplus', 'DisneyController@create')->name('disneyplus.create');
Route::post('disneyplus', 'DisneyController@store')->name('disneyplus.store');

Now, create two methods inside the DisneyplusController.php file.

<?php

// DisneyplusController.php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppDisneyplus;

class DisneyplusController extends Controller
{
    public function create()
    {

    }

    public function store()
    {
        
    }
}

Step: 5 Create a form blade file for input the data

Now, inside the views folder, create the form.blade.php file. Add the following code.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Disneyplus Shows
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('disneyplus.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="price">Series :</label>
              <input type="text" class="form-control" name="series"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

Step 6: Store data in the database

Now, we will write the two functions inside the DisneyplusController.php file.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppDisneyplus;

class DisneyplusController extends Controller
{
    public function create()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }
}

So, in the above file, first, we have shown the form file, and then inside the store function, we check for validation and then store the data into the database.

Also, add the fillable fields inside the Disneyplus.php model file.

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Disneyplus extends Model
{
    protected $fillable = ['show_name', 'series', 'lead_actor'];
}

Now, go to this route: http://laravel6.test/disneyplus or http://localhost:8000/disneyplus.

You will see one form. Try to save the data, and if everything in the code is right, you will see one entry in the database.

Step: 7 Create a view file to display the data.

Before creating a view file, we need to add one route inside the web.php.

// web.php

Route::get('disneyplus/list', 'DisneyplusController@index')->name('disneyplus.index');

Now, create a view file called list.blade.php file. Add the following code.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Now, add the code inside the index() function of the DisneyplusController.php file.

public function index()
{
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
}

Now, go to the http://laravel6.test/disneyplus/list or http://localhost:8000/disneyplus/list.

You will see the listing of the shows.

Step 8: Create Exports class

You may do this by using the make:export command.

php artisan make:export DisneyplusExport --model=Disneyplus

The file can be found in app/Exports directory.

The file DisneyplusExport.php is the following.

<?php

namespace AppExports;

use AppDisneyplus;
use MaatwebsiteExcelConcernsFromCollection;

class DisneyplusExport implements FromCollection
{
    /**
    * @return IlluminateSupportCollection
    */
    public function collection()
    {
        return Disneyplus::all();
    }
}

If you prefer to create the export manually, you can build the following in app/Exports.

Step 9: Write the export function

Inside the DisneyplusController.php file, add the following code.

// DisneyplusController.php

use AppDisneyplus;
use AppExportsDisneyplusExport;
use MaatwebsiteExcelFacadesExcel;

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
}

So, our final file looks like below.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppDisneyplus;
use AppExportsDisneyplusExport;
use MaatwebsiteExcelFacadesExcel;

class DisneyplusController extends Controller
{
    public function create()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }

    public function index()
    {
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
    }

    public function export() 
    {
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
    }
}

Finally, add the route to be able to access the export:

// web.php

Route::get('export', 'DisneyplusController@export');

Also, add the link to the Export inside the list.blade.php file.

@foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
      <td><a href="{{action('DisneyplusController@export')}}">Export</a></td>
    </tr>
@endforeach

Okay, now eventually go to the http://laravel6.test/disneyplus/list, and now you can see one link called Export.

Click on the Export link, and you will see the disney.xlsx file inside your Download folder.

Exporting collections in CSV in Laravel

By default, the export format is determined by the file’s extension.

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.csv');
}

It will download the CSV file.

If you want to configure the export format explicitly, you can pass it through as 2nd parameter.

You can find more details about export in different formats on this link.

Finally, Laravel Export in Excel and CSV data example is over.

In Laravel, you don’t have to write long code to export your data, there is already a package available for that – Laravel Excel.

It allows exporting data in various formats like – XLSX, CSV, XLS, HTML, etc.

In this tutorial, I show how you can export MySQL database data in CSV & Excel format using the Laravel Excel package in Laravel 8.

How to export data to CSV & Excel format in Laravel 8


Contents

  1. Install Package
  2. Update app.php
  3. Publish package
  4. Database Configuration
  5. Create Table
  6. Model
  7. Create Export class
  8. Route
  9. Controller
  10. View
  11. Demo
  12. Conclusion

1. Install Package

Requirement –

  • PHP: ^7.2|^8.0
  • Laravel: ^5.8
  • PhpSpreadsheet: ^1.21
  • psr/simple-cache: ^1.0
  • PHP extension php_zip enabled
  • PHP extension php_xml enabled
  • PHP extension php_gd2 enabled
  • PHP extension php_iconv enabled
  • PHP extension php_simplexml enabled
  • PHP extension php_xmlreader enabled
  • PHP extension php_zlib enabled

Install the package using composer –

composer require maatwebsite/excel

If you are getting an error while executing the above command then execute the below command –

composer require psr/simple-cache:^1.0 maatwebsite/excel

After that again execute –

composer require maatwebsite/excel

2. Update app.php

  • Open config/app.php file.
  • Add the following MaatwebsiteExcelExcelServiceProvider::class in 'providers' –
'providers' => [
      ....
      ....
      ....  
      MaatwebsiteExcelExcelServiceProvider::class
];
  • Add the following 'Excel' => MaatwebsiteExcelFacadesExcel::class in 'aliases' –
'aliases' => [
     .... 
     .... 
     .... 
     'Excel' => MaatwebsiteExcelFacadesExcel::class
];

3. Publish package

Run the command –

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config

This will create a new excel.php file in config/.


4. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

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

5. Create Table

  • Create a new table Employees using migration and add some records.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('name');
        $table->string('email');
        $table->smallInteger('age');
        $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and add some records in it.

6. Model

  • Create Employees Model.
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – username, name, email, and age using the $fillable property.

Completed Code

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Employees extends Model
{
    use HasFactory;

    protected $fillable = [
       'username','name','email','age'
    ];
}

7. Create Export class

I am creating 2 export classes just for example purpose –

1. EmployeesExport Class –

php artisan make:export EmployeesExport --model=Employees
  • Open app/Exports/EmployeesExport.php file.

Class has 2 methods –

  • collection() – Load export data. Here, you can either –
    • Return all records.
    • Return specific columns or modify the return response which I did in the next Export class.
  • headings() – Specify header row.

NOTE – Remove headings() methods if you don’t want to add a header row.

Completed Code

<?php

namespace AppExports;

use AppModelsEmployees;
use MaatwebsiteExcelConcernsFromCollection;
use MaatwebsiteExcelConcernsWithHeadings;

class EmployeesExport implements FromCollection, WithHeadings
{

    /**
    * @return IlluminateSupportCollection
    */
    public function collection()
    {
        ## 1. Export all data
        // return Employees::all();

        ## 2. Export specific columns
        return Employees::select('id','username','name')->get();

    }

    public function headings(): array
    {
        return [
          '#',
          'Username',
          'Name'
        ];
    }
}

2. EmployeesByAgeExport Class –

php artisan make:export EmployeesByAgeExport --model=Employees
  • Open app/Exports/EmployeesByAgeExport.php file.
  • In this class, I added __construct() to allow a parameter send while creating class instance and use it to retrieve data.
  • After initializing $result Array pass $result in collect() for return – return collect($result);
  • Mention header row names in the heading() method.

Completed Code

<?php

namespace AppExports;

use AppModelsEmployees;
use MaatwebsiteExcelConcernsFromCollection;
use MaatwebsiteExcelConcernsWithHeadings;

class EmployeesByAgeExport implements FromCollection, WithHeadings
{
    private $agegreaterthan;

    public function __construct($age=0) 
    {
        $this->agegreaterthan = $age;
    }

    /**
    * @return IlluminateSupportCollection
    */
    public function collection()
    {
        ## 3. Conditional export and customize result
        $records = Employees::select('*')->where('age','>',$this->agegreaterthan)->get();

        $result = array();
        foreach($records as $record){
           $result[] = array(
              'id'=>$record->id,
              'username' => $record->username,
              'name' => $record->name,
              'email' => $record->email,
              'age' => $record->age,
              'status' => 1 // Custom data
           );
        }

        return collect($result);
    }

    public function headings(): array
    {
       return [
         '#',
         'Username',
         'Name',
         'Email',
         'Age',
         'Status'
       ];
    }
}

8. Route

  • Open routes/web.php file.
  • Define 4 routes –
    • / – Load index view.
    • employees/exportcsv – Export data in CSV format.
    • employees/exportexcel – Export data in Excel format.
    • employees/exportbyagecsv – POST route to export data by age.

Completed Code

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersEmployeesController;

Route::get('/', [EmployeesController::class, 'index'])->name('home'); 
Route::get('employees/exportcsv', [EmployeesController::class, 'exportCSV'])->name('employees.exportcsv');
Route::get('employees/exportexcel', [EmployeesController::class, 'exportExcel'])->name('employees.exportexcel');
Route::post('employees/exportbyagecsv', [EmployeesController::class, 'exportByAgeCSV'])->name('employees.exportbyagecsv');

9. Controller

  • Create EmployeesController Controller.
php artisan make:controller EmployeesController
  • Open app/Http/Controllers/EmployeesController.php file.
  • Import EmployeesExportEmployeesByAgeExport and Excel.
  • Create 4 methods –
    • index() – Load index view.
    • exportCSV() –  To export data call Excel::download().

It takes 2 parameters –

    1. Class instance.
    2. File name with extension.
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv'; 
return Excel::download(new EmployeesExport, $file_name);
    • exportExcel() – Using the same above code and change the file extension to .xlsx.
    • exportByAgeCSV() – Read POST age value and pass it with EmployeesByAgeExport($age) instance.
$file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv'; 
return Excel::download(new EmployeesByAgeExport($age), $file_name);

Completed Code

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppExportsEmployeesExport;
use AppExportsEmployeesByAgeExport;
use Excel;

class EmployeesController extends Controller
{
    public function index(){
       return view('index');
    }

    // CSV Export
    public function exportCSV(){
       $file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
       return Excel::download(new EmployeesExport, $file_name);
    }

    // Excel Export
    public function exportExcel(){
       $file_name = 'employees_'.date('Y_m_d_H_i_s').'.xlsx';
       return Excel::download(new EmployeesExport, $file_name);
    }

    // Conditional Export (csv)
    public function exportByAgeCSV(Request $request){

       $age = $request->age;

       $file_name = 'employees_'.date('Y_m_d_H_i_s').'.csv';
       return Excel::download(new EmployeesByAgeExport($age), $file_name);
    }
}

10. View

Create index.blade.php file in resources/views/ folder.

Create 2 anchor elements –

  1. Set href to {{ route('employees.exportcsv') }} for CSV export.
  2. Set href to {{ route('employees.exportexcel') }} for Excel export.

Create a <form method='post' action="{{ route('employees.exportbyagecsv') }}">. Add input element to enter age and a submit button.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1"> 
   <title>How to Export data to CSV & Excel format in Laravel 8</title>

   <!-- CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>

   <div class="container mt-5">

      <a class="btn btn-primary" href="{{ route('employees.exportcsv') }}">CSV Export</a> &nbsp;&nbsp;
      <a class="btn btn-primary" href="{{ route('employees.exportexcel') }}">Excel Export</a><br><br>

      <form method='post' action="{{ route('employees.exportbyagecsv') }}">
         @csrf
         <div class="mb-3">
            <label for="age" class="form-label">Age</label>
            <input type="number" class="form-control" id="age" name="age" value="0">
         </div>

         <button type="submit" class="btn btn-success">Export</button>
      </form>
   </div>

</body>
</html>

11. Demo

View Demo


12. Conclusion

Use constructor in Export class to handle passed parameters and use it to fetch data.

In this tutorial, I only mentioned 2 export formats – CSV, and Excel but there is more format available. You can learn more about it from here.

You can view this tutorial to know how to import data using the Laravel Excel package.

If you found this tutorial helpful then don’t forget to share.

Mar 02, 2023 . Admin

Hi all,

This article is focused on laravel 10 import export excel & csv files. I would like to share with you laravel 10 import export excel. I explained simply step by step step by step how to import and export excel & csv file to database in laravel 10 using maatwebsite/excel package. I explained simply about Maatwebsite Package to import export large excel and csv file into mysql database in PHP Laravel 10.

This tutorial helps you understand how to comfortably import and export excel or CSV files to a Database with Laravel 10.

If you want to create easy import and export, excel file functionality, this laravel maatwebsite/excel tutorial is best for you.

Let’s start for following example:

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app

Step 2 : Install maatwebsite/excel Package

In this step we need to install maatwebsite/excel package via the Composer package manager, so one your terminal and fire bellow command:

composer require psr/simple-cache:^1.0 maatwebsite/excel

If, you are using less the laravel 10 versions then use bellow command:

composer require maatwebsite/excel

Step 3 : Add Dummy Records

In this step, we will create some dummy records for users table, so we can export them to that users. so let’s run below tinker command:

php artisan tinker

User::factory()->count(10)->create()

Step 4 : Add Import Class

In maatwebsite 3 versions provide a way to build import class and we have to use it in the controller. So it would be a great way to create a new Import class. So you have to run the following command and change the following code on that file:

php artisan make:import UsersImport --model=User

app/Imports/UsersImport.php

<?php

namespace AppImports;

use AppModelsUser;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
use Hash;

class UsersImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return IlluminateDatabaseEloquentModel|null
    */
    public function model(array $row)
    {
        return new User([
            'name'     => $row['name'],
            'email'    => $row['email'], 
            'password' => Hash::make($row['password']),
        ]);
    }
}

You can download demo csv file from here: Demo CSV File.

Step 5 : Add Export Class

maatwebsite 3 version provide way to built export class and we have to use in controller. So it would be great way to create new Export class. So you have to run following command and change following code on that file:

php artisan make:export UsersExport --model=User

app/Exports/UsersExport.php

<?php

namespace AppExports;

use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;
use MaatwebsiteExcelConcernsWithHeadings;

class UsersExport implements FromCollection, WithHeadings
{
    /**
    * @return IlluminateSupportCollection
    */
    public function collection()
    {
        return User::select("id", "name", "email")->get();
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function headings(): array
    {
        return ["ID", "Name", "Email"];
    }
}

Step 6 : Add Controller

In this step, we will create UserController with index(), export() and import() method. so first let’s create controller by following command and update code on it.

php artisan make:controller UserController

Now, update code on UserController file.

app/Http/Controllers/UserController.php

file('file'));
               
        return back();
    }
}

Step 7 : Add Routes

In this step, we need to create routes for list of users, import users and export users. so open your «routes/web.php» file and add following route.

routes/web.php

<?php
  
use IlluminateSupportFacadesRoute;
  
use AppHttpControllersUserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::controller(UserController::class)->group(function(){
    Route::get('users', 'index');
    Route::get('users-export', 'export')->name('users.export');
    Route::post('users-import', 'import')->name('users.import');
});

Step 8 : Add Blade File

In Last step, let’s create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put following code:

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Import Export Excel & CSV File Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
     
<div class="container">
    <div class="card mt-3 mb-3">
        <div class="card-header text-center">
            <h4>Laravel 10 Import Export Excel & CSV File Example</h4>
        </div>
        <div class="card-body">
            <form action="{{ route('users.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="file" name="file" class="form-control">
                <br>
                <button class="btn btn-primary">Import User Data</button>
            </form>
  
            <table class="table table-bordered mt-3">
                <tr>
                    <th colspan="3">
                        List Of Users
                        <a class="btn btn-danger float-end" href="{{ route('users.export') }}">Export User Data</a>
                    </th>
                </tr>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
                @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                </tr>
                @endforeach
            </table>
  
        </div>
    </div>
</div>
     
</body>
</html>

Run Laravel App:

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

php artisan serve    

Now, you have to open a web browser, type the given URL and view the app output:

http://localhost:8000/users    

Output:

I hope it can help you…

Home  »  Laravel   »   Laravel 9 Import Export Excel & CSV File Tutorial

This tutorial helps you understand how to comfortably import export excel or CSV file to Database with Laravel.

If you want to create easy import and export, excel file functionality, this laravel maatwebsite/excel tutorial is best for you.

At the end of this tutorial, you will be able to download or import excel & CSV file directly from the database in laravel application, respectively.

Generically, we will follow all the imperative that are needed to build a general laravel application. We will go from point a to b, something like creating or importing data to xls or CSV.

Laravel 9 Import Export Excel & CSV File to Database Example

Preferably, we will use a maatwebsite/excel composer plugin for exporting and importing data, most importantly, to interact with the database.

I will share the working pattern with you. Ideally, how should you import-export and download the excel & CSV file from the database using the maatwebsite/excel composer plugin.

Follow the given below steps that will take you to the learning dimension.

Table of Contents

  1. Download Laravel Application
  2. Compose Database Connection
  3. Install Excel (maatwebsite) Pacakage
  4. Generate Fake Records and Migrate
  5. Construct Route
  6. Make Import Class
  7. Construct Export Class
  8. Create and Prepare Controller
  9. Write Down Blade View
  10. Summary

Download Laravel Application

Let’s evoke this tutorial with the imperative step; installing a brand new laravel application offers us a key to opening the many opportunities. We can create the app from the beginning, build multiple features with it.

You can skip this step if you’ve already installed the app. Otherwise, put the command into effect to download the sacred canon.

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

Later on, after the project installation, execute the command to enter the project directory.

cd laravel-excel-csv

Compose Database Connection

Make the consensus between laravel app and MySQL database, append the following code in .env file.

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Install Excel (maatwebsite) Pacakage

Commonly, to complete our foundational work, we require a third-party package. Ideally, we are talking about the Laravel-Excel plugin by Maatwebsite. It provides the robust mechanism to deal with Excel exports and imports in Laravel. In response, It has got the immense love of artisan’s on GitHub.

Run command to install the package.

composer require maatwebsite/excel

Register Plugin’s Service in Providers & Aliases

You can have the following code placed inside the config/app.php file.

'providers' => [
  .......
  .......
  .......
  MaatwebsiteExcelExcelServiceProvider::class,
 
 ],  
'aliases' => [ 
  .......
  .......
  .......
  'Excel' => MaatwebsiteExcelFacadesExcel::class,
], 

Execute the vendor, publish command, and publish the config.

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"

This will formulate a new config file as config/excel.php.

Generate Fake Records, Migrate Table

Often, this step consists of two sub-steps. In the first one, we migrate the User table. Laravel comes with the User model and migration with default values, and we can use it and migrate to the database.

php artisan migrate

Once the migration is completed, then execute the command to generate the fake records.

php artisan tinker
User::factory()->count(50)->create();
exit

Eventually, the above command has created the some data inside the database.

Construct Route

Usually, routing in laravel is the foundational mechanism that interprets the URI endpoint and conjugates it into parameters to shape which module or controller is associated.

Define 3 routes in routes/web.php that handle the import and export for Excel and CSV files.

<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersUserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('file-import-export', [UserController::class, 'fileImportExport']);
Route::post('file-import', [UserController::class, 'fileImport'])->name('file-import');
Route::get('file-export', [UserController::class, 'fileExport'])->name('file-export');

Make Import Class

The maatwebsite module offers an imperative method to develop an import class. Obviously, it should be used along with the laravel controller, and i believe you already know this has been the best way to generate a new import class.

Execute the below command:

php artisan make:import UsersImport --model=User

Place the following code inside the app/Imports/UsersImport.php file.

<?php
namespace AppImports;
use AppModelsUser;
use IlluminateSupportFacadesHash;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
class UsersImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return IlluminateDatabaseEloquentModel|null
    */
    public function model(array $row)
    {
        return new User([
            'name'     => $row[0],
            'email'    => $row[1],
            'password' => Hash::make($row[2])
        ]);
    }
}

Construct Export Class

The maatwebsite module provides an essential method to construct an export class. Preferably, it needs to get along with the laravel controller, and i know it doesn’t sound vague.

Run the following command in your terminal:

php artisan make:export UsersExport --model=User

Here is the final code that is conjugated in app/Exports/UsersExport.php.

<?php
namespace AppExports;
use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;
class UsersExport implements FromCollection
{
    /**
    * @return IlluminateSupportCollection
    */
    public function collection()
    {
        return User::all();
    }
}

Create and Prepare Controller

Now, we have reached an essential step in this tutorial. We will evoke this step by creating a controller. Altogether all the logic goes in here to manage the import and export file such as Excel and CSV.

Invoke the command to generate UserController.

php artisan make:controller UserController

Place the following code in the app/Http/Controllers/UserController.php file.

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use MaatwebsiteExcelFacadesExcel;
use AppImportsUsersImport;
use AppExportsUsersExport;
class UserController extends Controller
{
    /**
    * @return IlluminateSupportCollection
    */
    public function fileImportExport()
    {
       return view('file-import');
    }
   
    /**
    * @return IlluminateSupportCollection
    */
    public function fileImport(Request $request) 
    {
        Excel::import(new UsersImport, $request->file('file')->store('temp'));
        return back();
    }
    /**
    * @return IlluminateSupportCollection
    */
    public function fileExport() 
    {
        return Excel::download(new UsersExport, 'users-collection.xlsx');
    }    
}

Write Down Blade View

Ultimately, we have reached the last step. In general, here we need to formulate the view for handling importing and exporting through the frontend.

Create a resources/views/file-import.blade.php file to set up the view. Place the following code inside the blade view file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Import Export Excel & CSV to Database in Laravel 7</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5 text-center">
        <h2 class="mb-4">
            Laravel 7 Import and Export CSV & Excel to Database Example
        </h2>
        <form action="{{ route('file-import') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="form-group mb-4" style="max-width: 500px; margin: 0 auto;">
                <div class="custom-file text-left">
                    <input type="file" name="file" class="custom-file-input" id="customFile">
                    <label class="custom-file-label" for="customFile">Choose file</label>
                </div>
            </div>
            <button class="btn btn-primary">Import data</button>
            <a class="btn btn-success" href="{{ route('file-export') }}">Export data</a>
        </form>
    </div>
</body>
</html>

We have followed every step, respectively, and consecutively, now its time to run the app to test what we build so far.

php artisan serve

Here is the endpoint that you can finally test:

http://localhost:8000/file-import-export

Summary

So this was it, we have completed the tutorial. In this tutorial, we threw light on importing-exporting and downloading the Excel & CSV file from the database with the maatwebsite/excel composer package.

You can also check the documentation of the plugin that we assimilated in this tutorial.

You can download the full code of this tutorial from GitHub.

I hope you must have liked this tutorial, we covered the basic functionality but good for getting started.

Recommended Posts:

Понравилась статья? Поделить с друзьями:
  • Laravel word to pdf
  • Latin word for complete
  • Latin word for community
  • Laravel export to excel
  • Latin word for clothing