How to get the first object with morphToMany relation?

Viewed 992

I have a polymorphic relation on my Item Table

public function categories(): MorphToMany
{
    return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')
        ->withTimestamps();
}

It works. I get a list of objects as expected. Only, some models in my database will always have only one category.

I’d like to avoid getting a list of items. I would like the object directly.

I tried that, but it doesn't work :

public function category()
{
    return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')->first;
}

Call to undefined method App\Models\Category::addEagerConstraints()

I have a result like that :

{
  'id': 1,
  'name': 'My name',
  'categories': [
    {my object category}
   ]
}

I want :

{
  'id': 1,
  'name': 'My name',
  'category': 
    {my object category}
}

How can I do this? It's a many to many polymorphic relationship.

1 Answers

morphToMany is similar to HasMany() which always returns an array.

You can use Eloquent Accessor to get the categories and manipulate the data.

protected $appends = ['category_data'];

public function getCategoryDataAttribute()
{       
    return $this->categories->first();
} 
Related