How to Import Export Excel & CSV File in Laravel 6?

How to Import Export Excel & CSV File in Laravel 6?

In this tutorial, we will learn how to import export excel & csv file in Laravel 6. I written simple tutorial of laravel 6 maatwebsite/excel. using maatwebsite/excel we can import export excel or csv from database in laravel 6 application.

In this tutorial, we will learn how to import export excel & csv file in Laravel 6. I written simple tutorial of Laravel 6 maatwebsite/excel. using maatwebsite/excel we can import export excel or csv from database in Laravel 6 application.

In this example i written full script of how to import csv file from database in Laravel 6 and how to export csv file from database in Laravel 6. you can easily download excel & csv file from database in laravel 6.

We will simple create import data to csv, xls file and also we can import data to database using csv file in laravel 6 application.

In this example we will use maatwebsite/excel composer package for import and export task. maatwebsite/excel provide easy way to import and export using database model. maatwebsite/excel updated version 3 and they provide great way to import export data from database, so first follow few step to get example.

Step 1 : Install Laravel 6

Here, we need install Laravel 6 application using bellow command, So open your terminal OR command prompt and run bellow command:

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

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 maatwebsite/excel

Now open config/app.php file and add service provider and aliase.

config/app.php

'providers' => [

    ....

    Maatwebsite\Excel\ExcelServiceProvider::class,

],

'aliases' => [

    ....

    'Excel' => Maatwebsite\Excel\Facades\Excel::class,

],

Step 3: Create Dummy Records

In this step, we have to require "users" table with some dummy records, so we can simply import and export. So first you have to run default migration that provided by laravel using following command:

php artisan migrate

After that we need to run following command to generate dummy users:

php artisan tinker

factory(App\User::class, 20)->create();

Step 4: Add Routes

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

Route::get('importExportView', '[email protected]');

Route::get('export', '[email protected]')->name('export');

Route::post('import', '[email protected]')->name('import');

Step 5: Create Import Class

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

php artisan make:import UsersImport --model=User

app/Imports/UsersImport.php

<?php



namespace App\Imports;



use App\User;

use Maatwebsite\Excel\Concerns\ToModel;

use Maatwebsite\Excel\Concerns\WithHeadingRow;



class UsersImport implements ToModel, WithHeadingRow

{

    /**

    * @param array $row

    *

    * @return \Illuminate\Database\Eloquent\Model|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 6: Create 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 App\Exports;



use App\User;

use Maatwebsite\Excel\Concerns\FromCollection;



class UsersExport implements FromCollection

{

    /**

    * @return \Illuminate\Support\Collection

    */

    public function collection()

    {

        return User::all();

    }

}

Step 7: Create Controller

In this step, now we should create new controller as MyController in this path "app/Http/Controllers/MyController.php". this controller will manage all importExportView, export and import request and return response, so put bellow content in controller file:

app/Http/Controllers/MyController.php

<?php



namespace App\Http\Controllers;



use Illuminate\Http\Request;

use App\Exports\UsersExport;

use App\Imports\UsersImport;

use Maatwebsite\Excel\Facades\Excel;



class MyController extends Controller

{

    /**

    * @return \Illuminate\Support\Collection

    */

    public function importExportView()

    {

       return view('import');

    }



    /**

    * @return \Illuminate\Support\Collection

    */

    public function export() 

    {

        return Excel::download(new UsersExport, 'users.xlsx');

    }



    /**

    * @return \Illuminate\Support\Collection

    */

    public function import() 

    {

        Excel::import(new UsersImport,request()->file('file'));



        return back();

    }

}

Step 8: Create Blade File

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

resources/views/import.blade.php

<!DOCTYPE html>

<html>

<head>

    <title>Laravel 6 Import Export Excel to database Example - ItSolutionStuff.com</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

</head>

<body>



<div class="container">

    <div class="card bg-light mt-3">

        <div class="card-header">

            Laravel 6 Import Export Excel to database Example - ItSolutionStuff.com

        </div>

        <div class="card-body">

            <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">

                @csrf

                <input type="file" name="file" class="form-control">

                <br>

                <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 you can check on your laravel 6 application.

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/importExportView

I hope it can help you...

laravel php web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Laravel Development Company

Skenix Infotech is a top Laravel Website Development Company with Expert Laravel Developers that provides robust Laravel Development Services at fair costs.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...