Back to Course |
[Mini-Course] Laravel 11: Breeze with User Role Areas

Auto-Redirect to Correct Area after Login/Register

Next, let's work on redirecting users to the correct page after login or registration. For now, we have hard-coded a redirect to the student timetable page. Let's change it.


User Model: Redirect Method

We will create a method that returns a route name based on the user's role.

This method can be placed in various places, but I think it is best suited in the User Model. In the method, we can use the PHP match expressions to return a route name.

app/Models/User.php:

class User extends Authenticatable
{
use HasFactory, Notifiable;
 
// ...
 
public function getRedirectRouteName(): string
{
return match ((int) $this->role_id) {
1 => 'student.timetable',
2 => 'teacher.timetable',
};
}
}

Controllers: Redirect Based on Role

Now, we can use this method to redirect users to the proper page based on its role.

app/Http/Controllers/Auth/AuthenticatedSessionController.php:

class AuthenticatedSessionController extends Controller
{
// ...
 
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
 
$request->session()->regenerate();
 
return redirect()->intended(route('student.timetable', absolute: false));
return redirect()->intended(route(auth()->user()->getRedirectRouteName(), absolute: false));
}
 
// ...
}

app/Http/Controllers/Auth/RegisteredUserController.php:

class RegisteredUserController extends Controller
{
// ...
 
public function store(Request $request): RedirectResponse
{
// ...
 
return redirect(route('student.timetable', absolute: false));
return redirect(route(auth()->user()->getRedirectRouteName(), absolute: false));
}
}

After logging in or registering, the user is redirected to the correct page.

However, if someone knows the URL for the different roles pages, they can still access them. We will add restrictions in the next lesson.