laravel-permission: BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::givePermissionTo()'

After successfully assigning users to role, I tried calling the givePermissionTo() method to give my roles permission and I get the above error. I added the HasRole trait to my users model as it says in the README. However I’m not quite sure where to put use Spatie\Permission\Models\Role; and use Spatie\Permission\Models\Permission;Could this be the cause of the error? Thanks

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 15 (3 by maintainers)

Most upvoted comments

When adding the HasRole trait to the User model, the givePermissionTo() isn’t part of the Eloquent query-builder chain.

This works:

$user = User::find(4); // returns an instance of \App\User
$user->givePermissionTo('edit posts');
//or
$user->assignRole('moderator');

but this does not:

$user = User::where('email', 'tom@example.com')->get(); // returns an Eloquent Collection
$user->givePermissionTo('foo');
// or
$user->assignRole('bar');

In the example above you could change get() to first() to make it work:

$user = User::where('email', 'tom@example.com')->first(); //returns instance of User (if a record was found)

Assign Role worked for me with tinker like this:

\App\Models\User::first()->assignRole('administrator');

I have the same error but with “assingRole” using “tinker”, I have tried everything. My “user” model has “HasRoles”, can create roles without problems, but when I assign it to a user, it gives me the same error. I am about to shoot me in the head.