Easy Excel Imports in Laravel

Importing Excel files come handy when you’re building some large scale inventory kind of an application where you need to import set of data from CSV or excel files. In this short tutorial, we’ll go through on importing excel files with Laravel & look on for some crazy hacks and tricks in between.

Importing Excel files come handy when you’re building some large scale inventory kind of an application where you need to import set of data from CSV or excel files. In this short tutorial, we’ll go through on importing excel files with Laravel & look on for some crazy hacks and tricks in between.

Installing the package

composer require maatwebsite/excel

Add the Service Provider & Facade

Right into your config/app.php, add the service provider.

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

and the facade

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

Learn how to export excel files with in your Laravel 

Example

In the example below, we’ll create a simple seeder and import data from the CSV file.

Step#1 – Create a UsersTableImport class

Create a UsersTableImport class somewhere inside your database/seeds directory. Let’s create it under database/seeds/imports/UsersTableImport.php and paste the following code.

class UsersTableImport implements toCollection, WithChunkReading, WithStartRow {

   public function collection( Collection $rows ) {

      foreach ( $rows as $row ) {
         User::create( [
            'name'             => $row[0],
            'email'            => $row[1],
         ] );
      }
   }

   /**
    * @return int
    */
   public function chunkSize(): int {
      return 250;
   }

   /**
    * @return int
    */
   public function startRow(): int {
      return 2;
   }

Here we’ve imported data to a Collection. Below points explains a bit of what we’ve done here.

  • If you’ve larger csv files, you can always use WithChunkReading interface and define the size for faster imports.
  • If your CSV’s first row contains the titles, you can utilize the WithStartRow interface to set your custom row to read data from.

Check out the docs if you want to have a more clearer understanding of all interfaces.

Step#2 – Create a Seeder

Create a new seeder with artisan php artisan make:seeder UsersTableSeeder. Inside of the run() method, simply paste the following code (suppose we already have a csv file in seeds/csvs/users_table_seeder.csv).

Excel::import( new UsersTableImport, database_path( 'seeds/csvs/users_table_seeder.csv' ), null, \Maatwebsite\Excel\Excel::CSV );

Conclusion

That’s it, you can test it out by simply running php artisan migrate and you’ll see data populates in your DB. importing excel files was never this simple before. For more information about this awesome package, check out the documentation website.