Skip to content

Instantly share code, notes, and snippets.

@Bunix
Created April 26, 2020 00:15
Show Gist options
  • Save Bunix/390498fce14057fca6238b571c3424d9 to your computer and use it in GitHub Desktop.
Save Bunix/390498fce14057fca6238b571c3424d9 to your computer and use it in GitHub Desktop.
Laravel authentication with multiple user roles

Getting Started

For starters, whip up a new Laravel application with auth scaffolding.

laravel new multi-auth --auth

Migrations

Let's tweak our user migration and add a role column to determine whether a user is a student or a professor.

Schema::create('users', function (Blueprint $table) {
	$table->id();
	$table->string('name');
	$table->string('email')->unique();
	$table->timestamp('email_verified_at')->nullable();
	$table->string('password');
+	$table->string('role');
	$table->rememberToken();
	$table->timestamps();
});

Extending authentication controllers

We will override the authenticated method to decide where to redirect users after a successful login.

class LoginController extends Controller
{
	use AuthenticatesUsers; // << here are all the goodies
	
	...
	
	protected function authenticated(Request $request, $user)
	{
		if ($user->role === 'professor) {
			return redirect()->route('professors.dashboard');
		}
		
		return redirect()->route('home');
	}
}

There are also a number of other methods that we can use to extend the behavior of authentication classes, check the traits inside these classes for more details.

Redirect if authenticated

Authenticated professors will be forwarded to their dashboard page whenever they tried to visit a guest-only page. Now that we know what we want, head over to app/middleware directory and edit this file:

class RedirectIfAuthenticated
{
	public function handle($request, Closure $next, $guard = null)
	{
		if (! Auth::guard($guard)->check()) {
			return $next($request);
		}
		
		if ($request->user()->role === 'professor') {
			return redirect()->route('professors.dashboard');
		}
		
		return redirect()->route('home');
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment