Type error: Argument 1 passed to: hasPermission () must be an instance of: Permission string given

0

I'm stuck in an error here in Laravel and I do not understand why it's occurring, the message itself I understood, that I'm passing as a parameter to the function a value that is string when it should be an instance of my model, but before it worked and I did not understand why this error is occurring now, it follows the files:

AuthServiceProvider.php

public function boot()
{
    $this->registerPolicies();

    $permissions = Permission::with('roles')->get();

    foreach ($permissions as $permission) {
        Gate::define($permission->name, function($user) use ($permission) {
            return $user->hasPermission($permission->name);
        });
    }
}

The model: User.php

/**
 * @param \Api\Users\Models\Permission $permission
 *
 * @return bool
 */
public function hasPermission(Permission $permission)
{
    return $this->hasAnyRoles($permission->roles);
}

/**
 * @param $roles
 *
 * @return bool
 */
public function hasAnyRoles($roles)
{
    if(is_array($roles) || is_object($roles) ) {
        return !! $roles->intersect($this->roles)->count();
    }

    return $this->roles->contains('name', $roles);
}

Here is the error that occurs:

  

"Type error: Argument 1 passed to Api \ Users \ Models \ User :: hasPermission () must be an instance of Api \ Acl \ Models \ Permission, string given, called in C: \ wamp \ www \ restfulapi_test \ infrastructure \ Providers \ AuthServiceProvider.php on line 34 "

    
asked by anonymous 20.02.2018 / 15:51

1 answer

0

The hasAnyRoles wait on the first argument must be an object of type Api\Acl\Models\Permission , in case you passed $permission->roles which probably contains another type of object or value:

public function hasPermission(Permission $permission)
{
    return $this->hasAnyRoles($permission->roles);
}

So the error message:

  

Argument 1 passed to Api \ Users \ Models \ User :: hasPermission () must be an instance of Api \ Acl \ Models \ Permission

Translated would be:

  The first argument passed to Api \ Users \ Models \ User :: hasPermission () must be an instance of Api \ Acl \ Models \ Permission

As in hasPermission(Permission $permission) you already receive the object so you probably have to do this:

public function hasPermission(Permission $permission)
{
    return $this->hasAnyRoles($permission);
}
    
20.02.2018 / 20:34