I have a User model with two functions to check gender of the user. For a particular Form I've created a FormRequest
object. Now, I need to setup some validation rules which are specific to users gender, i.e. for male users there is a set of rules and for female users there is another set of rules.
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 in the FormRequest
Class, There is a authorize()
mehtod to check if the user is logged in and have access to the form, which uses Auth::check()
method and Auth::user()->profile_ok()
method(), which works withhout throwing up any errors. But in the rules()
method when I try to access current user via Auth::user()->is_male()
it throws up an error saying,
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 within the rules() method?
The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder: An improvement to this snippet is first checking if there is an authenticated user before trying to access it:
2. Get the User in a Bean The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder: An improvement to this snippet is first checking if there is an authenticated user before trying to access it:
To get the username from inside a method in the class library. In .NET Core, it appears that HttpContext no longer has a Current or User property. Here's a simple use case. Suppose I have a data entity and service that "stamps" entities with the date and username before saving them to the database.
We can define the principal directly as a method argument, and it will be correctly resolved by the framework: The API of the Authentication class is very open so that the framework remains as flexible as possible.
You can do it by $this->user()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With