前言
登录跳转:
不同的用户在登录成功之后跳转到不同的网页当中
例如:网站管理员登录成功后跳转到网站后台,vip用户登录成功后跳转到vip页面
准备工作
用户表
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`role` varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'normal',
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`),
KEY `users_role_index` (`role`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
分别录入系统管理员、vip用户和普通用户
使用redirectPath和middeware实现安全的登录跳转
1)app\Http\Controllers\Auth\LoginController.php下复写redirectPath方法
判断登录的用户,实现不同的跳转页
//复写redirectPath实现登录跳转
public function redirectPath()
{
switch (auth()->user()->role) {
case 'admin':
return 'admin/dashboard';
case 'vip':
return 'vip/dashboard';
default:
return '/home';
}
}
2)创建Isvip和Isadmin中间件过滤越权访问用户
php artisan make:middleware Isvip
php artisan make:middleware Isadmin
Isvip
public function handle($request, Closure $next)
{
//如果是vip则往下执行逻辑
if(auth()->user()->role === 'vip'){
return $next($request);
}
//不是vip则跳转到首页
return redirect('/home');
}
Isadmin
public function handle($request, Closure $next)
{
//如果是管理员则往下执行逻辑
if(auth()->user()->role === 'admin'){
return $next($request);
}
//不是管理员则跳转到首页
return redirect('/home');
}
app\Http\Kernel.php注册Isadmin和Isvip中间件
protected $routeMiddleware = [
\Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\Isadmin::class,
'vip' => \App\Http\Middleware\Isvip::class,
];
路由中加入中间件进行访问过滤
//中间件检查访问该目录admin/dashboard是否为admin用户,过滤不合格的用户
Route::get('admin/dashboard', function (){
return view('admin.dashboard');
})->middleware(['auth','admin']);
//中间件检查访问该目录vip/dashboard是否为vip用户,过滤不合格的用户
Route::get('vip/dashboard', function (){
return view('vip.dashboard');
})->middleware(['auth','vip']);
优化在不使用复写redirectPath方法下实现登录跳转
创建UserRoleRedirect中间件用于不同用户登录跳转不同页面功能实现
php artisan make:middleware UserRoleRedirect
UserRoleRedirect逻辑代码
public function handle($request, Closure $next)
{
switch (auth()->user()->role) {
case 'admin':
return redirect('admin/dashboard');
case 'vip':
return redirect('vip/dashboard');
default:
break;
}
return $next($request);
}
路由使用结合admin和vip中间件过滤
Route::get('/home', function () {
return view('welcome');
})->middleware(['auth','auth.redirect']);
Auth::routes();
//中间件检查访问该目录admin/dashboard是否为admin用户,过滤不合格的用户
Route::get('admin/dashboard', function (){
return view('admin.dashboard');
})->middleware(['auth','admin']);
//中间件检查访问该目录vip/dashboard是否为vip用户,过滤不合格的用户
Route::get('vip/dashboard', function (){
return view('vip.dashboard');
})->middleware(['auth','vip']);
到此这篇关于Laravel实现登录跳转功能的文章就介绍到这了,更多相关Laravel登录跳转内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!