Apr 25, 2022
7
Level 13
How to add 404 Not found in api routes
I'm working with Laravel 9
I see on postman taht if call a wrong route Laravel retunr 200OK and empty response.
Of course, on Postman if put header Accept with value application/json
Controller
public function index(Request $request)
{
return ($request->full)
? new CommandCenterCollection(CommandCenter::all())
: new CommandCenterResource(CommandCenter::paginate());
}
api.php
Route::group(['prefix' => 'v1', 'as' => 'api.', 'middleware' => ['auth:sanctum']], function () {
Route::apiResource('command-centers', CommandCenterApiController::class);
}
Postman
- https://sitelight.test/api/v1/command-centers/28282828 // No exist model
- https://sitelight.test/api/v1/command-centers/ahahaha // No exists route
All endpoints return status 200 and empty body.
Level 60
https://laravel.com/docs/9.x/errors#rendering-exceptions
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
3 likes
Please or to participate in this conversation.