【发布时间】:2020-05-30 22:20:18
【问题描述】:
我正在使用Laravel guard 来保护路由,现在我想在不受保护的(普通)路由中获取用户id,例如:
受保护:
/个人资料
不受保护:
/搜索
我能够在受保护的路由中获取用户 ID,例如 ProfileController.php,如下所示:
$id = auth()->guard('agent')->user()->id;
但我想在 searchController.php 中得到它,但它返回 null,知道吗?
api.php:
Route::middleware('auth:agent')->group(function () {
Route::get('profile', 'ProfileController@details');
});
Route::post('search', 'searchController@search');
另一方面,当用户登录并打开搜索页面时,我想获取用户 ID。
【问题讨论】:
-
在
cookie中存储id可以是option! -
我可能听起来很傻,但是当您访问
/search路由时 - 您当时是否通过agent守卫进行了身份验证? -
@SebastianSulinski no,
search不使用警卫 -
我明白这一点,但是当您尝试访问
/search时 - 您当时是否已登录?如果您没有登录,那么显然将没有用户,因为没有经过身份验证。 -
没问题 - 请检查答案 - 一切正常。您是使用默认的
App\Http\Middleware\Authenticate::class中间件还是以任何方式对其进行了修改?如果是默认值,则很可能是守卫的实现。
标签: php laravel laravel-guard