0
votes

I have two tables with a many to many relation. Groups and Members table with a pivot table group_member. The relations are well done and have seeded the tables including the pivot table. Now what i want to do is, when i select a group in the drop down, the list of members in that particular group should show up in a different drop box.

Controller

//displays the form
public function create()
    {
        $groups = Group::all()->where('user_id',Auth::user()->id);
        $members = Member::with('groups')->get();
        $selectedGroup = $groups->pluck('id')->toArray();
        return view('group.show',compact('groups','selectedGroup','members'));
    }

Now my code shows the groups alright but it doesn't fetch only the members belonging to that group but all members belonging to the user. How can i dynamically do this; Select a group and display its members at the same time. Thank you

1
What do you mean by "but all members belonging to the user"? A member can belong to a user? It's not really clear what you are trying to achieve. - Camilo
Please show the models relationships and the relevant portion of the group.show view. - Camilo

1 Answers

0
votes

To get the members of a selected group in the dropdown dynamically, you'll have to use ajax to fetch the data and populate the select element.

considering your select element as

<select id="group_id" name="group_id">
    @foreach($groups as $group)
    <option value="{{ $group->id }}">{{ $group->name }}</option>
    @endforeach
</select>

you'll have to write javascript/jQuery to listen to change in the select value

$('#group_id').change(function() {
    $.get('/group/'+this.value, function(data){
        // Code to populate the secondary select element
    });
});

You need a route which gives out group members as json to feed the select element.