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.
JavaScript
x
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
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:
JavaScript
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.
JavaScript
public function render($request, Exception $e)
{
if ($e instanceof IlluminateDatabaseEloquentModelNotFoundException) {
dd('model not found');
}
return parent::render($request, $e);
}