我正在尝试修改 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"
,他/她不会被重定向到 "/onboarding"
。
全局检查在哪里最合适(无论我网站上的什么url),如果是用户第一次登录,他/她应该被重定向到“/onboarding”
?
最佳答案
这听起来像一个检查每个请求的中间件是有意义的。像这样:
<?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.
}
关于PHP - Laravel 检查全局首次登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51174492/