0

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"}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Dev
  • 1,013
  • 7
  • 15
  • 37

3 Answers3

2

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']);
trajchevska
  • 942
  • 7
  • 13
  • I know about this, but it return me not clear error, wrapped in HTML code – Dev Jul 19 '16 at 19:52
  • What do you mean? It throws an exception and if it's not caught properly, you will be shown an HTML page saying that an exception was thrown. That's how the exceptions are working. To catch it, you need to wrap your code in a try/catch block. The other approach would be to simply go with the find method. – trajchevska Jul 19 '16 at 19:54
  • I mean that I need return message without HTML code for API mobile – Dev Jul 19 '16 at 19:58
2

You can handle various types of exceptions, that exception can be handle with a ModelNotFoundException in this case

try{
    $user = User::findOrFail($id);
}catch(ModelNotFoundException $e){
    return response()->json(['error' => 'User not found'], 400);
}

And there's another way to catch various types of exceptions in the Handler.php located on app/Exceptions/Handler.php there you can catch the exceptions and return whatever you want inside the render function.

For example insede that function you can add this before the return parent::render($request, $e):

if($e instanceof ModelNotFoundException)
{
    return new Response(['message' => 'We haven\'t find any data'], 204);
}
0

You should look in render method of Handler file. You can test exception class here and depending on it return different response in Json format

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291