Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return current User in Laravel 4

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

like image 609
JasonDavis Avatar asked Sep 01 '13 15:09

JasonDavis


1 Answers

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
}
like image 141
Laurence Avatar answered Oct 29 '22 03:10

Laurence