How to import data from excel to your database table in Laravel

Overview

I always use this functionality every time I create a POS (point of sale) application because the products to be stored are just too many to be entered one after the other. So in this shot, I will teach you how to import data from an excel sheet and store them into your database table. We would be using the Fast-Excel package.

Package installation

Run the composer command:

composer require rap2hpoutre/fast-excel

After installation, you can implement it in any controller you want, or you can create one like so:

php artisan make:controller ImportController

Example

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Rap2hpoutre\FastExcel\FastExcel;
use App\User;
use App\Http\Controllers\Controller;

class ImportController extends Controller
{
   public function index(){
   $users = (new FastExcel)->import('file.xlsx', function ($line) {
    return User::create([
        'name' => $line['Name'],
        'email' => $line['Email']
    ]);
});

  }
}

Import the use Rap2hpoutre\FastExcel\FastExcel; class

  • From the example above, we use the index() function to implement the data import.

  • We first instantiate the FastExcel then we chain the import() method, which receives two-parameters. The first parameter is the excel file you want to import and the second parameter is a callback function.

  • In our callback function, we pass the excel file where we get each column value and store it in the database.

Explanation

The USER: is the table we are importing data to, therefore we call the create() method, which creates the new data in the database from the excel file (file.xlsx).

Output

From the code above you will only see the result in your database.

Free Resources