如何从 FormRequest 类方法中访问当前经过身份验证的用户

Posted

技术标签:

【中文标题】如何从 FormRequest 类方法中访问当前经过身份验证的用户【英文标题】:How to access current authenticated user from within FormRequest class method 【发布时间】:2015-07-10 07:41:56 【问题描述】:

我有一个用户模型,它有两个功能来检查用户的性别。对于一个特定的表单,我创建了一个FormRequest 对象。现在,我需要设置一些特定于用户性别的验证规则,即男性用户有一套规则,女性用户有另一套规则。

这是我的用户模型:

// app\User.php
class User extends Model implements AuthenticatableContract, CanResetPasswordContract 

    use Authenticatable, CanResetPassword;

    public function is_male()
    
        return $this->gender == Gender::male();
    

    public function is_female()
    
        return $this->gender == Gender::female();
    

    public function profile_ok()
    
        return $this->status == 'OK';
    

现在在FormRequest 类中,有一个authorize() mehtod 用于检查用户是否已登录并可以访问表单,它使用Auth::check()method 和Auth::user()->profile_ok() method(),没有抛出任何错误。但是在rules() 方法中,当我尝试通过Auth::user()->is_male() 访问当前用户时,它会抛出一个错误提示,

FatalErrorException in ProfileRequest.php line 34:
Class 'app\Http\Requests\Auth' not found

这是我的 FormRequest 类:

// app\Http\Requests\ProfileRequest.php
class ProfileRequest extends Request 
    public function authorize()
    
        if ( !Auth::check() )
        
            return false;
        
        return Auth::user()->profile_ok();
    

    public function rules()
    
        if(Auth::user()->is_male())
        
            return ['rule1' => 'required',]; //etc
        
        if(Auth::user()->is_female())
        
            return ['rule2' => 'required',]; //etc
        
    

我做错了什么?如何从 rules() 方法中访问当前用户?

【问题讨论】:

【参考方案1】:

你可以通过$this->user()来做

【讨论】:

以上是关于如何从 FormRequest 类方法中访问当前经过身份验证的用户的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5:在从 BaseController 扩展的控制器中对 FormRequest 类进行类型提示

Laravel 5.5 FormRequest 自定义表单请求验证类

如何在 Laravel 5.1 中强制 FormRequest 返回 json?

Laravel通过request表单验证类返回封装http状态码

Laravel通过request表单验证类返回封装http状态码

如何从另一个类引用当前或主要活动