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

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

I tried to attach permission if not present and got error -

<?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', 'a@gmail.com')->first();
        if(!$adminUser->hasRole('admin')) {
            $adminUser->attachRole($admin);
        }

        $moderatorUser = User::where('email', 'b@gmail.com')->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);
        }
    }
}

I take a look on EntrustUserTrait and method is not there. It’s in EntrustRoleTrait. Do i need to use that as well with EntrustUserTrait? is that case there will be collision.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 16

Most upvoted comments

@jonjie0317 try this to be sure it isn’t failing because of an invalid admin variable:

         $admin = Role::where('name', 'admin');
         $createPermission = Permission::where('name', 'create-post');
         dd ($admin,  $createPermission);

OR better yet, use xdebug instead of dd ()

HTH, Bud

@jonjie0317 No problem. BTW, you probably should have started a new thread instead of adding on to a closed one.

HTH, Bud

@manzwebdesigns Wow! it worked. I just checked the data first using dd() and changing my code from:

$admin = Role::where('name', 'admin');
$createPermission = Permission::where('name', 'create-post');
$admin->attachPermission($createPermission);
dd('Success.');

to this:

$admin = Role::where('name', 'admin')->first();
$createPermission = Permission::where('name', 'create-post')->first();
$admin->attachPermission($createPermission);
dd('Success.');

Thanks men 😃