Laravel 5.2 How To redirect All 404 Errors to Homepage
Solution 1
For that, you need to do add few lines of code to render
method in app/Exceptions/Handler.php
file.
public function render($request, Exception $e)
{
if($this->isHttpException($e))
{
switch (intval($e->getStatusCode())) {
// not found
case 404:
return redirect()->route('home');
break;
// internal error
case 500:
return \Response::view('custom.500',array(),500);
break;
default:
return $this->renderHttpException($e);
break;
}
}
return parent::render($request, $e);
}
Solution 2
For me with php 7.2 + Laravel 5.8, it works like a boss. I changed the render method (app/Exceptions/Handler.php). Therefore, we have to check if the exception is an HTTP exception, because we are calling the getStatusCode () method, which is available only in HTTP exceptions. If the status code is 404, we may return a view (for example: errors.404) or redirect to somewhere or route (home).
app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
if($this->isHttpException($exception)) {
switch ($exception->getStatusCode()) {
// not found
case 404:
return redirect()->route('home');
break;
// internal error
case 500:
return \Response::view('errors.500', [], 500);
break;
default:
return $this->renderHttpException($exception);
break;
}
} else {
return parent::render($request, $exception);
}
}
To test: Add abort(500); somewhere in the flow of your controller to view the page/route. I used 500, but you can use one of errors code: Abort(404)...
abort(500);
Optionally, we may provide a response:
abort(500, 'What you want to message');
Solution 3
I added this to the routes/web.php to redirect 404 pages to home page
Route::any('{query}', function() { return redirect('/'); })->where('query', '.*');
Buglinjo
I'm into programming for over 9 years and have huge production experience. Most of my career I have worked on Microservices and backend-heavy projects. My passion is to develop stateless, clean, and scalable microservices with Docker and Kubernetes. I'm a hard-working, high-quality professional with huge experience behind. I've more than 7 years of production experience and developed numerous projects using different frameworks and languages including Laravel/PHP, Golang, NodeJS, TypeScript, Server-side Swift, etc... Ohh, forgot... I like IoT so, soo much that I have a huge collection of Arduino and Raspberry Pi boards and have developed a few interesting projects at home. So, that's it...
Updated on June 08, 2022Comments
-
Buglinjo almost 2 years
How can I redirect all 404 errors to homepage? I have custom Error Page but google analytics is throwing too much errors.