Laravel 5 with entrust - hasRole not working

2019-07-22 17:42发布

问题:

I have a logged in user and the code here works:

@if( Auth::check() )
Logged in as: {{ Auth::user()->firstname }} {{ Auth::user()->lastname  }}
@endif

I'm using zizaco/entrust and it's all working. I've created roles and permissions and given my user the admin role which has administrative permission.

So why doesn't this work:

$user = Auth::user();
print_r($user->hasRole('admin'));

If I print_r the $user I can see that the Auth user is loaded, but hasRole is not working. I was just testing this within the blade template at the moment but tried it in the Controller with the same result. My error is:

BadMethodCallException in Builder.php line 1992:
Call to undefined method Illuminate\Database\Query\Builder::hasRole()

My user model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Model {
  use EntrustUserTrait;

   protected $table = 'users';
   public $timestamps = true;

   use SoftDeletes;

   protected $dates = ['deleted_at'];

}

UPDATE

I realized hasRole works for me when I look up the user this way (returns App\Models\User Object):

$user = \App\Models\User::find( \Auth::user()->id );

but NOT when I find the user this way (returns App\User Object ):

$user = \Auth::user();

I rather would have thought it would work the other way, when I pull up the App\User I'd have access to hasRole but not necessarily when I search for a user. I thought hasRole would work right from the Auth::user() without having to lookup the user with the user model...???

回答1:

Found the issue..

in config/auth.php I had

'model' => 'App\User',

My namespace requires

'model' => 'App\Models\User',


回答2:

Thanks for you update, it was a problem for me as well. And I used your advice and I put in my HomeController

public function index()
{
    $user = User::find( \Auth::user()->id );

    return view('home', compact('user'));
}

and then in my Home View

@if ($user->hasRole('Admin'))
    <li><a href="/users/create">Create User</a></li>
@endif
<li><a href="/users">User List</a></li>
<li><a href="">Create Client</a></li>
<li><a href="">Create Payment</a></li>

and everything works perfect...