Question: I created a site by laravel and I want to show categories and relevant products names.

I have an array and like this

```
$category  = [
    '1' => 'cat1',
    '2' => 'cat2'
];

$product = [
    '0' => array(
     'name' => 'product1',
     'category_id' => '2'
),
    '1' => array(
     'name' => 'product2',
     'category_id' => '2'
),
    '2' => array(
     'name' => 'product3',
     'category_id' => '2'
),
    '3' => array(
     'name' => 'product4',
     'category_id' => '1'
),
    '4' => array(
     'name' => 'product5',
     'category_id' => '1'
),
    '5' => array(
     'name' => 'product6',
     'category_id' => '2'
)]; 

```

and I want to showing it like this

```
<h3>cat1</h3>
<p>product4</p>
<p>product5</p> 
<hr>
<hr> 
<h3>cat2</h3>
<p>product1</p>
<p>product2</p>
<p>product3</p>
<p>product6</p> 

```

You have to know I'm using laravel and I want doing this job with laravel but you also can coding with PHP, I think I can to convert it in laravel

Answer: 
You can make use of Laravel collections' [groupBy](https://laravel.com/docs/5.8/collections#method-groupby) for your use case.

In your controller file, group by `category_id` key and render them in your blade by looping.

**Controller Snippet:**

```
public function someMethod(){
    $category  = [
        '1' => 'cat1',
        '2' => 'cat2'
    ];

    $product = [
        '0' => array(
         'name' => 'product1',
         'category_id' => '2'
    ),
        '1' => array(
         'name' => 'product2',
         'category_id' => '2'
    ),
        '2' => array(
         'name' => 'product3',
         'category_id' => '2'
    ),
        '3' => array(
         'name' => 'product4',
         'category_id' => '1'
    ),
        '4' => array(
         'name' => 'product5',
         'category_id' => '1'
    ),
        '5' => array(
         'name' => 'product6',
         'category_id' => '2'
    )]; 

    $category_collection = collect($product)->groupBy('category_id')->toArray();

    return view('your_blade_name',compact('category_collection','category'));
}

```

**Blade Snippet:**

```
@foreach($category_collection as $category_id => $data)
    <h3>{{ $category[$category_id] }}</h3>
    @foreach($data as $current_data)
        <p>{{ $current_data['name'] }}</p>
    @endforeach
<hr>
<hr> 
@endforeach

```
try

```
@foreach($category as $key => $cat)
  <h3>{{$cat}}</h3>
@foreach($product as $pr)
    @if($pr['category_id'] == $key)
        <p>{{$pr['name']}}</p><br>
    @endif
@endforeach
 <br>
@endforeach

```