Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5 redirect user after login based on user's role

My 'users' table has a 'role' column and when users are registered or logged in, I want them to be redirected based on their role column. how can I do that?

like image 676
Salar Avatar asked Apr 23 '16 14:04

Salar


People also ask

How do I redirect after authentication?

During a user's authentication, the redirect_uri request parameter is used as a callback URL. This is where your application receives and processes the response from Auth0, and is often the URL to which users are redirected once the authentication is complete.

How do I redirect back to original URL after successful login in laravel?

You may use Redirect::intended function. It will redirect the user to the URL they were trying to access before being caught by the authenticaton filter.

How do I redirect from one page to another in laravel?

By default laravel will redirect a user to the home page like so: protected $redirectTo = '/home'; To change that default behaviour, add the following code in App/Http/Controllers/Auth/LoginController. php . This will redirect users (after login) to where ever you want.


3 Answers

I added this function to AuthController.php and everything fixed magically

public function authenticated($request , $user){
    if($user->role=='super_admin'){
        return redirect()->route('admin.dashboard') ;
    }elseif($user->role=='brand_manager'){
        return redirect()->route('brands.dashboard') ;
    }
}
like image 57
Salar Avatar answered Oct 21 '22 05:10

Salar


If you are using the Authentication system provided with Laravel you can override the redirectPath method in your Auth\AuthController.

For example, this would redirect a user with role 'admin' to /admin and any other user to /account:

public function redirectPath()
{
    if (\Auth::user()->role == 'admin') {
        return "/admin";
        // or return route('routename');
    }

    return "/account";
    // or return route('routename');
}

You could also use Laravel Authorization (introduced in 5.1.11) to manage role logic.

like image 20
SlateEntropy Avatar answered Oct 21 '22 04:10

SlateEntropy


In laravel 5.7 there is no AuthController.php so you have to go Controllers\Auth\LoginController.php and add the below function,

If the redirect path needs custom generation logic you may define a redirectTo method instead of a redirectTo property

protected function redirectTo()
{

    if($user->role=='super_admin'){
        return '/path1';
    }elseif($user->role=='brand_manager'){
        return '/path2';
    }   

}
like image 42
Mohamad Osama Avatar answered Oct 21 '22 04:10

Mohamad Osama