Search code examples
laravelbefore-filterlaravel-routing

How to forward argument for redirect::route->with when hitting an auth filter using Laravel?


I have the following problem:

After a user is created and the user has confirmed her email. I would like the user to login, I use the following code to do that:

Redirect::route('login-forward')->with('alert_message', ...) the alert messages simply states that everything went well, and I would like her to login.

login-forward is protected with an before filter, that runs the actual login form, When the user then logs in sucesfully, she is brought back to login-forward, whic then puts the user at her personal landing page.

the code for the route 'login-forward is:

Route::get('my-login', array(
    'as' => 'login-forward',
    'before' => 'auth',
    function ()
    {
        $user = Auth::user();
        switch ($user->role) 
        {
            case 'Administrator':
                return Redirect::route('admin_dashboard');

            case 'FreeUser':
                return Redirect::route('cs-dashboard');

            default:
                return Redirect::route('/');
        }}));

the problem is, the ->with('alert_message',...) is not seen by the real login route called by the before filter.

How do I solve this?


Solution

  • The best approach is to let the user logs in automatically when the email is confirmed, if the user confirms the account creation then when you find that user is valid then you may log in that user using something like:

    // $user = Get the user object
    Auth::login($user);
    

    Also you may use:

    Session::put('alert_message', ...);
    Redirect::route('login-forward');
    

    Then when the user logs in for the first time, just get the message from Session using:

    // Get and show the alert_message
    // from session and forget it
    @if (Session::has('alert_message'))
        {{ Session::pull('alert_message') }}
    @endif
    

    So, when you pull the message from the Session to show it, the message will no longer be available in the Session or you may use Session::reflash() to flash the flashed session data for another subsequent request until you get in the page where you want to show the message.