How to Change Default Redirect Url of Laravel 5 Auth Filter

How to change default redirect URL of Laravel's Auth filter?

In your app/filters.php you may find something like this:

Route::filter('auth', function($route, $request)
{
if (Auth::guest()) return Redirect::guest('login');
});

You need to change the return Redirect::guest('login') to this:

return Redirect::guest('user/login');

How to change default middleware redirect

By default User get redirected to $redirectTodefined in
Http/Controllers/Auth/LoginController. Update this to your needs.

use AuthenticatesUsers;

/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';

Auth filter redirecting back to original POST request in Laravel

I had the same desire to redirect back to a POST request with the original input. I could not find an existing way to do this in Laravel except for redirecting to to the intended URL via GET.

Laravel 5

I first solved this in Laravel 4 following the outline below but found the exact same setup not to work in Laravel 5. Follow the outline for Laravel 4 but instead of the creating the IntendedUrlServiceProvider create a Middleware.

  1. The problem is that in Laravel 5 the session seems to be started with the StartSession which runs after all of the ServiceProviders.

/app/Http/Middleware/IntendedUrl.php

<?php namespace App\Http\Middleware;

use Closure;
use Request;
use Session;

class IntendedUrl {

/**
* This loads saved POST input data and changes the method to POST if a visitor tried to access a page
* but was blocked via an auth filter. Auth filter saves data via the Redirect::guest() and after
* login it needs to be repopulated to simulate a POST.
*
* GET requests also may pass through here. I am less certain if it is required for them but shouldn't hurt
* and may help load any input data.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Check to see if we were redirected to this page with the Redirect::intended().
// We extended the class to track when the redirect occurs so we know to reload additional request data
if (Session::has('intended.load')) {
// intended.load could be set without these being set if we were redirected to the default page
// if either exists, both should exist but checking separately to be safe
if (Session::has('intended.method')) {
Request::setMethod(Session::get('intended.method'));
}
if (Session::has('intended.input')) {
Request::replace(Session::get('intended.input'));
}
// Erase all session keys created to track the intended request
Session::forget('intended');

// Laravel 5.2+ uses separate global and route middlewares. Dispatch altered request as the route type changed. *Credit to Munsio in answer below
return \Route::dispatch($request);
}

return $next($request);
}

}

  1. Then instead of adding the IntendedUrlServiceProvider as in step 4 below add the new middleware after the StartSession in the $middleware array of /app/Http/Kernel.php

protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',

'App\Http\Middleware\IntendedUrl',
];
  • Also of note, just for organization I moved my customer service providers to the new standard /App/Providers and changed their namespace.

Laravel 4

I decided to extend the framework to add this feature. It will be hard to detail my complete solution, but here is an outline. To do this you will need to be pretty familiar with the framework and read up on how to extend it.
http://laravel.com/docs/extending#ioc-based-extension

I also referenced Taylor's book "Laravel from Apprentice to Artisan"

  1. Extend the Redirector class to record additional info on the intended request.

    <?php namespace GQ\Routing;
    class Redirector extends \Illuminate\Routing\Redirector {
    /**
    * ** Extended to add functionality for restoring POST input and the POST method after a login
    */
    public function guest($path, $status = 302, $headers = array(), $secure = null)
    {
    // Recording the method and input for the request so that it can be reloaded after being redirected back to the intended page
    $this->session->put('intended.method', $this->generator->getRequest()->getMethod());
    $this->session->put('intended.input', $this->generator->getRequest()->all());

    return parent::guest($path, $status, $headers, $secure);
    }

    /**
    * ** Extended to record in the session when we redirect to an intended page so method and input can be loaded on the next page
    */
    public function intended($default = '/', $status = 302, $headers = array(), $secure = null)
    {
    $redirect_response = parent::intended($default, $status, $headers, $secure);

    // Set the intended.load session variable so we know we returned to the intended page and can load the additional method and input
    return $redirect_response->with('intended.load', true);
    }
    }
    ?>
  2. Create a new Service Provider that writes over "redirect" in the IOC container. I originally tried extending the RoutingServiceProvider but had trouble with that working.

    <?php namespace App\Providers;

    use GQ\Routing\Redirector;
    use Illuminate\Support\ServiceProvider;
    class RedirectServiceProvider extends ServiceProvider {

    protected $defer = true;

    /**
    * Register the Redirector service.
    *
    * ** Copy of class registerRedirector from RoutingServiceProvider,
    * using a different "use" statement at the top to use the extended Redirector class
    * Extending the RoutingServiceProvider was more of a pain to do right since it is loaded as a base provider in the Application
    *
    * @return void
    */
    public function register()
    {
    $this->app['redirect'] = $this->app->share(function($app)
    {
    $redirector = new Redirector($app['url']);

    // If the session is set on the application instance, we'll inject it into
    // the redirector instance. This allows the redirect responses to allow
    // for the quite convenient "with" methods that flash to the session.
    if (isset($app['session.store']))
    {
    $redirector->setSession($app['session.store']);
    }

    return $redirector;
    });
    }
    public function provides() {
    return array('redirect');
    }
    }
  3. Create a new service provider which will set the intended method and input after the redirect.

    <?php

    namespace GQ\Providers;

    use Illuminate\Support\ServiceProvider;

    class IntendedUrlServiceProvider extends ServiceProvider {
    /**
    * Bootstrap the application events.
    *
    * @return void
    */
    public function boot() {
    // Check to see if we were redirected to this page with the Redirect::intended().
    // We extended the class to track when the redirect occurs so we know to reload additional request data
    if (\Session::has('intended.load')) {
    // intended.load could be set without these being set if we were redirected to the default page
    // if either exists, both should exist but checking separately to be safe
    if (\Session::has('intended.method')) {
    \Request::setMethod(\Session::get('intended.method'));
    }
    if (\Session::has('intended.input')) {
    \Request::replace(\Session::get('intended.input'));
    }
    // Erase all session keys created to track the intended request
    \Session::forget('intended');
    }
    }

    public function register() {
    }
    }
  4. Finally add your 2 new service providers to your providers array in app/config/app.php

    'GQ\Providers\RedirectServiceProvider',
    'GQ\Providers\IntendedUrlServiceProvider',

Hopefully this steers you in a good direction. This has worked for me but I have not tested it extensively. Maybe if it continues to work well we could build a composer package or get the ability included in Laravel.

Laravel redirect back to original destination after login

For Laravel 5.3 and above

Check Scott's answer below.

For Laravel 5 up to 5.2

Simply put,

On auth middleware:

// redirect the user to "/login"
// and stores the url being accessed on session
if (Auth::guest()) {
return redirect()->guest('login');
}
return $next($request);

On login action:

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('defaultpage');
}

For Laravel 4 (old answer)

At the time of this answer there was no official support from the framework itself. Nowadays you can use the method pointed out by bgdrl below this method: (I've tried updating his answer, but it seems he won't accept)

On auth filter:

// redirect the user to "/login"
// and stores the url being accessed on session
Route::filter('auth', function() {
if (Auth::guest()) {
return Redirect::guest('login');
}
});

On login action:

// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return Redirect::intended('defaultpage');
}

For Laravel 3 (even older answer)

You could implement it like this:

Route::filter('auth', function() {
// If there's no user authenticated session
if (Auth::guest()) {
// Stores current url on session and redirect to login page
Session::put('redirect', URL::full());
return Redirect::to('/login');
}
if ($redirect = Session::get('redirect')) {
Session::forget('redirect');
return Redirect::to($redirect);
}
});
// on controller
public function get_login()
{
$this->layout->nest('content', 'auth.login');
}

public function post_login()
{
$credentials = [
'username' => Input::get('email'),
'password' => Input::get('password')
];

if (Auth::attempt($credentials)) {
return Redirect::to('logged_in_homepage_here');
}

return Redirect::to('login')->with_input();
}

Storing the redirection on Session has the benefit of persisting it even if the user miss typed his credentials or he doesn't have an account and has to signup.

This also allows for anything else besides Auth to set a redirect on session and it will work magically.

Laravel 5.5 change unauthenticated login redirect url

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

It's just the case that the function is not there by default anymore.

You can just override it as you did in 5.4. Just make sure to include

use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;

in the Handler file.

For Example my app/Exceptions/Handler.php looks somewhat like this:

<?php
namespace App\Exceptions;
use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
(...) // The dfault file content
/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json(['message' => 'Unauthenticated.'], 401)
: redirect()->guest(route('authentication.index'));
}
}

Change default /auth/login routes in laravel 5

use these routes in your routes.php file :

Route::get('ingresar' , 'Auth\AuthController@getLogin' ) ;
Route::post('registrar', 'Auth\AuthController@postLogin') ;

when defining routes in laravel, the second argument is the name of the controller and the related action.

in laravel applications, the AuthController.php file is located inside 'Auth' folder with a path like this:

project_root\app\Http\Controllers\Auth\AuthController.php

thats why we use 'Auth\AuthController' to define our routes.

laravel redirect to url after login

I've decided to copy and paste the getLogin function of the trait AuthenticatesUsers into my AuthController. I overwrite the function AND keep the trait as is.

I've just added

\Session::put('url.intended',\URL::previous());



Related Topics



Leave a reply



Submit