Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mhdev's avatar
Level 1

Dependency Injection when resource is not found

Need some help with dependency injection. The issue I'm having is that I'm building an API and using dependency injection for some of my routes, but when the model is not found I want to return a fallback JSON response, rather than Laravel's default 404 page.

My api.php file;

Route::get('/view/{example}', [ExampleController::class, 'view'])->name('view');

My ExampleController.php file;

    public function view(Request $request, Example $example): JsonResponse
    {
        // Returns a 404 If $example Not Found
        // Do Stuff Here
    }

So if $example doesn't exist in my examples table, Laravel is currently returning a 404 page, whereas I want to return something like;

return response()->json([
    'error' => true,
], Response::HTTP_NOT_FOUND)

I've also added the following to my api.php file:

    Route::fallback(function() {
        return response()->json([
            'error' => true,
        ], Response::HTTP_NOT_FOUND);
    });

This works well for routes that aren't defined, but not for routes where the resource in dependency injection is not defined.

I know I can manually do the checks myself (so within the controller do $example = Example::findOrFail($exampleId) and then handle the response that way) but feels neater to make use of dependency injection, so wondered if there was a way.

0 likes
2 replies
tykus's avatar

Don't type-hint the Example model in the Controller action; but using find rather than findOrFail which will also throw an ModelNotFoundException. I know you might want to be clever and attempt to use dependency injection, but simple and straight-forward is the way to go here.

public function view(Request $request, $id): JsonResponse
{
    $example = Example::find($id);
    if (!$example) {
        return response()->json([
            'error' => true,
        ], Response::HTTP_NOT_FOUND);

        // Do Stuff Here
}
1 like
martinbean's avatar

@mhdev You’ll get a JSON response if you request a JSON response by sending an Accept: application/json header with requests.

Please or to participate in this conversation.