我正在尝试修改Laravel,因此它将检查登录用户是否已经登录过,无论他们首次登录时将导航到哪个页面。
目前,只有在用户首次登录时将用户重定向到"/home"
时,它才能正常工作:
UserController.php
:
public function index()
{
$user = Auth::user();
if (!$user->last_login){
//This will redirect the user to the onboarding area, if they haven't logged in before.
return redirect()->route('onboarding');
}else{
if ($user->isAdmin()) {
return view('pages.admin.home');
}
return view('pages.user.home');
}
}
public function onboarding(){
//If the user hasn't logged in yet, let's onboard him/her
//Please check function index(), for the actual redirect.
return view('onboarding.home');
}
routes/Web.php
:
//Onboarding
Route::get('/onboarding', 'UserController@Onboarding')->name('onboarding');
现在,如前所述,它将仅在用户导航到"/home"
时重定向,但是,如果用户决定转到"/profile"
,则他/她将不会重定向到{{1} }。
全局检查最合适的位置在哪里(无论我的网站上的网址是什么),如果这是用户首次登录,应该将他/她重定向到"/onboarding"
?
答案 0 :(得分:6)
这听起来像做一个检查每个请求的中间件有意义。像这样:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfFirstLogin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
$user = Auth::user();
if (!$user->last_login){
//This will redirect the user to the onboarding area, if they haven't logged in before.
return redirect()->route('onboarding');
}
return $next($request);
}
}
您需要在Kernel.php
中注册路线:
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
// ...
'onboarding' => \App\Http\Middleware\RedirectIfFirstLogin::class,
// ...
];
然后可以用Route::group
包装所有适用于它的路由。您将需要确保任何路由(例如登录名或onboarding
路由本身)必须不在此Route::group
之外。
Route::get('/onboarding', 'UserController@Onboarding')->name('onboarding');
Route::group(['middleware' => ['onboarding']], function () {
// all routes will go here.
}