Last active
January 26, 2018 18:37
-
-
Save arturmamedov/0b2e5b7e39c7e1de8fc09f69f79db618 to your computer and use it in GitHub Desktop.
install `laravel`, install `maatwebsite/excel` and import data from excel to db table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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