How can I treat Violation Constraint exception to show the user in a user friendly way

Asked

Viewed 1,269 times

0

How best to treat a Integrity Constraint Violation exception to explain user-friendly ?

2 answers

1

Another solution would be you use Queryexception, first you 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 in a user-friendly way 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 library laracasts/flash

https://github.com/laracasts/flash
  • I just edited the answer with everything you need.

  • 1

    +1 I believe this form is the best, but I was not remembering the "way" of the Queryexception (big namespace, I did not record)

1

You can probably use a try/catch to capture a specific exception.

try {

   Model::operations()->save();

} catch (\PDOException $e) {

    return redirect()->back()->withErrors('message', 'Erro ao realizar a operação');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.