Search code examples
laravellaravel-5laravel-responselaravel-exceptions

How to handle native exception in Laravel?


For example, I use:

return User::findOrFail($id);

When row does not exist with $id I get exception.

How I can return this exception in Json response? It returns HTML Laravel page now.

I need something like as:

{"error", "No query results for model"}

Solution

  • From their documentation:

    Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.

    So, you can either catch that exception, or go with the simple Find method. It will return false if not found, so you can handle it accordingly.

    return User::find($id);
    

    UPDATE:

    Option 1:

    try {
        return User::findOrFail($id);
    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
        return json_encode(['error' => 'No query results for model']);
    }
    

    Option 2:

    $user = User::find($id);
    if($user) {
        return $user;
    }
    return json_encode(['error' => 'No query results for model']);