How to treat exceptions when deleting a primary key record referenced in another table in the Laravel framework

Asked

Viewed 275 times

0

I’m having trouble deleting a record to which your primary key was referenced in another record from another table!

The tables are discipline and teacher, where the primary key of teacher is being referenced in the table discipline!

I wanted to know the correct way to treat this exception to return a message/warning without error in the system with the default message from Larable!

Note: I don’t want to use the method cascade, only to inform that it cannot be excluded because the teacher has relation to a discipline!

public function delete(Request $dados)
{
    DB::table('professors')->where('cdprofessor', '=', $dados->cdprofessor)->delete();
    return redirect()->route('professor')->withStatus(__('Professor deletado com sucesso.'));
}

Exceção do Laravel

  • How is your action delete()

  • public function delete(Request $dados){ 
 DB::table('professors')->where('cdprofessor', '=', $dados->cdprofessor)->delete();
 return redirect()->route('professor')->withStatus(__('Professor deletado com sucesso.'));
}

1 answer

1

The Laravel has a way of treating exceptions in the Globa, the class App/Exception/Handler.php.

In your case, it is possible that an Illuminate Database Queryexception is being displayed, that is, there is an error with your query or something related to its execution, and this is an error defies a relation to the table.

Since the question is how to deal with the error, what matters is just the Exception Hand (https://laravel.com/docs/5.8/errors), and to capture this error, you need to capture it in the method render or report in class App/Exception/Handler.php.

For the report method, a log is expected to be generated, not our case.

We will insert the exception capture in the render method:

public function render($request, Exception $exception)
{
    if($exception instanceof \Illuminate\Database\QueryException){

        preg_match('#\[(.*?)\]#',$exception->getPrevious()->getMessage(), $match);
        $mysql_error_code = $match[1];
        if($mysql_error_code == '23000'){
            return response()->json((["message" => 'Não é possível executar essa ação', "errors" => 'Chave estrangeira inválida'], 400);
        }
        return response()->json((["message" => 'Não é possível executar essa ação', "errors" => $exception->errors()], 400);
    }
    return parent::render($request, $exception);
} 

The important thing is to know that to treat the error, you should check the Exceptionhandler of the Framework in the file App/Exception/Handler.php.

  • Hello Anthraxisbr, thanks for the explanation. I did as you demonstrated, the return that stayed inside the if() didn’t open on my app, but I managed to get around with a about();. But he takes all the exceptions of query. So one more question: How to identify if the exception is of integrity of Foreign key?

  • Hello @Eriklesbonfimribeiro, try to see if this solves: $Exception->getPrevious()->getMessage(), the return of this line will be the Pdoexception message, it returns the error text, use a regex to retrieve the error code from Mysql, https://dev.mysql.com/docrefman/5.7/en/server-error-Reference.html. I edited the answer with a change there, but I didn’t get to test it here.

Browser other questions tagged

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