Jamie
Jamie

Reputation: 10896

Laravel morph belongs to?

I've got a situation where multiple tables have a belongsTo relationship to a category table in laravel 5.4.

So I thought about this structure:

User table:

id
name
email
category_id   <--

Category table

id
model_type
name

Is this possible with a morph relationship?

Upvotes: 0

Views: 4217

Answers (1)

Eric Tucker
Eric Tucker

Reputation: 6345

This would not be since model_type is just a constraint of which categories are available for which models. If you set it up like that you would add that constraint on each model's relation like:

class User extends Model
{
    // User class

    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

Or since you have many models that belong to Category you could take that one step further and use a trait for the relation and place the trait on each model that belongs to Category:

trait BelongsToCategory()
{
    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

class User extends Model
{
    use BelongsToCategory;

    // User class
}

Upvotes: 3

Related Questions