Domanda

I have this table structure

users

  • id
  • email
  • roles

role

  • id
  • role

role_user

  • id
  • role_id
  • user_id

And I added a function in the User model which will check for Authenticated user's role. But I get it returns this error:

Undefined variable: role

//User.php
public function hasRole($role = null)
{
    $hasRole = false;
    $hasRole = !$this->roles->filter(function($item) {
        return $item->role == $role;
    })->isEmpty();
    return $hasRole;
}

So I can use into something like this - maybe inside a filter

if(Auth::user()->hasRole('encoder')) {
    //...
}
È stato utile?

Soluzione

In PHP, By default, a function has no access to the variables declared outside of the function.

This variable can not be accessed from that closure

public function hasRole($role = null)
{
    $hasRole = false;
    $hasRole = !$this->roles->filter(function($item) {
        return $item->role == $role;
    })->isEmpty();            ^^^^^
    return $hasRole;
}

You can use the use keyword, which passes one variable to a function:

public function hasRole($role = null)
{
    $hasRole = false;
    $hasRole = !$this->roles->filter(function($item) use($role) {
        return $item->role == $role;
    })->isEmpty();
    return $hasRole;
}

They is more info about this particular problem on this blog post

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top