2

I'm struggling to see why my select list is returning an error.

I have a nested foreach loop, the second loop which should display records by building_id. However it is this very id which it returns an undefined variable for ($building->id)

Is it the construction of the query which is at fault?

<select>
     @foreach (Building::orderBy('title')->get() as $building)
          <optgroup label="{{ $building->title }}"></optgroup>
           @foreach (Floor::whereIn('id', function($query){
                 $query->select('floor_id')
                   ->from('rooms')
                   ->where('building_id', $building->id)->distinct();
                   })->get() as $floor)
            <option value="{{ $floor->id }}">{{ $floor->description }}</option>
           @endforeach    
     @endforeach
</select>

2 Answers 2

2

You are using a closure function which you have passed to Floor::whereIn So this closure function can't recognize external variables like the variable / object ($building) that you wanted to use in it. so you have to tell PHP to use this $bulding variable in this closure / anonymous function:

<select>
     @foreach (Building::orderBy('title')->get() as $building)
          <optgroup label="{{ $building->title }}"></optgroup>
           @foreach (Floor::whereIn('id', function($query) use ($building){
                 $query->select('floor_id')
                   ->from('rooms')
                   ->where('building_id', $building->id)->distinct();
                   })->get() as $floor)
            <option value="{{ $floor->id }}">{{ $floor->description }}</option>
           @endforeach    
     @endforeach
</select>

So now the function can reconize this variable :) Read more about it : http://php.net/manual/en/functions.anonymous.php

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your informed answer. That's it working perfectly now.
2

Try it like this

  ....
  @foreach (Floor::whereIn('id', function($query) use ($building){
  ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.