How to present different lists of categories in a same page using Laravel 5.3

0

Good morning, I'm using Laravel 5.3, and I need to set up a page with a list of categories, and each category is a dropdown that should present the link to the products of those categories,

  

Category 1

  • Product 1A
  • Product 1B
  

Category 2

  • Product 2A
  • Product 2B
  

Category 3

  • Product 3A
  • Product 3B

All this is information coming from the bank, the problem is that all categories are showing all products, it looks like this:

  

Category 1

  • Product 1A
  • Product 1B
  • Product 2A
  • Product 2B
  • Product 3A
  • Product 3B
  

Category 2

  • Product 1A
  • Product 1B
  • Product 2A
  • Product 2B
  • Product 3A
  • Product 3B
  

Category 3

  • Product 1A
  • Product 1B
  • Product 2A
  • Product 2B
  • Product 3A
  • Product 3B

For now the view looks like this:

 @foreach($categorias as $key => $value)
    <li class="dropdown">
      <a href="#" class="dropdown-toggle btn btn-primary" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{$value->nome}}</a>
      <ul class="dropdown-menu dropdown-produto" aria-labelledby="dropdownMenu3">
          @foreach($produtos as $key => $value)
            <li class=""><a href="{{url('produtos/'.$value->url.'/')}}" class="btn btn-primary">{{$value->nome}}</a></li>
          @endforeach
       </ul>
    </li>
@endforeach

And the controller like this:

$data['categorias'] = Categorias::All();

$data['categorias'] = (
    Categorias::where('nome', 'like', "%%")
    ->orderBy('nome', 'asc')
    ->paginate(10)
);

$data['produtos'] = Produtos::All();

$data['produtos'] = (
     Produtos::where('nome', 'like', '%%')
      ->where('hidden', 'like', 0)
      ->orderBy('created_at', 'desc')
      ->paginate(10)
);        


return view('front/produtos/index', $data);
    
asked by anonymous 02.12.2016 / 14:06

1 answer

0

You'll probably use GroupBy to solve this. I'm not talking about GroupBy of Eloquent Query Builder, but about Collection (the result of your query).

Example:

$produtos = Produto::get(); // já pegou o resultado

$grupoProdutos = $produtos->groupBy(function ($produto) {
     // pega a penúltima letra e agrupa por elas
     return substr($produto->nome, -2, 1); 
});

In the view you can do:

@foreach($grupoProdutos as $produtos)
    <select>
    @foreach($produtos as $produto)
        <!-- <option></option> -->
    @endforeach
    </select>
@endforeach
    
02.12.2016 / 14:39