Vinícius
Vinícius

Reputation: 483

How to use two foreachs in laravel?

I have a category table, it is organized by 'parent_id' and 'categoryid'. I need to organize it in a list, where I group the parent class with the daughter class.

I created this code.

In the controller I get the value of the categories.

public function index()
    {
      $cat1 = Category::where('erp_parentid', '=', 0)->get();
      foreach($cat1 as $categoria1){
        $cat2 = Category::where('erp_parentid', '=', $categoria1->erp_categoryid)->get();
        return view('admin.categories')->with('cat1', $cat1)->with('cat2', $cat2);
      }
    }

$cat2 is the child category, I get its values through the categoryid of the parent category.

But when I pass the values to the view, all parent categories take the same value as the first.

enter image description here I used that code to display the values in the view:

<div class="container">
  <div class="row">
    <ul class="list-group">
      @foreach($cat1 as $value)
      <a data-toggle="collapse" data-target="#catfilha{{$value->erp_categoryid}}"><li class="list-group-item">{{$value->erp_name}}</li></a>
      <ul id="catfilha{{$value->erp_categoryid}}" class="collapse">
        @foreach($cat2 as $value2)
        <li>{{$value2->erp_name}}</li>
        @endforeach
      </ul>
      @endforeach
    </ul>
  </div>
</div>

I searched for similar cases here on the site, but found no resemblance, any suggestions? Thank you in advance.

Upvotes: 1

Views: 62

Answers (1)

Laerte
Laerte

Reputation: 7083

You should define the relations in the model and call them in the view. Try something like this:

In Category Model:

public function getParent()
{
    return self::where('erp_parentid', '=', $this->erp_categoryid)->get();
}

In Controller:

public function index()
{
    $cat1 = Category::where('erp_parentid', '=', 0)->get();
    return view('admin.categories')->with('cat1', $cat1);
}

In the View:

<div class="container">
  <div class="row">
    <ul class="list-group">
      @foreach($cat1 as $value)
      <a data-toggle="collapse" data-target="#catfilha{{$value->erp_categoryid}}"><li class="list-group-item">{{$value->erp_name}}</li></a>
      <ul id="catfilha{{$value->erp_categoryid}}" class="collapse">
        @foreach($value->getParent() as $value2)
        <li>{{$value2->erp_name}}</li>
        @endforeach
      </ul>
      @endforeach
    </ul>
  </div>
</div>

In your code, the return statement is inside the loop, so cat2 will be always the categories from the first item of cat1.

Upvotes: 2

Related Questions