0

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?

2
  • What does the error says Commented Mar 27, 2017 at 18:01
  • Exactly what the title of this post says: Call to undefined method Illuminate\Database\Query\Builder::attachPermissions() :-) Commented Mar 27, 2017 at 18:02

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Nice! Thank you. Earlier you had written get() and with that I was still getting the error. Can you point me to the link in the docs where the difference between get() and first() is explained?
get returns an Eloquent collection of models whereas first returns the first model or row of the query
So get()[0] would've worked as well? Not considering efficiency, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.