Reputation: 1272
I'm new to laravel. I want to display a custom 404 error depending on requested url.
Example:
site.com/somepage
and
site.com/admin/somepage
I've see this answer but it's for laravel 4. I can't find the equivalent answer for Laravel 5.1
Please help. Thanks!
My code based on suggestion by Abdul Basit
//Handle Route Not Found
if ($e instanceof NotFoundHttpException) {
//Ajax Requests
if ($request->ajax() || $request->wantsJson()) {
$data = [
'error' => true,
'message' => 'The route is not defined',
];
return Response::json($data, '404');
} else {
//Return view
if (Request::is('admin/*')) {
return Response::view('admin.errors.404', array(), 404);
} else {
return Response::view('errors.404', array(), 404);
}
}
}
//Handle HTTP Method Not Allowed
if ($e instanceof MethodNotAllowedHttpException) {
//Ajax Requests
if ($request->ajax() || $request->wantsJson()) {
$data = [
'error' => true,
'message' => 'The http method not allowed',
];
return Response::json($data, '404');
} else {
//Return view
if (Request::is('admin/*')) {
return Response::view('admin.errors.404', array(), 404);
} else {
return Response::view('errors.404', array(), 404);
}
}
}
Upvotes: 0
Views: 1569
Reputation: 11
Check the fallback route, you may define a route that will be executed when no other route matches the incoming request, The fallback route should always be the last route registered by your application. https://laravel.com/docs/5.8/routing#fallback-routes
Route::fallback(function () {
//Send to 404 or whatever here.
});
Upvotes: 0
Reputation: 439
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to.
Upvotes: 0
Reputation: 971
You can do the logic for that in render
method of App\Exceptions\Handler
in app\Exceptions\Handler.php
public function render($request, Exception $e)
{
//Handle Route Not Found
if ($e instanceof Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
{
//Ajax Requests
if($request->ajax() || $request->wantsJson())
{
$data = [
'error' => true,
'message' => 'The route is not defined',
];
return Response::json($data, '404');
}
else
{
//Return view
return response()->view('404');
}
}
//Handle HTTP Method Not Allowed
if ($e instanceof Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException)
{
//Ajax Requests
if($request->ajax() || $request->wantsJson())
{
$data = [
'error' => true,
'message' => 'The http method not allowed',
];
return Response::json($data, '404');
}
else
{
//Return view
return response()->view('404');
}
}
return parent::render($request, $e);
}
Upvotes: 3