biplob
biplob

Reputation: 1272

Query structure in laravel 5 for getting nested array result

I’m trying to make a dynamic resume. To show the skills I’ve created 3 tables as follows-

  1. Skills - Contains all skill with expertise level
  2. Groups - Contains category like front end, back end, database, programming etc
  3. Skill_Groups - As one skill can be in multiple groups, I made this table. For example- PHP can be back end group also in programming group.

Skills

enter image description here

Groups

enter image description here

Skill_Groups

enter image description here

Now, I would like to display the groups and skills with nested list. Example-

For this, I need a multidimensional array. What should be the query in laravel to get the result on this way?

[This question may be duplicate one, but I didn’t found. If so, please let me know, I will merge/delete it.]

Any alternate solutions also appreciable, if have.

Upvotes: 2

Views: 906

Answers (1)

aleksejjj
aleksejjj

Reputation: 1835

In Model Group you can add relationship

public function skills()
{
    return $this->belongsToMany(Skill::class, 'skill_groups');
}

In Controller

$groups = Group::with('skills')->get();

In View

@foreach($groups as $group)
    {{ $group->name }}

    @foreach($group->skills as $skill)
        {{ $skill->name }}
    @endforeach
@endforeach

Upvotes: 2

Related Questions