Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel pluck an array from nested relationship

Tags:

laravel

I need to get only the roomnumber arrays returned from the following query:

$roomnumbers = Room::with(['floorroomcount' => function($query){
                $query->with('roomnumber')->get();
        }])->where('roomtype_id', $roomtype_id)->get();

Tried: The follow pluck is returning floorroomcount

$roomnumbers->pluck('floorroomcount');

but i need roomnumber array, how can i get?

like image 805
arun Avatar asked May 09 '18 08:05

arun


2 Answers

This gives you all roomnumber results in one collection:

$roomnumbers->pluck('floorroomcount')->collapse()->pluck('roomnumber')->collapse();
like image 94
Jonas Staudenmeir Avatar answered Oct 15 '22 16:10

Jonas Staudenmeir


You may shorten @Jonas Staudenmeir's answer like so:

$roomnumbers->pluck('floorroomcount.*.roomnumber.*')->collapse();

pluck('*') is essentially the same as collapse() in this particular context.

like image 25
Steen Schütt Avatar answered Oct 15 '22 16:10

Steen Schütt