Easy Excel Imports in Laravel

Last Updated at : March 7, 2019 By - Usama Muneer | 153

    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.

    blog user
    Usama Muneer

    A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

    Related Posts

    Gear up fellow developers, another Laravel Meetup is coming back to Lahore & it will be a great milestone while helping our fellow web developers across the city to become motivated and will help them grow as Laravel developers.

    Getting an app developed is not the only thing that one needs to ensure in terms of digital visibility and e-commerce. Yes, having an app is important but to stay updated and to be abreast with the competition Optimization of performance is necessary.

    Telescope gives knowledge into the solicitations coming into your application, exemptions, log sections, database questions, lined employments, mail, notices, reserve activities, planned errands, variable dumps and that's just the beginning.

    Laravel Live Islamabad, ended on 24th Nov'18 & we got a lot to learn from the top-notch of speakers & influencers. Thanks to the sponsors for pulling off such a great event in the capital of Pakistan.