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 >
<h1 >Student feedback system</h1>
</div>
<div >
<form method="POST" >
@csrf
<div >
<label for="exampleInputEmail1">email</label>
<input name="email" type="text" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter ">
</div>
<div >
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" id="exampleInputPassword1" placeholder=" Enter Password">
</div>
<button type="submit" 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');
CodePudding user response:
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');
}
}