How can I handle constraint violation exception to show user friendly

0

What is the best way to treat an Integrity constraint violation exception to explain user friendly?

    
asked by anonymous 11.06.2016 / 17:10

2 answers

1

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');
}
    
14.06.2016 / 13:50
1

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
    
15.06.2016 / 15:12