Search code examples
phpmysqllaraveleloquenteager-loading

Eager loading inside appending property in model


I want to append category_id into seat collection, but I need to fill it using eager loading or relation.

where am I doing wrong?

Seat Model:

class Seat extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $appends = ['category_id'];

    protected $fillable = [
        'seat_name',
        'seat_url',
        'logo_src',
    ];

    public function getCategoryIdAttribute()
    {
        return $this->hasMany(AdSeatCategories::class);
    }

}

when I run Seat::all();, I get {} for category_id in response. response example:

{
"id": 95,
"seat_name": "gtest",
"seat_url": "http://ooop.com",
"logo_src": null,
"category_id": {},
},

Solution

  • It looks like your getCategoryIdAttribute() is returning a relation, when you instead want it to return the collection so be sure to call get() like this:

    public function getCategoryIdAttribute()
    {
        return $this->hasMany(AdSeatCategories::class)->get();
    }
    

    Alternatively, perhaps instead you want a relation and an attribute:

    public function categories()
    {
        return $this->hasMany(AdSeatCategories::class);
    }
    
    public function getCategoryIdsAttribute()
    {
        return $this->categories()->get()->pluck('id');
    }