May Sale! All accounts are 40% off this week.

darknesseyes's avatar

fetch associative array from pivot table and pass it to view ?

Hi everyone, I'm really stuck

I have two tables

groups id title

subjects id title

group_subject group_id subject_id

how can I fetch associative array , pass it to view and iterate to make

menu with submenu

group 1 -math -art

group 2 -chemistry -physics

0 likes
3 replies
FourStacks's avatar
Level 3

Hi @darknesseyes

I'm assuming you have models for your Group and Subject tables with a belongsToMany relationship defined for each model (e.g. in the Group model you'd have a method called subjects and in your Subject model you'll have a groups method)? If so you'll probably want to do something like this in your controller:

public function myControllerMethod(){
    $groups = App\Group::with('subjects')->get();
    return view('my.view', compact($groups));
}

Then in your view you can iterate over your groups using blade syntax like so:

@if( ! $group->isEmpty() )
<ul>
@foreach($groups as $group)
    <li>{{ $group->title }}
        @if( ! $group->subjects->isEmpty() )
        <ul>
            @foreach($group->subjects as $subject)
                <li>{{ $subject->title }}</li>
            @endforeach 
        </ul>
        @endif 
    </li>
@endforeach 
</ul>
@endif 

Think that should have you covered - it's a bit proto-code but you should hopefully get the gist. Shout if anything is unclear.

Edit - sorry, should probably mention that you'd be dealing with eloquent collections in the example above though you can easily convert to plain arrays using the all() collection method: http://laravel.com/docs/5.1/collections#method-all

Please or to participate in this conversation.