I am Try to get User List with their role in laravel 8, for role and permission i am use spatie package (https://spatie.be/docs/laravel-permission/v4/)

i am trying to get any data via user it return error

following function return error

$all_users_with_all_their_roles = User::with('roles')->get(); 
$all_users_with_all_direct_permissions = User::with('permissions')->get(); 
$user->hasAllRoles(Role::all());

function (https://spatie.be/docs/laravel-permission/v3/basic-usage/basic-usage#eloquent)

ERROR : "Call to undefined method App\Models\User::getAllPermissions()",…}

I think something missing in user model.

please help to solve this issue

TIA

2

There are 2 best solutions below

0
On BEST ANSWER

I think you forgot to add the trait to the User class:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable {
    use HasRoles;

    // ...
}

If you have not forgotten the trait, then use the below code to get all users roles and permissions.

$users = User::all();
$user_roles = [];
$user_permissions = [];
if($users) {
    foreach ($users AS $user) {
        $user_roles[$user->id] = $user->getRoleNames();
        $user_permissions[$user->id] = $user->getAllPermissions();
    }
}

FMI SEE: https://spatie.be/docs/laravel-permission/v3/basic-usage/basic-usage

0
On

Notice:

Result of User::all() and User::where(..)->get() is an instance of laravel eloquent collection, not an instance of User model.

Solution:

Use first() on your collection or loop over it.

$all_users_with_all_their_roles = User::with('roles')->get(); 
$all_users_with_all_direct_permissions = User::with('permissions')->get();

// Use for example first() to get the first user instance from collection 
$user->first()->hasAllRoles(Role::all());

// Or loop over it
foreach($all_users_with_all_direct_permissions as $user){
    $user->hasAllRoles(Role::all());
}