Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MahmoudMonem's avatar

How to show only Unique values from a foreach loop

hello guys, I have 3 tables Products - Stocks - Colors

Relationships are as follows :

1- Products belongs to many stocks and vice versa with a pivot table [ Product-Stock ] 
2- Stock belongs to color
3- Color has many stocks

to access the data in show.blade.php

 @foreach($product->stocks as $stock)
<option value="{{$stock->color->color_name}}">{{$stock->color->color_name}}</option>
@endforeach

Product.php

    public function getRouteKeyName(){
        return 'slug';
    }

ProductsController.php

    public function show(Product $product)
    {
        return view('products.show', ['product' => $product]);
    }

It works fine, but the loop shows all the colors which shows multiple lines for the same color if the product has many stocks that has the same color. How can I get only unique values from the loop .. so that I avoid having the color repeated. I know that there is a Unique or Distinct function, but not really familiar with how to use them in the controller or blade.

0 likes
9 replies
MahmoudMonem's avatar

Hello @Tray2 .. thanks for your reply, can you please tell me how can i implement it in my case. because I read the docs and I'm familiar with what needs to be done, but not sure how to do it.

Sinnbeck's avatar

@MahmoudMonem Wow thats alot of n+1

Be sure to load your relations!

$product->load('stocks.color');
return view('products.show', ['product' => $product]);
MahmoudMonem's avatar

Hello @Sinnbeck thanks so much for this tip, really never knew there is has manythrough :D will definitely apply it more often. However, I actually had no problem retrieving the data. I just wanted to retrieve without repetition. an show values one time if same stock has multiple color.

MahmoudMonem's avatar

Hello @Umid82 .. this worked just perfectly :D thank you so much.. is there a way to do it cleaner in the controller ? but this is actually exactly what I was looking for, appreciate ur help <3

Please or to participate in this conversation.