2

I'm setting up an API with Laravel. When I enter a route that does not exist I get redirected to a view that says 404 | Not found.

How could I change this view to abort( response()->json('Not Found', 404)); so that the person that tries to access the API via another application get a JSON response saying Not Found.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Michael
  • 355
  • 1
  • 8
  • 17

4 Answers4

4

You may publish Laravel's error page templates using the vendor:publish Artisan command. Once the templates have been published, you may customize them to your liking:

php artisan vendor:publish --tag=laravel-errors
Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39
1

You only need to create a 404.blade.php file under resources/views/errors/ with whatever content and style you want. I've just done that...

Custom 404 page in Laravel

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
0

Otherwhise

define a fallback route at the end of the routes/api.php file:

Route::fallback(function(){
    return response()->json(['message' => 'Not Found.'], 404); 
})->name('api.fallback.404');

Source

Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39
0

Try these steps:

1) In the app/Exceptions/Handler.php file, modify the render method.

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if ($exception->getStatusCode() == 404) {
            return response()->view('errors.' . '404', [], 404);
        }
    }

    return parent::render($request, $exception);
}

2) Create a new view file errors/404.blade.php.

<!DOCTYPE html>
<html>
<head>
    <title>Page not found - 404</title>
</head>
<body>
The page your are looking for is not available
</body>
</html>
Shamsheer
  • 734
  • 4
  • 8