PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] How to return custom API response for "No query results for model", Laravel

 January 19, 2022     laravel, laravel-5.2, php     No comments   

Issue

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.


Solution

See if you can catch ModelNotFound instead.

public function render($request, Exception $e)
{
    if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
        dd('model not found');
    }

    return parent::render($request, $e);
}


Answered By - lagbox
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing