Maatwebsite Excel in Laravel Project
Introduction
During my course of working on a project, I implemented bulk import using excel, and I would like to share how to integrate this in your Laravel project. There are couples of packages out there which provides this functionality, but I will be using Laravel Excel (formally Maatwebsite Excel) for this writeup.
This is a walk-through on how to integrate Maatwebsite Excel in Laravel application, please refer to documentation if you have any concern.
Requirement and Set Up.
Package requirement
- PHP version ^7.0
- Laravel version ^5.5
- PhpSpreadsheet version ^1.6.
Download the package in your project by running the code below.
$ composer require maatwebsite/excel
However, Maatwebsite\Excel\ExcelServiceProvider
is auto-discovered by default, but you can do it yourself by Adding to
the ServiceProvider in config/app.php
.....
'providers' => [
/*
* Package Service Providers…
*/
Maatwebsite\Excel\ExcelServiceProvider::class
]
The Excel facade is also auto-discovered, but you can add it yourself by adding the code below to the facade
in config/app.php
.
.....
'aliases' => [
.....
'Excel' => Maatwebsite\Excel\Facades\Excel::class
]
Lastly, to publish the config, run the vendor publish command:
$ php artisan vendor:publish - provider="Maatwebsite\Excel\ExcelServiceProvider"
This will create a new config file in the config/excel.php where you can make a lot of changes and configurations.
Excel Import
There’s a lot you can do here. Please check the documentation for the available functions. I will be using import to collection here.
i). Import to Collection.
Create an import class in app/Imports by either running this command below
$ php artisan make:import MovieImport
or manually by creating Imports directory in app, then ClassNameImport.php (i.e Imports\MovieImport.php) in Imports directory.
<?php
namespace App\Imports;
use App\Movies;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class MoviesImport implements ToCollection, WithHeadingRow
{
/**
* @param array $row
*
* @return Movies|null
*/
public function collection(Collection $rows)
{
$errorMsg = "";
DB::beginTransaction();
$i = 1;
foreach ($rows as $row) {
if ($row['title'] != null) {
$data['title'] = $row['title'];
} else {
$errMsg = "Title is empty on SN $i";
break;
}
//You can validate other values using same steps.
$data['synopsis'] = $row['synopsis'];
$data['release_date'] = $row['release_date'];
if (!Movies::create($data)) {
$errMsg = "Error while creating movies";
break;
}
$i++;
}
if (!empty($errorMsg)) {
DB::rollBack(); // Rollback in case there is error
return redirect()->back()->with('error', $errorMsg);
} else {
DB::commit(); // Commit to database
return redirect()->back()->with('success', 'Uploaded Successfully');
}
}
}
ii). Now create a method in the controller for the import.
public function bulkMovieUpload(Request $request)
{
if ($request->hasFile('excel_file')) {
$data = $request->file('excel_file');
$data->move(('path'), $data->getClientOriginalName());
//You can choose to validate file type. e.g csv,xls,xlsx.
$file_url = ('path') . $data->getClientOriginalName();
Excel::import(new MovieImport, $file_url);
return back()->with('success', 'Uploaded Successfully!');
} else {
return back()->with('error', "File is required");
}
}
Call through the route (View)
Route::post('movies/bulkupload', [
'as' => 'movies-bulkupload',
'uses' =>'MovieController@bulkMovieUpload'
]);
This will handle the Excel import. I will write a second article on Maatwebsite Excel Export ASAP.
If you have any error or issue, please reach out on Twitter.
If you find this useful, kindly share and repost. Thank you 😊!
NOTE: Previously posted on Medium