I have two tables with users, one for public users and one for workers. The workers can only be created by other workers, but when I go to the workers registration url, it detects that I am logged in and redirects me to home, how can I change this behavior?
I have tried commenting out part of the handle function in the RedirectIfAuthenticated.php file but this causes users to be able to visit the login links while logged in.
Function I commented in RedirectIfAuthenticated.php:
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
// foreach ($guards as $guard) {
// if (Auth::guard($guard)->check()) {
// return redirect(RouteServiceProvider::HOME);
// }
// }
return $next($request);
}
My Answer:
> One way to achieve this is by creating a custom middleware that checks the user's role before redirecting. Here's an example of how you can do this:
1. Create a new middleware using the following command:
bash
php artisan make:middleware CheckUserRole
2. Open the newly created middleware file (`CheckUserRole.php`) and modify the `handle` method to check the user's role before redirecting. Here's an example implementation:
php
public function handle(Request $request, Closure $next, ...$guards)
{
$user = Auth::user();
if ($user && $user->isWorker()) {
return $next($request);
}
return redirect('/home');
}
3. Register the middleware in your `app/Http/Kernel.php` file. Add the following line to the `$routeMiddleware` array:
php
'checkUserRole' => \App\Http\Middleware\CheckUserRole::class,
4. Apply the middleware to the route where workers can register. You can do this in your routes file (`web.php`) like this:
php
Route::get('/register-worker', 'WorkerController@register')->middleware('checkUserRole');
By following these steps, you can ensure that only workers can access the worker registration page while still being logged in as a different user.
Rate this post
4 of 5 based on 8809 votesComments