Tuesday, March 21, 2017

Laravel: return multiple relationships

I have the following table:

enter image description here

The table is called user_eggs and it stores the user eggs. eggs are items with additional data (hatch_time)

As you can see, user 2 has 2 eggs, which are items 46 and 47.

My items table stores the item general information such as name, image, description, etc...

How I can return the user eggs using $user->eggs() including the item data in my items table of the egg item_id?

I tried:

User Model:

/**
     * Get the eggs
     */
    public function eggs()
    {
        return $this->belongsToMany(Egg::Class, 'user_eggs','user_id','item_id')
        ->withPivot('id','hatch_time');
    }

but $user->eggs() returns an empty array.

Any ideas?



via TheUnreal

Advertisement