Integrating Maatwebsite Excel in Laravel Project.
Hey guys, this is my first blog post here. I want to share how to integrate excel in your Laravel project. There are couples of packages out there which provides this functionality but I will be using Maatwebsite Excel for this purpose.
This is a walk-through on how to integrate Maatwebsite Excel in Laravel application, please refer to documentation if you have any concern.
- 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.
2. 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.
<?phpnamespace 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");
}
}
3. Call this through the route
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 @heavykenny or use the comment section. Thanks.