alanmanderson
alanmanderson

Reputation: 8230

Laravel Accessing One To Many polymorphic objects

I have this table:

user_permissions
----------------
id
user_id
permissable_id
permissable_type

permissable_type can be anything. This is how I am controlling permissions on certain abilities. One of the possible permissable_types is App\Models\Product. If a user can only use 2 of the 5 products, there will be 2 rows in the user_permissions table. What is the best way to get those 2 permissions?
I have return $this->hasMany('UserPermission'); This gets me 2 userPermission objects, but I want to get a collection of Products not UserPermissions. What is the best way to do this?

I am on Laravel 5.0

Upvotes: 0

Views: 232

Answers (1)

patricus
patricus

Reputation: 62368

Your user_permissions table is setup like a polymorphic relationship. The fields are already named correctly and everything. If you have this relationship setup, this should be pretty easy.

It sounds like you are looking for a set of products for a specific user. Phrasing it this way kind of gets you to the code you would need:

// "I want Products that have a specific user"
$products = \App\Models\Product::whereHas('permissions.user', function($q) use ($user) {
    $q->where('id', $user->id);
});

If your relationships are not already set up, this is an idea of what they'd look like:

class UserPermission {
    public function user() {
        return $this->belongsTo(User::class);
    }

    public function permissable() {
        return $this->morphTo();
    }
}

class Product {
    public function permissions() {
        return $this->morphMany(UserPermission::class, 'permissable');
    }
}

Upvotes: 1

Related Questions