I am using maatwebsite to import the excel file and save the records in the database.
I was able to import them but I also want to add validations such as required|email and also want to catch the sql exceptions raised in between.
Below is my controller code.
public function import(Request $request)
{
$validateData = $request->validate([
'class_id' => 'required'
]);
try {
$import->import(request()->file('usersExcel'), null , \Maatwebsite\Excel\Excel::XLSX);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
$errormessage = "";
dd($failures);
foreach ($failures as $failure) {
$errormess = "";
foreach($failure->errors() as $error)
{
$errormess = $errormess.$error;
}
$errormessage = $errormessage." ,\n At Row ".$failure->row().", ".$errormess."<br>";
}
return redirect('/create_users')->with('error', $errormessage);
}
}
Here is the import code:
use Importable, SkipsErrors;
private $classid = 0;
public function __construct(int $classid)
{
$this->classid = $classid;
}
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => Hash::make('password')
]);
}
public function rules(): array
{
return [
'name' => 'required',
'email' => 'required',
'password' => 'required',
];
}
My roadblocks here are, i can catch the row validations and send that to the view through the controller but not sure whether this is right code. And I am not able to handle the queryExceptions that i get if i insert duplicate record.
Can you guys help me figuring it out.
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HTnSTq
via IFTTT
Aucun commentaire:
Enregistrer un commentaire