Import Export Excel and CSV File in Laravel 8

Import Export Excel CSV Laravel File

Throughout this tutorial, you will learn how to easily import and export Excel and CSV files in the Laravel 8 application while communicating with the PHP MySQL database using Maatwebsite/Laravel-Excel package.

Set up Laravel Environment

In general, to run the PHP commands or even interact with Laravel, you need to set up Composer on your development machine. After downloading and setting up the composer follow the below process.

Enter composer command on console and hit enter to install a new Laravel application:

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

Get into the project:

cd import-export-excel-csv-laravel

Add Database Details

The learning paradigm of this tutorial also explains Laravel 8 Import Export Excel and CSV File to MySQL database. So you need to make the connection between Laravel and MySQL by adding the database name, username, and password in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db //database name 
DB_USERNAME=root
DB_PASSWORD=

Install Maatwebsite/Laravel-Excel Package

You need to run the below command to install Maatwebsite/Laravel-Excel package in Laravel:

composer require maatwebsite/excel

After the package installation, open config/app.php file and inject the Laravel excel plugin in providers and aliases array simultaneously:

'providers' => [
  .......
  Maatwebsite\Excel\ExcelServiceProvider::class, 
 ],  

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

With the help of the vendor publish command easily publish the config and propel it inside the config/excel.php:

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

Now, you can see a newly generated config file in config/excel.php.

Create Records in Database

You need some records in the database to export and import to CSV/Excel format, so use the migrate command to migrate the User table which comes default with Laravel.

php artisan migrate

Run command to enter into Psy PHP Shell:

php artisan tinker

Run command to create the dummy records, and yes you can check them inside the database:

User::factory()->count(60)->create();

Create Maatwebsite Import Export Classes

Create import and export class specifically for maatwebsite package, and later you will have to use both the classes in the controller file.

php artisan make:import UsersImport --model=User

Go ahead and include the below code in app/Imports/UsersImport.php file:

<?php

namespace App\Imports;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UsersImport 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],
            'password' => Hash::make($row[2])
        ]);
    }
}

Also, enter command in console and hit enter to generate UsersExport class:

php artisan make:export UsersExport --model=User

You can check following file has been generated in app/Exports/UsersExport.php path:

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

Generate and Getting Ready Controller

To create the functionality of importing and exporting Excel and CSV files in Laravel, you have to generate a new controller and write logic within the controller

The below command generates the UserImportExportController.

php artisan make:controller UserImportExportController

We created three functions, the importExport() method contains the view method which initializes the view in laravel app, whereas importFile() and exportFile() processes import and export features respectively.

Add the following code in the app/Http/Controllers/UserImportExportController.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\UsersExport;
use App\Imports\UsersImport;

class UserImportExportController extends Controller
{

    public function importExport()
    {
       return view('welcome');
    }
   
    public function importFile(Request $request) 
    {
        Excel::import(new UsersImport, $request->file('file')->store('temp'));
        return back();
    }

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

Define Route

You need to create three routes to manage displaying view, import and export excel and CSV file:

Insert the following code in routes/web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserImportExportController;
/*
|--------------------------------------------------------------------------
| 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('import-export', [UserImportExportController::class, 'importExport']);
Route::post('import-file', [UserImportExportController::class, 'importFile'])->name('import-file');
Route::get('export-file', [UserImportExportController::class, 'exportFile'])->name('export-file');

Create Blade View

Now, finally, you have to create a view which rewards our intense hard work, for the Laravel 8 export to excel demo go to resources/views/welcome.blade.php file and replace it with the below code.

<!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 and Export Excel & CSV Demo in Laravel 8 </title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container mt-5 text-center">
      <form action="{{ route('import-file') }}" method="POST" enctype="multipart/form-data"> @csrf <div class="form-group mb-5" style="max-width: 600px; 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">Browse file</label>
          </div>
        </div>
        <button class="btn btn-danger">Click to Import</button>
        <a class="btn btn-primary" href="{{ route('export-file') }}">Click to Export</a>
      </form>
    </div>
  </body>
</html>

Start Laravel Application

And, now we are done with coding just start the app and test:

php artisan serve

Here is the endpoint that you can finally test:

http://localhost:8000/import-export

Now, you can easily export and import the Users records from the database in .xlsx format:

The Laravel Import and Export into Excel tutorial is over, I hope you have liked this tutorial.

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment