user3189734
user3189734

Reputation: 665

Laravel foreach giving undefined error

In my laravel view, I have a select list built up of 3 foreachs. I appreciate that the query in the 2nd foreach isn't best practice but I'm unaware of how best to construct this.

My issue at the moment is largely that I am getting an undefined error referring to building, in the 2nd foreach.

Can anyone help?

@foreach($buildings as $building)
   <optgroup label="{{ Str::upper($building->title) }}"></optgroup>
    @foreach (DB::select('select id, description from `floors` where `id` in (select distinct `floor_id` from `rooms` where `building_id` = $building->id)') as $floor)
       <optgroup label="{{ $floor->description }}"></optgroup>
          @foreach (Room::where('active',1)->where('floor_id', $floor->id)->where('building_id', $building->id)->orderBy('name')->get() as $room)
          <option value="{{ $room->id }}"> - {{ $room->fulltitle }}</option>
          @endforeach
    @endforeach
@endforeach

Upvotes: 0

Views: 103

Answers (1)

Marc B
Marc B

Reputation: 360672

You're using '-quoted strings. They do NOT interpolate variables.

$foo = 'bar';

echo '$foo'; // outputs $, f, o, o
echo "$foo"; // outputs b, a ,r

This means you're sending a literal $, b, u, etc... to the database, which will be an unknown/illegal field name.

So you should have:

@foreach (DB::select("select [...snip...] = $building->id)") as $floor)
                     ^------------------------------------^

Upvotes: 1

Related Questions