I'm trying to import data from excel file to database using laravel and maatwebsite excel package
So I'm using the following code :
class ProjectsImport implements ToModel,WithHeadingRow,WithValidation
{
use Importable;
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function rules(): array
{
return [
'nom' => 'required',
'prenom' => 'required',
'cine' => 'required|unique:castings',
];
}
public function customValidationMessages()
{
return [
'nom.required' => 'Le nom est requis',
'prenom.required' => 'Le prénom est requis',
'cine.required' => 'Le CINE est requis',
'cine.unique' => 'Le CINE a déjà été pris',
];
}
public function model(array $row)
{
$casting = new Casting();
$representant = new Representant();
$casting->nom = $row['nom'];
$casting->prenom= $row['prenom'];
$casting->cine = $row['cine'];
$casting->save();
}
}
My Controller :
public function importFile(){
Excel::import(new ProjectsImport,request()->file('fichier'));
return response()->json(['success' => 'Data is successfully added']);
}
My script :
$('#fileform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"{{ route('castingss.importFile') }}",
method:"POST",
data: new FormData(this),
dataSrc: "",
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
html = '<div class="alert alert-success">' + data.success + '</div>';
table.clear().rows.add(data).draw();
}
$('#form_result2').html(html);
}
})
});
When all works fine I get in my view the message of success (Data is successfully added) , But when for example I have an error the error is displayed on the network and not on my view
I get only the succes message in my view bit in the case of errors I get the messages on network
How can I display the errors message in my view in this case ?
UPDATE
With this code I get in my network :
message: "The given data was invalid.",…}
errors: [["There was an error on row 2. Le CINE a déjà été pris"]]
0: ["There was an error on row 2. Le CINE a déjà été pris"]
message: "The given data was invalid."
How can I display that in my view ?