Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
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.
composer require maatwebsite/excel
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
In the example below, we'll create a simple seeder and import data from the CSV file.
UsersTableImport classCreate 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.
WithChunkReading interface and define the size for faster imports.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.
Also Read: Laravel Deployments using Envoy
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 );
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.