Making exceptions in the Eloquent ORM Observers

Asked

Viewed 530 times

1

I have the following code in my model:

public static function boot(){
    parent::boot();

    // Não deixa excluir caso possua registros vinculados.
    static::deleting(function($content_area){
        if($total = $content_area->contents->count() > 0){
            //throw new Exception("Essa área não pode ser removida, ela possui {$total} conteútos vinculados.");
            return App::abort(403, "Essa área não pode ser removida, ela possui {$total} conteútos vinculados.");
        }
    });
}

In my controller I have the following:

public function destroy($id){
    $content_area = ContentArea::find($id);

    try {
        $content_area->delete();
    } catch (Exception $e) {
        return Response::json(
            [
                'success' => 'false',
                'message' => $e->getMessage(),
                'messageType' => 'error'
            ]
        );
    }

    return Response::json(['success' => false]);
}

Theoretically, during the deletion of the record, it should launch the exception if the condition is true within the Observer.

The problem is that it shows the Laravel exception screen and kills the application. I didn’t want this to happen, I wanted him to just return the message to display to the user. Does anyone know why this is happening?

1 answer

2

If you are using namespaces, you may need to inform PHP that your exception is not in the current namespace, but in the root:

catch (\Exception $e)
  • His "catch" is inside the controller, so you wouldn’t need to use the namespace pointing to the root. I say this because I have the same problem. I created an Observer and I try to give throw new Exception but the controller does not take the Exception.

  • 1

    Being inside the controller makes no difference, if the controller is inside a namespace, all references to classes within this controller will by default be directed to the same namespace as the controller, unless the developer indicates a new namespace, in this case the root ( ). I created a gist to test and show it working: https://gist.github.com/antonioribeiro/7d4feb011b2e61599544. If you add the bar ( ) to the first catch it captures the exception at that point.

Browser other questions tagged

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