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

abkrim's avatar
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

All endpoints return status 200 and empty body.

0 likes
7 replies
abkrim's avatar
Level 13

@Nakov This not work. Almost in Laravel 9. Just tried after looking for solution in Google.

Thanks.

abkrim's avatar
Level 13

@Sergiu17 Also this not work for me.

In two ways, get same result. 200OK and empty json.

I put a dd($request) for see dump, on index() method of controller, and not get dump.

abkrim's avatar
Level 13

@jlrdw Thanks... Obtuse.. After one horu with this question, I was obtuse and didn't see it.

Yes now.

mehdi0121's avatar

@abkrim hello use this in Exceptions->Handler.php


    public function render($request,Throwable $exception)
    {
       //Model and Route not found error
        if($exception instanceof NotFoundHttpException || $exception instanceof ModelNotFoundException){
         return   $this->NotFOUNDExceptionMessage($request,$exception);
        }

}

    //Model and route not found message
    public function NotFOUNDExceptionMessage($request,Exception $exception)
    {
        # code...
        return $request->expectsJson() ?
        response( [
            'data'=>[
                'message'=>'not found'
            ]
            ],Response::HTTP_NOT_FOUND)
        :parent::render($request,$exception);
    }

Please or to participate in this conversation.