1

I am developing a web application with laravel 5.2 multi auth.

here is my code.

Auth.php

  'guards' => [
    'a' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'b' => [
        'driver' => 'session',
        'provider' => 'customers',
    ],
],



   'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'customers' => [
        'driver' => 'eloquent',
        'model' => App\Customer::class,
    ],
],

IndexController.php

 public function doLogin(){
    $credentails = [
        'name'      =>Input::get('name'),
        'password'  =>Input::get('password')
    ];

    if(Auth::guard('a')->attempt($credentails)){
        return Redirect::to(route('sessionviewa'));
    }else{
        return "Login Error";
    }
}


public function logout(){
    Auth::guard('a')->logout();
    return "succeess";
}

public function SessionViewA(){
    dd(Auth::guard('a')->user());
}

public function SessionViewB(){
    dd(Auth::guard('b')->user());
}

Routes.

 Route::post('dologin',['as'=>'dologin','uses'=>'IndexController@doLogin']); 

Route::get('sessiona',['as'=>'sessionviewa','uses'=>'IndexController@SessionViewA']); 
Route::get('sessionb',['as'=>'sessionviewb','uses'=>'IndexController@SessionViewB']); 

I can login successfully, but not getting logged in user data. ?

Now its returning as null in my browser.

2 Answers 2

0

I see that you're using Laravel 5.2, I have this problem also before.

I solve this by putting my route into the web middleware group in route.php. This way, I can access the Auth and get the user I want.

Route::group(['middleware' => ['web']], function () {
    // Your route here
});

Try it and let me know its working or not.

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks Nizam, so obvious yet I just wasted a couple of hours on it :).

I'd like to point out that my problem was that though I did have the middleware specified in the route group where the login happens, I was trying to access the authenticated user from a different group that didn't - banging my head why it doesn't work. The moral of the story is, of course, have the middleware on each route where you need access to the guard.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.