Vit Kos
Vit Kos

Reputation: 5755

How to get related collection in model in Laravel4

Suppose I have a model called User where several relations are defined (role and permissions). How can I get directly in my User model related role collection or related permissions collection ?

What I am trying to do :

controller:

if (Auth::user()->hasPermission('test'))
{ // code goes here}

and my model:

public function hasPermission($name)
    {
        $permission = \Permission::where('name', '=', $name)->get();
        $list = ($this->overwrite_permission) ? $this->permissions : $this->role->permissions;
//here I want to have a collection to use contains()
        if ($list->contains($permission))
        {
            return true;
        }
        return false;
    }

Upvotes: 1

Views: 91

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

You can do this instead of checking collection:

public function hasPermission($name)
{
    return ($this->overwrite_permission)
       ? (bool) $this->permissions()->whereName($name)->first()
       : (bool) $this->role->permissions()->whereName($name)->first();
}

First() will fetch the permission model if it's in the related permissions (to the user or the role appropriately) or return null, thus casting to boolean will do the job.

If you want to use your code anyway, this is the line to change:

// it returns Collection, while you need Model (or its id) for contains() method
$permission = \Permission::where('name', '=', $name)->get();

// change to:
$permission = \Permission::where('name', '=', $name)->first();

Rest of the code is ok, $list is indeed a Collection (unless you have not setup relations to permissions correctly)

Upvotes: 2

Related Questions