I know this is already an overly discussed problem, but I believe I'm not making the mistake commonly made. I'm getting this error when using the Entrust package for Laravel to create roles and permissions. I'm trying to attach permissions to roles (note, not directly to models) and got this error. Here's some of the code:
use Illuminate\Database\Seeder;
use App\Role;
use App\Permission;
class RolePermissionSeeder extends Seeder
{
//assign permissions to roles
public function run()
{
//assign permissions to admin
$admin = Role::where('name', 'admin');
$assignTrainerRole = Permission::where('name', 'assign-trainer-role');
$removeTrainerRole = Permission::where('name', 'remove-trainer-role');
$assignTraineeRole = Permission::where('name', 'assign-trainee-role');
$removeTraineeRole = Permission::where('name', 'remove-trainee-role');
$attachToTrainer = Permission::where('name', 'attach-to-trainer');
$detachFromTrainer = Permission::where('name', 'detach-from-trainer');
$admin->attachPermissions(
[
$assignTrainerRole,
$removeTrainerRole,
$assignTraineeRole,
$removeTraineeRole,
$attachToTrainer,
$detachFromTrainer,
]
);
// snipped
Now, from what I found, generally this error arises when people try to set permissions directly on User or some other model. But I'm not doing that. I'm trying to assign permissions to roles, and still getting this error. Can someone help?
You're not fetching the permission models properly. You need to call the first
method like so:
$detachFromTrainer = Permission::where('name', 'detach-from-trainer')->first();
Also, you can optimize the SQL queries using the wherein clause instead of calling multiple queries like so:
$permissions = Permission::whereIn('name', ['name1', 'name2' ...])->get();