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

shashi_verma's avatar

What should happen when API route doesn't found or match?

I am creating an API in Laravel using Passport and using Postman for the testing of API. I am getting the output in JSON in Postman, so when I hit that route in Postman i.e. http://localhost:8000/api/login it works fine. But, what if my URL is http://localhost:8000/api/log which means a wrong URL then it's returning some error in HTML, here I want to show a message which may be 'Not Found' or something else in JSON format. HOW TO SHOW A PARTICULAR MESSAGE WHEN A METHOD OR ACTION IS NOT DEFINED IN CONTROLLER?

0 likes
9 replies
Guru5005's avatar
Guru5005
Best Answer
Level 3

try the code into app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        if ($request->is('api/*')) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('404', [], 404);
    }
    return parent::render($request, $exception);
}
Guru5005's avatar

yes would need the api's in the api.php, and by default all the api's start from prefix 'api/', if u r using any custom prefixes than u need to update the above code.

shashi_verma's avatar

@rugiguru Thanks for your reply, Did not work, in Postman when I use pretty with JSON it says unexpected '<' and in Preview it shows No message.

shashi_verma's avatar

@rugiguru this is my api.php Route::post('login', 'API\UserController@login'); Route::post('register', 'API\UserController@register');

//Route::controller('/','API\UserController');

Route::group(['middleware' => 'auth:api'], function(){

Route::post('details', 'API\ShowuserController@details');

Route::get('showall', 'API\ShowuserController@showall');

}); Route::post('show', 'API\ShowuserController@show');

shashi_verma's avatar

@rugiguru I haven't created view files for this controller's action, so it's showing me this there InvalidArgumentException View [notFound] not found.

Please or to participate in this conversation.