Laravel 6 Tutorial Import Export Excel & Csv to Database

In this article, we will show how to import export excel or csv data from database in laravel Framework using maatwebsite version 3 package with example. There have been many new changes in version 3 of the new maatwebsite package. It has made very simple and easy to use with laravel application for import export data to database.

For some time we want to export or import thousands of records to our database.Maatwebsite offers many features for exporting & importing thousands of records in excel sheet.

Contents

  • Install Laravel Fresh Project
  • Install Maatwebsite Package
  • Add Fake Records In Database
  • Create Controller
  • Add Routes
  • Create Import Export Classes
  • Create Blade View
  • Start Development Server
  • Conclusion

Install Laravel Fresh Project

We need to install Laravel fresh application using below command, Open your command prompt and run the below command :

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

After successfully install laravel Application, Go to your project .env file and set up database credential and move next step.

Install Maatwebsite Package

We need to install Maatwebsite package, Open command prompt(CLI) and run the below 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,

],

After successfully Install & Configurtion Maatwesite Package, Use the below command and publish the package :

php artisan vendor:publish

This command will create a new config file named “config/excel.php”.

Add Fake Records

Now we need to add fake records in our datatabase, so we can simply import and export. First of run the migration command it will create some basics table in our database.

php artisan migrate

After that we need to run below command to add fake records in users table :

If you found any query builder error in command prompt go to  => app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
 
public function boot()
{
    Schema::defaultStringLength(191);
}
php artisan tinker 

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

Create Controller

We need to create new controller. The controller manage all import export methods, open your terminal and run the below command.

php artisan make:controller TestController

This command will create our TestController, Go to app/Http/Controllers/TestController.php and put the below code here :

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Exports\ExportUsers;
use App\Imports\ImportUsers;
use Maatwebsite\Excel\Facades\Excel;
  
class TestController extends Controller
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function importExport()
    {
       return view('import');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function export() 
    {
        return Excel::download(new ExportUsers, 'users.xlsx');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function import() 
    {
        Excel::import(new ImportUsers, request()->file('file'));
           
        return back();
    }
}

Add Routes

Here, we will create routes for import export data to our database. Open your routes/web.php and create the below routes :

Route::get('import-export', '[email protected]');
Route::post('import', '[email protected]');
Route::get('export', '[email protected]');

Create Import Class

Now we need to create a import class and use this class to our testController. Open the command Prompt and run the below command :

php artisan make:import ImportUsers --model=User

Go to the app/Imports/ImportUsers.php

<?php
  
namespace App\Imports;
  
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
  
class ImportUsers implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'name'     => $row[0],
            'email'    => $row[1], 
        ]);
    }
}

Create Export Class

Now we need to create a import class and use this class to our testController. Open the command Prompt and run the below command :

php artisan make:export ExportUsers --model=User

app/Exports/ExportUsers.php

<?php
  
namespace App\Exports;
  
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
  
class ExportUsers implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::get();
    }
}

Create Blade File

Next we will create import.blade.php. Go to app/resource/views and create import.blade.php, put the below code here :

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.7 Import Export Excel to database - Tuts Make</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 mt-4">
        <div class="card-header">
            Laravel 5.7 Import Export Excel to database - Tuts Make
        </div>
        <div class="card-body">
            <form action="{{ url('import') }}" method="POST" name="importform" 
               enctype="multipart/form-data">
                {{ csrf_token() }}
                <input type="file" name="file" class="form-control">
                <br>
                <a class="btn btn-info" href="{{ url('export') }}"> 
                 Export File</a>
                <button class="btn btn-success">Import File</button>
            </form>
        </div>
    </div>
</div>
   
</body>
</html>

Start Development Server

In this step, we will use the php artisan serve command . It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

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

http://localhost:8000/import-export

Conclusion

In this article , We have successfully use the import export excel data to database using the maatwebsite package . our examples run quickly.

If you have any questions or thoughts to share, use the comment form below to reach us.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *