Using PHP and Laravel 4 I have a method in my User model like this below to check for Admin user…
public function isAdmin()
{
if(isset($this->user_role) && $this->user_role === 'admin'){
return true;
}else{
return false;
}
}
This doesn’t work when I call this function in other classes or models though.
To get the desired result I had to do it like this instead…
public function isAdmin()
{
if(isset(Auth::user()->user_role) && Auth::user()->user_role === 'admin'){
return true;
}else{
return false;
}
}
I am trying to access this inside my Admin Controller like this below but it returns an empty User object instead of current logged in user Object…
public function __construct(User $user)
{
$this->user = $user;
}
So my question is how can I get the first version to work? When I instantiate a User object in another class, I need to somehow make sure it has the data for the current logged in user but I am not sure the best way to do that…I know this is basic I am just a little rusty right now could use the help, thanks
This returns the user repository – not the current logged in user
public function __construct(User $user)
To access the current logged in user ANYWHERE in your application – just do
Auth::user()
(like your middle example)
So therefore – to check if a user is an admin user ANYWHERE in your application – just do
if (Auth::user()->isAdmin())
{
// yes
}
else
{
// no
}
Tags: laravel, php, phplaravel