user3384514
user3384514

Reputation: 297

Laravel and nested foreach of database query error

I am building a menu on laravel.

In blade layout i have:

@foreach ($menu1 as $menu1)
{{$menu1->nome}}

            <div class="panel-group" id="accordion">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">

                            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                                <span class="glyphicon glyphicon-chevron-down"></span>

                            </a>
                        </h4>
                    </div>            
                    <div id="collapseOne" class="panel-collapse collapse in">
                        <div class="panel-body">
                            <ul class="list-unstyled">
                    @foreach ($menu2 as $menu2)
                                <li> <a href="./"> {{$menu2->nome}} </a> </li>
                    @endforeach
                            </ul>
                        </div>
                    </div>
                </div>
 @endforeach

in my controller i pass 2 query.

public function menu($lingua)

{
    return View::make('index', ['menu1'=>DB::table('cat_nome')->join('lingua', 'cat_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(array('cat_nome.nome')),
                                'menu2' => DB::table('campo_nome')->join('lingua', 'campo_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(array('campo_nome.nome'))]
        );
}

I tried to UNnest the foreach and everything works fine. When i try to nest the foreach i get

Trying to get property of non-object

Upvotes: 0

Views: 196

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

@foreach ($menu2 as $menu2)

That line is most likely the culprit. You cannot use the same variable name twice in a foreach loop like that and expect good results. The second one is supposed to be what each entry in $menu2 will be scoped to during each iteration of the loop.

See the foreach documentation

Try changing the loop to look more like this:

@foreach ($menu2 as $innerMenu)
    <li> <a href="./"> {{$innerMenu->nome}} </a> </li>
 @endforeach

I would suggest doing the same thing for your outer menu as well.

Upvotes: 1

Related Questions