0
votes

I tried to attach permission if not present and got error after run db seed -

<?php

use Illuminate\Database\Seeder;
use App\Role;
use App\Permission;
use App\User;

class AttachRolesAndPermissionsToUsers extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $admin = Role::where('name', 'admin')->first();
        $moderator = Role::where('name', 'moderator')->first();

        $createPost = Permission::where('name', 'create-post')->first();
        $editUser = Permission::where('name', 'edit-user')->first();


        // attach role
        $adminUser = User::where('email', '[email protected]')->first();
        if(!$adminUser->hasRole('admin')) {
            $adminUser->attachRole($admin);
        }

        $moderatorUser = User::where('email', '[email protected]')->first();
        if(!$moderatorUser->hasRole('moderator')) {
            $moderatorUser->attachRole($moderator);
        }

        // attach Permission
        if(!$adminUser->can(['create-post', 'edit-user'])) {
            $adminUser->attachPermissions([$createPost, $editUser]);
        }

        if(!$moderatorUser->can('create-post')) {
            $moderatorUser->attachPermission($createPost);
        }
    }
}

[BadMethodCallException] Call to undefined method Illuminate\Database\Query\Builder::attachPermission()

2
check in your User model that attachPermission() method is exist. - SarangaR
No it's not, attachPermission shouldn't suppose to be in user model, it should come along with entrust package. Like I am using can, hasRole method without having them on user model - HADI
I guess i am doing a wrong that is i should attach permission to role not with user. - HADI

2 Answers

0
votes

Change it to

$adminUser->perms()->sync([$createPost->id, $editUser->id]);

and let see how it goes.

0
votes

It was wrong implementation, permission need to be attach with Role not with user.

$admin->attachPermissions([$createPost, $editUser]);
$moderator->attachPermission($createPost);

Where $admin and $moderator is role object.