1

I'm developing a Laravel 5.6 API and I'm using Resources and Collections, Route Model Binding.

To show an item, I currently use following code in my controller:

public function show(Todo $todo) { TodoResource::withoutWrapping(); return new TodoResource($todo); } 

In the Exceptions > Handler.php I have the following:

 public function render($request, Exception $exception) { // This will replace our 404 response with // a JSON response. if ($exception instanceof ModelNotFoundException) { return response()->json([ 'error' => 'Resource not found' ], 404); } return parent::render($request, $exception); } 

This works perfectly when the item is found in the database. If the item is not in the database I get a (when using a browser):

"Sorry, the page you are looking for could not be found" 

When using POSTMAN rest client, I'm getting

{ "message": "No query results for model [App\\Todo].", "exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", .... .... 

I would like to simply retrieve a 404 error with text "Resource not found", using both a browser or POSTMAN.

* Update with Routing info *

In my api.php, I have the following:

Route::apiResource('todos', 'TodoController'); Route::fallback(function () { return response()->json(['message' => 'Not Found!'], 404); }); 

In web.php, I have:

Route::Resource('todos', 'TodoController'); 

What is the best way to achieve this?

6
  • How are you routing your endpoints? in both routes/web.php and routes/api.php It wil depend of which middleware are handling the request. It seems that in the web.phpyou hasn't defined the endpoint. Commented Aug 13, 2018 at 13:32
  • Edited the original post with routing information Commented Aug 13, 2018 at 13:35
  • have you aliased ModelNotFoundException ? Commented Aug 13, 2018 at 13:44
  • Not sure what exactly you mean with aliased. But I'm capturing the ModelNotFoundException in Exceptions>Handler.php Commented Aug 13, 2018 at 13:45
  • 1
    have you aliased that class so you can use it by that short name in the current file you are in? Illuminate\Database\Eloquent\ModelNotFoundException Commented Aug 13, 2018 at 13:46

1 Answer 1

2

Make sure to alias the exception class you are checking for.

use Illuminate\Database\Eloquent\ModelNotFoundException; 

Without this you are checking for an instance of App\Exceptions\ModelNotFoundException.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.