How to access the current authenticated user from a FormRequest class method
I have a User model with two functions to check the gender of a user. For a specific form, I created an object FormRequest
. Now I need to set some validation rules that are gender specific, that is, there is a set of rules for male users and a different set of rules for women.
Here is my user model:
// 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';
}
}
Now FormRequest
there is a authorize()
mehtod in the class to check if the user is logged in and has access to the form that uses the method Auth::check()
and the Auth::user()->profile_ok()
() method that works with throwing any errors. But in the method rules()
, when I try to access the current user via Auth::user()->is_male()
, it throws an error,
FatalErrorException in ProfileRequest.php line 34:
Class 'app\Http\Requests\Auth' not found
Here is my FormRequest class:
// 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
}
}
}
What am I doing wrong? How can I access the current user from the rules () method?
source to share