Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
install `laravel`, install `maatwebsite/excel` and import data from excel to db table
<?php
// #1 - Install laravel: https://laravel.com/docs/5.5#installation
/* $console/bash/cmd commands >
$> composer global require "laravel/installer"
$> laravel new excel_to_db_project
$> cd excel_to_db_project
// #2 - Install excel package, documentation on: https://github.com/Maatwebsite/Laravel-Excel if laravel >5.5 no need to do nothing
$> composer require "maatwebsite/excel"
*/
// In laravel (Controller or directly in route ... how and where you prefer)
// i use `routes/web.php` and route `/` ~~and it view `resources/views/welcome.blade.php`~~
use Illuminate\Support\Facades\DB;
Route::get('/', function () {
// #3 - load excel file
Excel::load('file.xlsx', function($reader) {
// #4 - Get all user
$users = $reader->all();
/* example data:
#items: array:2 [▼
0 => RowCollection {#14623 ▼
#heading: array:4 [▶]
#title: "RegistratiSitoDruma"
#items: array:211 [▼
0 => CellCollection {#14629 ▼
#title: null
#items: array:4 [▼
"cognome" => "Mamedov"
"nome" => "Artur"
"email" => "wxample@gmail.com"
"azienda" => "obiv.it"
]
}
1 => CellCollection {#14634 ▶}
2 => CellCollection {#14638 ▶}
3 => CellCollection {#14642 ▶}
4 => CellCollection {#14646 ▶}
5 => CellCollection {#14650 ▶}
*/
// begin a db transactions
DB::beginTransaction();
try {
// #5 - iterate trough users (be carefoul to have 1 sheet in the file)
foreach ($users as $user) {
// here we have 1 user row with accessible properties as: $user->nome, $user->email ...
// insert fields in DB
DB::table('users')->insert([
'email' => $user->email,
'password' => str_random(6),
'first_name' => $user->nome,
'last_name' => $user->cognome,
'agency' => $user->azienda,
'created' => date('Y-m-d H:i:s'),
'modified' => date('Y-m-d H:i:s'),
]);
}
} catch (\Exception $e) {
// rollback all thing, control excel file and run again
DB::rollBack();
dd($e);
}
// commit if all right! we done!
DB::commit();
});
return view('welcome');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.