How to display different categories lists on the same page using Laravel 5.3

Asked

Viewed 63 times

0

Good morning, I’m using Laravel 5.3, and I need to put together a page with a list of categories, and each category is a dropdown that should present the link to the products of these categories, example of how it should look:

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 the categories are presenting all the products, this getting 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

So far 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 thus:

$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);
  • post the layout of the tables, post the code you made so far!

1 answer

0

You will probably use the GroupBy to solve this. I’m not talking about the GroupBy Eloquent Query Builder, and yes Collection (the outcome of its consultation).

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.