spatie / laravel-permission

Associate users with roles and permissions
https://spatie.be/docs/laravel-permission
MIT License
12.18k stars 1.78k forks source link

Unable to get all users with a given permission (BadMethodCallException) #741

Closed bilfeldt closed 6 years ago

bilfeldt commented 6 years ago

I am trying to get all users that has the permission edit articles or a role which inherits this permission using:

App\User::permission('edit articles')->get();

then I get the error:

BadMethodCallException with message 'Method Illuminate/Database/Query/Builder::permission does not exist.'

If I instead search for users with a given role, then this works just fine, and a collection is returned:

App\User::role('super-admin')->get();

Am I missing a trait or why is the permission function not working? According to the documentation, then I have included the trait:

<?php

namespace App;

use Backpack\CRUD\CrudTrait;
use Spatie\Permission\Traits\HasRoles;
use Laravel\Spark\User as SparkUser;

class User extends SparkUser
{
    use CrudTrait;
    use HasRoles;
drbyte commented 6 years ago

I wonder if you have a clash of dependencies?

This demo app built on the principles in the readme doesn't give that error ... but it doesn't have those other packages installed either: https://github.com/drbyte/spatie-permissions-demo/ Here's fresh output from that app, for App\User::permission('edit articles')->get();:

$ cd permissions-demo

$ php artisan migrate:fresh --seed
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2017_09_10_183759_create_permission_tables
Migrated:  2017_09_10_183759_create_permission_tables
Migrating: 2017_12_18_214801_create_posts_table
Migrated:  2017_12_18_214801_create_posts_table
Seeding: PermissionsDemoSeeder

$ php artisan tinker
Psy Shell v0.9.3 (PHP 7.2.5 — cli) by Justin Hileman
>>> App\User::permission('edit articles')->get();
=> Illuminate\Database\Eloquent\Collection {#2360
     all: [
       App\User {#2371
         id: 1,
         name: "Example User",
         email: "test@example.com",
         created_at: "2018-05-18 12:47:48",
         updated_at: "2018-05-18 12:47:48",
       },
     ],
   }
bilfeldt commented 6 years ago

@drbyte Thank you for a detailed explanation. I apologise for this. The issue was caused by the fact that we used an older version of the package, where this functionality was not yet implemented.