-1

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?

shashi verma
  • 873
  • 2
  • 15
  • 25
  • This question should be marked as duplicate. https://stackoverflow.com/questions/53279247/laravel-how-to-show-json-when-api-route-is-wrong-or-not-found – Farooq Ahmed Khan Nov 16 '18 at 04:23
  • 1
    Does this answer your question? [Laravel - How to show JSON when API route is wrong or not found?](https://stackoverflow.com/questions/53279247/laravel-how-to-show-json-when-api-route-is-wrong-or-not-found) – miken32 Dec 10 '20 at 19:09
  • @miken32 I don't work in Laravel anymore :) – shashi verma Dec 26 '20 at 12:36

1 Answers1

1

Have a look at these articles that talks about fallback routes in 5.5+

https://themsaid.com/laravel-55-better-404-response-20170921

https://laravel-news.com/404-responses-laravel-api

As you can read you can create a fallback route which then allows you to control the response.

So you would want something like this:

Route::fallback(function(){
    return response()->json(['message' => 'Not Found.'], 404);
})->name('api.fallback.404');
Josh
  • 1,316
  • 10
  • 26
  • Thanks for Answer, yes I put this code in my api.php, it is working but I have to change the HTTP method in postman from post to get for login and then it return 'Not Found' but then I can't use the login functionality. – shashi verma Nov 16 '18 at 05:07
  • Hi Sashi. you would need to create 2 routes. 1 for api and the other for user interface. I would then use access tokens for accessing the api which the user can get through the user interface for incorporating into their api code. Also if you are having issues with not found then you need to create a route for that issue – Josh Nov 16 '18 at 05:21