Skip to content
Advertisement

How to return custom API response for “No query results for model”, Laravel

I am building an RESTful API in Laravel 5.2.

In my resource controllers I want to use implicit model binding to show resources. e.g.

public function show(User $users)
{
    return $this->respond($this->userTransformer->transform($users));
}

When a request is made for a resource that doesn’t exist Laravel automatically returns the NotFoundHttpException

NotFoundHttpException

I want to return my own custom response but how can I do that for a query that is done using route model binding?

Would something like this Dingo API response answer be able to be implemented?

Or will I stick with my old code which was something like this:

public function show($id)
{
    $user = User::find($id);

    if ( ! $user ) {
        return $this->respondNotFound('User does not exist');
    }

    return $this->respond($this->userTransformer->transform($users));
}

So I could see if a resource (user) was not found and return an appropriate response.

Advertisement

Answer

See if you can catch ModelNotFound instead.

public function render($request, Exception $e)
{
    if ($e instanceof IlluminateDatabaseEloquentModelNotFoundException) {
        dd('model not found');
    }

    return parent::render($request, $e);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement