gpt4 book ai didi

php - Laravel-Event:如何在事件中使用 Auth::user()?

转载 作者:行者123 更新时间:2023-12-04 00:38:03 25 4
gpt4 key购买 nike

当我在 CandidateEvent 中询问 if(Auth::user()->role == "xxxx") 时,显示“正在尝试获取非对象的属性”

问题是组件 Auth::user() 在我的事件中不工作。

在事件中使用 Auth 的正确方法是什么?

public function __construct()
{
if(Auth::user()->role == "XXXX")
{
$candidate = count(Candidate::CountNewCandidate());
}
else
{
$candidate = count(Candidate::CountNewCandidateGroup());
}
$this->data = [ 'cCandidate' => $candidate ];
}

最佳答案

如果没有经过身份验证的用户 Auth::user() 将返回 null,所以 Auth::user()->role将引发 Trying to get property of non-object;尝试使用 Auth::check() 检查是否有经过身份验证的用户,然后您可以检查角色:

public function __construct()
{
if(auth()->check() && auth()->user()->role == "XXXX")
{
$candidate = count(Candidate::CountNewCandidate());
}
else
{
$candidate = count(Candidate::CountNewCandidateGroup());
}
$this->data = [ 'cCandidate' => $candidate ];
}

注意:我使用了辅助函数 auth() .

希望对您有所帮助。

关于php - Laravel-Event:如何在事件中使用 Auth::user()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38732252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com