You can use distinct in your query and only pull the ones you want instead of handling that in php.
https://laravel.com/docs/8.x/queries#specifying-a-select-clause
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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.
Please or to participate in this conversation.