What is the best way to treat an Integrity constraint violation exception to explain user friendly?
What is the best way to treat an Integrity constraint violation exception to explain user friendly?
You can probably use a try/catch
to catch a specific exception.
try {
Model::operations()->save();
} catch (\PDOException $e) {
return redirect()->back()->withErrors('message', 'Erro ao realizar a operação');
}
Another solution would be to use QueryException , you first need to "call" the class in your controller :
use Illuminate\Database\QueryException;
Then you can use it as follows:
try {
$dados = MinhaModel::findOrFail($id);
$dados->delete();
} catch (QueryException $e) {
dd($e->getMessage());
}
To return the exception friendly to the user, do the following:
try {
$dados = MinhaModel::findOrFail($id);
$dados->delete();
} catch (QueryException $e) {
flash()->error('Mensagem para o usuário');
return redirect()->back();
}
For error notifications I use the laracasts / flash
https://github.com/laracasts/flash