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

Asked

Viewed 308 times

0

I am stuck in an error here in Laravel and I don’t understand why it is occurring, the message itself I understood, that I am passing as parameter to the function a value that is string when it should be an instance of my model, but before it worked and 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);
        });
    }
}

A 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);
}

this 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"

  • 1

    Just try changing the $permission->name for the $permission object.

  • Should be $this->hasAnyRoles($permission); the correct, is not?

  • I’m not sure, but I’ll take the test

  • @arllondias was just like that!

1 answer

0


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

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

Hence 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() needs to be an instance of Api Acl Models Permission

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.