Laravel – multi user type login

Advertisements

Hello iam new to laravel and i have created a login page with custom Auth that will redirect the users based on their roles.
so far i have been able to let the authenticated users login and stop the unauthenticated users. but i dont know how to redirect the authenticated users to different pages based on their roles?(i have userrole col in my DB)

my controller:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required',
        'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        if (Auth::user()->usertype == "admin") {
            return Redirect::to('admin');
        } elseif (Auth::user()->usertype == "user"){
            return Redirect::to('user');
        }
    } else {
        return redirect()->back()->with('error', 'Invalid Credentials');
    }
}

index:

@extends('layout')
@section('content')
<div class=" row justify-content-center">
 <h1 class="mt-4">Student feedback system</h1>
</div>
 <div class="row justify-content-center ">
    <form method="POST" class="mt-4"                                 >  
        @csrf
        <div class="form-group">
          <label for="exampleInputEmail1">email</label>
          <input name="email" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter ">
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">Password</label>
          <input name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder=" Enter Password">
        </div>

        <button type="submit" class="btn btn-primary" name="submit">Login</button>
      </form>
 </div>
@endsection

web.php:

Route::get('/', function () {
    return view('home');
});


Route::get('/index', function () {
    return view('index');
});


Route::get('/postlogin', function () {
    return view('postlogin');
});


Route::post('index', [control::class, 'login'])->name('index'); 

>Solution :

In your requirement you have to use auth()->user(). In auth user you have to give name role column to check user logged in with which type of role

For example:-
auth()->user()->user_role

Here is an example according to your code and requirement.

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
                    
        if(auth()->user()->user_role == 'admin')
        {
            //  pass admin route
            return redirect()->intended('/postlogin');
        }
        if(auth()->user()->user_role == 'user')
        {
            //  pass user route
            return redirect()->intended('/postlogin');
        }
    }
    else {
        return redirect()->back()->with('error', 'Invalid Credentials');
    }
    
}

Leave a ReplyCancel reply