Neha
Neha

Reputation: 2261

How to get array of nested relations into single Array in Laravel

Item Model:

public function item_makes(){
     return $this->hasMany(ItemMake::class,'item_id','id');
}

In ItemMake Model :

public function make(){
    return $this->belongsTo(Make::class,'make_id','id');
}

I need to get array of all make based on item_id. How to achieve this? Thanks in Advance.

Upvotes: 1

Views: 809

Answers (3)

Neha
Neha

Reputation: 2261

This worked for me.

$item = Item::findOrFail(1)
         ->item_makes()
         ->with('make')
         ->get()
         ->pluck('make')
         ->flatten()
         ->toArray();

Upvotes: 2

sid heart
sid heart

Reputation: 1149

Try wherehas method something like this

$makes = Make::whereHas('item_makes', function ($query) use($item_id) {
   $query->where('item_id',  $item_id);
})->get();

Upvotes: 1

piscator
piscator

Reputation: 8709

Try something like this:

Item::findOrFail(1)
    ->with('item_makes.make')
    ->get()
    ->pluck('make')
    ->flatten()
    ->toArray()

Upvotes: 1

Related Questions