I want to redirect user to other view based on their roles.
for admin i want to redirect it to /home view and for normal user redirect it to emDashboard view. can anyone help me with this?
Thank you guys.
this is my Login Controller
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except([
'logout',
]);
}
public function login()
{
return view('auth.login');
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$email = $request->email;
$password = $request->password;
$dt = Carbon::now();
$todayDate = $dt->toDayDateTimeString();
$activityLog = [
'name' => $email,
'email' => $email,
'description' => 'has log in',
'date_time' => $todayDate,
];
if (Auth::attempt(['email'=>$email,'password'=>$password,'status'=>'Active'])) {
DB::table('activity_logs')->insert($activityLog);
Toastr::success('Login successfully :)','Success');
return redirect()->intended('home');
}elseif (Auth::attempt(['email'=>$email,'password'=>$password,'status'=> null])) {
DB::table('activity_logs')->insert($activityLog);
Toastr::success('Login successfully :)','Success');
return redirect()->intended('home');
}else{
Toastr::error('fail, Wrong Username or Password','Error');
return redirect('login');
}
}
Route for Login and Home Dashboard
Route::controller(LoginController::class)->group(function (){
Route::get('/login', 'login')->name('login');
Route::post('/login', 'Authenticate');
Route::get('/logout', 'logout')->name('logout');
Route::controller(HomeController::class)->group(function () {
Route::get('/home', 'index')->name('home');
Route::get('em/dashboard', 'emDashboard')->name('em/dashboard');
this is the users Model
protected $table = 'users';
protected $fillable = [
'name',
'rec_id',
'email',
'join_date',
'phone_number',
'status',
'role_name',
'avatar',
'password',
];
CodePudding user response:
Add a if check before return redirect()->intended('home');
in your authenticate method... something like this
if(Auth()->user()->role_name == "admin"){
return redirect()->intended('home');
} else {
return redirect()->intended('em/dashboard');
}