Laravel 8 Import Export Excel & CSV File Example

Hello, Artisan.

I hope everything is going well for you. I’m back with a new tutorial today. I’ll show you how to import and export CSV files in Laravel 8 today. In this example, I will import and export data using the maatwebsite/excel composer package.

This package is fantastic for exporting and importing CSV files into a Laravel program. If you’re not sure how to upload, export, or import a CSV file in a Laravel program. Here, I will show you how to import a CSV or excel file and export a CSV or excel file in a laravel 8 framework using maatwebsite/excel version 3.

Create Laravel Project

Firstly create brand new laravel app for use breeze Auth Scaffolding.If you have already a authentication system then it may not work.

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

Make Database Connection

Go to your project directory and find .env file and update it like :

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_auth8
DB_USERNAME=root
DB_PASSWORD=

Install Maatwebsite Package

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, ------------
],

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();

Configure the 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('/export', 'UserController@export')->name('export'); 
Route::get('/data-view', 'UserController@dataView'); 
Route::post('/import', 'UserController@import')->name('import');

Create Class for Import

Now we need to create our import class to create import data in laravel application.

php artisan make:import UsersImport --model=User

app/Imports/UsersImport.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']),
         ]);
     }
 }

Create Class for Export

Now we have to create our export class to create export data in laravel 7 application. so do it.

php artisan make:export UsersExport --model=User

app/Exports/UsersExport.php

namespace App\Exports;
 use App\User;
 use Maatwebsite\Excel\Concerns\FromCollection;
 class UsersExport implements FromCollection
 {
     public function collection()
     {
         return User::all();
     }
 }

Create Controller class

Now we have to create a controller to handle our declared route methods so that we can export and import CSV file in laravel application.

app/Http/Controllers/UserController.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();
    }
}

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 Import Export Excel to database Example</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 Import Export Excel to database Example
        </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> 

Hope it will work for you.