Integrating Maatwebsite Excel in Laravel Project.

  1. Set Up.
    Package requirement
    - PHP version ^7.0
    - Laravel version ^5.5
    - PhpSpreadsheet version ^1.6.
composer require maatwebsite/excel
...'providers' => [
/*
* Package Service Providers…
*/
Maatwebsite\Excel\ExcelServiceProvider::class
]
...
'aliases' => [

'Excel' => Maatwebsite\Excel\Facades\Excel::class
]
php artisan vendor:publish - provider="Maatwebsite\Excel\ExcelServiceProvider"
php artisan make:import MovieImport
<?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');
}
}
}
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");
}
}
Route::post('movies/bulkupload', ['as' => 'movies-bulkupload', 'uses' =>'MovieController@bulkMovieUpload']);

--

--

--

Back-end Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kehinde A. Olawuwo

Kehinde A. Olawuwo

Back-end Developer

More from Medium

Sharp 7 for Laravel is released

How is Laravel work?

How Laravel work

How to Clear Cache In Laravel 8

Laravel Route 101: Basics & Best Practices