Laravel 8 Import Export CSV File Tutorial

Laravel 8 import export csv to database tutorial. In this post, i will show you how to import and export csv file from database in laravel.

The Maatwebsite Package provides for laravel app. Which is used to import and export large csv file into mysql database in PHP Laravel 8.

In this example post, i will create import form, which is used to import large csv file data to database. And also, create one button for export large csv data in file from database in laravel 8.

Import export excel or csv from database is a very basic need in laravel apps. So, in this import export csv file into database in laravel, i will give you very easy example step by step for import and export csv or excel file using maatwebsite/excel version 3 in laravel 8.

Laravel 8 import and export csv file to database app will look like in the following image:

Laravel import csv file validation:

Succussfully import csv file data into database:

Import and Export CSV File in Laravel 8

  • Step 1 – Installing Laravel 8 App
  • Step 2 – Configuring Database in .env File
  • Step 3 – Installing Maatwebsite
  • Step 4 – Run Migration
  • Step 5 – Create Import and Export CSV Routes
  • Step 6 – Create Import And Export Class
  • Step 7 – Creating Import Export CSV Controller
  • Step 8 – Create Blade View
    • Create Import CSV Form
    • Create Export CSV Button on Export Form
  • Step 9 – Start Development Server

Step 1 – Installing Laravel 8 App

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Configuring Database in .env File

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Installing Maatwebsite

In step 3, Navigate to your downloaded LaravelImportExportCSV directory. And then install Maatwebsite Packages in your laravel 8. Open terminal and run the following command:

cd / LaravelImportExportCSV

composer require maatwebsite/excel

Then configure this package in app.php file, which is located inside config directory.

Add the ServiceProvider in config/app.php:

'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]

Then add the Facade in config/app.php:

'aliases' => [
    ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]

To publish the config, run the vendor publish command:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

Step 4 – Run Migration

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 5 – Create Import and Export CSV Routes

In step 5, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\ImportExportController;

Route::get('import-form', [ImportExportController::class, 'index']);
Route::post('import', [ImportExportController::class, 'import']);
Route::get('export', [ImportExportController::class, 'export']);

Step 6 – Create Import And Export Class

In step 6, create import and export csv file class by using the following command, so open command prompt and type the following command:

php artisan make:import UsersImport --model=User

php artisan make:export UsersExport --model=User

Then open UsersImport.php, which is located inside app/Imports/ directory. And then add the following code into it:

<?php
   
namespace App\Imports;
   
use App\Models\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']),
        ]);
    }
}

Next, open UsersExport.php, which is located inside app/Imports/ directory. And then add the following code into it:

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

Step 7 – Creating Import Export CSV Controller

In step 7, create import and export csv file controller by using the following command:

php artisan make:controller ImportExportController

The above command will create ImportExportController.php file, which is located inside LaravelImportExportCSV/app/Http/Controllers/ directory. So add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Exports\UsersExport;

use App\Imports\UsersImport;

use Maatwebsite\Excel\Facades\Excel;

use App\Models\User;

class ImportExportController extends Controller
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function index()
    {
       return view('import-form');
    }
   
    /**
    * @return \Illuminate\Support\Collection
    */
    public function import(Request $request) 
    {
    	$validatedData = $request->validate([

           'file' => 'required',

        ]);

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

           
        return redirect('import-form')->with('status', 'CSV file has been imported in laravel 8');
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function export() 
    {
        return Excel::download(new UsersExport, 'users.csv');
    }
   
}

Step 8 – Create Blade View

In step 8, create new blade view file that named import.blade.php inside resources/views directory for importing csv file data into database and export data in csv format in laravel.

  • Create Import CSV Form
        <form id="import-csv-form" method="POST"  action="{{ url('import') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="file" placeholder="Choose file">
                    </div>
                    @error('file')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>              
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>
  • Create Export CSV Button on Export Form
 <h2 class="float-right"><a href="{{url('export')}}" class="btn btn-success">Export</a></h2>

The full source code of import.blade.php file is following:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Import Export CSV File Example Tutorial</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-5">

  
  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <div class="card">

    <div class="card-header font-weight-bold">
      <h2 class="float-left">Import Export CSV File In Laravel 8</h2>
      <h2 class="float-right"><a href="{{url('export')}}" class="btn btn-success">Export</a></h2>
    </div>

    <div class="card-body">

        <form id="import-csv-form" method="POST"  action="{{ url('import') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="file" placeholder="Choose file">
                    </div>
                    @error('file')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>              
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>

</div>  
</body>
</html>

Step 9 – Start Development Server

In step 9, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/import-form

Leave a Comment