For starters, whip up a new Laravel application with auth scaffolding.
laravel new multi-auth --authLet'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();
});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.
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');
}
}