1
votes

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?

1
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. - Kenny Horna
Edited the original post with routing information - wiwa1978
have you aliased ModelNotFoundException ? - lagbox
Not sure what exactly you mean with aliased. But I'm capturing the ModelNotFoundException in Exceptions>Handler.php - wiwa1978
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 - lagbox

1 Answers

2
votes

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.