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.