Laravel Eloquent – relations method is returning HasMany object and property is returning Collection

  eloquent, laravel, oop, php, relational-database

I have a simple questions but I cant find any answer in internet.

class Product extends Model
    use HasFactory;

    public function variants()
        return $this->hasMany(Variant::class);

>>> $p->variants();
=> IlluminateDatabaseEloquentRelationsHasMany {#4331}
>>> $p->variants;
=> IlluminateDatabaseEloquentCollection {#4310
     all: [
       AppModelsVariant {#4319
         id: "1",
         name: "VariantOne",
         created_at: null,
         updated_at: null,
         quantity: "2",
         product_id: "1",

Why while I’m using method variants() I got empty HasMany object but when I use just a variants property, I got a Collection with properly data?

And how did variants property comes up to live? I don’t have it defined in my Product class.

Source: Laravel

Leave a Reply