Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to homepage if route doesnt exist in Laravel 5

Tags:

/** Redirect 404's to home
*****************************************/
App::missing(function($exception)
{
    // return Response::view('errors.missing', array(), 404);
    return Redirect::to('/');
}); 

I have this code in my routes.php file. I am wondering how to redirect back to the home page if there is a 404 error. Is this possible?

like image 245
justin.esders Avatar asked Apr 06 '15 20:04

justin.esders


People also ask

How do I redirect a route in Laravel?

Laravel offers an easy way to redirect a user to a specific page. By using the redirect() helper you can easily create a redirect like the following: return redirect('/home'); This will redirect the user to the /home page of your app.

How do I fix error 404 in Laravel?

It should be enough to just run php artisan vendor:publish --tag=laravel-errors and then edit the newly created resources/views/errors/404.

How do I redirect a user to another page after login in Laravel?

Laravel built-in authentication system has a $redirectTo property that you can use to customize where the user will be redirected after successful login/registration. But we can customize even more than that. By default, app/Http/Controllers/Auth/RegisterController. php has the $redirectTo property.


2 Answers

For that, you need to do add few lines of code to render method in app/Exceptions/Handler.php file which looks like this:

public function render($request, Exception $e)
    {
        if($this->isHttpException($e))
        {
            switch ($e->getStatusCode()) 
                {
                // not found
                case 404:
                return redirect()->guest('home');
                break;

                // internal error
                case '500':
                return redirect()->guest('home');
                break;

                default:
                    return $this->renderHttpException($e);
                break;
            }
        }
        else
        {
                return parent::render($request, $e);
        }
    }
like image 73
William Langlois Avatar answered Jan 03 '23 18:01

William Langlois


I just want to add a suggestion for cleaning it up a bit more. I'd like to credit the accepted answer for getting me started. In my opinion however since every action in this function will return something, the switch and else statement create a bit of bloat. So to clean it up just a tad, I'd do the following.

public function render($request, Exception $e)
{
    if ($this->isHttpException($e))
    {
        if ($e->getStatusCode() == 404)
           return redirect()->guest('home');

        if ($e->getStatusCode() == 500)
           return redirect()->guest('home');
    }

    return parent::render($request, $e);
}
like image 39
MMMTroy Avatar answered Jan 03 '23 16:01

MMMTroy