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

matthewinSpire's avatar

Displaying a dropdown depending on whether or not there are values in the database

Three tables: products, flavors, and flavor_product (the pivot table).

The flavor product model and the flavor model both have the necessary belongsToMany relationship defined.

Regarding how the product is retrieved and displayed (from the controller):

$product = Product::where('slug', $slug)->with('flavors')->firstOrFail();
$mightAlsoLike = Product::where('slug', '!=', $slug)->mightAlsoLike()->get();

return view('product')->with([
    'product' => $product,
    'mightAlsoLike' => $mightAlsoLike,
]);

From the view:

 <select id="product-flavor" class="bs-select">
  @foreach ($product->flavors as $flavor)
     <option value="{{ $flavor->id }}">{{ $flavor->name }}</option>
  @endforeach
</select>

Now, here's the issue I'm running into. Not all products have flavors, so I need to only show the dropdown when there are flavors associated with said product. I've tried encompassing the view code in an if statement, but to not avail. I've though about how I could modify the controller, but I'm not sure if that's the right way forward.

Any suggestions? Thank you!

0 likes
3 replies
lostdreamer_nl's avatar

I think that you've tried the following and failed :

@if($product->flavors)
   <select id="product-flavor" class="bs-select">
    @foreach ($product->flavors as $flavor)
       <option value="{{ $flavor->id }}">{{ $flavor->name }}</option>
    @endforeach
  </select>
@endif

The reason that it failed was because $product->flavors is always 'trueish', it's an object (Collection object).... It's an empty collection, but still a collection, so if ($collection) is true.

Try the following:

@if($product->flavors->count())
   <select id="product-flavor" class="bs-select">
    @foreach ($product->flavors as $flavor)
       <option value="{{ $flavor->id }}">{{ $flavor->name }}</option>
    @endforeach
  </select>
@endif

That should work (since count will return 0 or more, and zero is 'falsey'

1 like
matthewinSpire's avatar

That worked perfectly, thank you! Also, you were exactly right on what I attempted and thank you for explaining why it failed.

Robstar's avatar
Robstar
Best Answer
Level 50

Could make it slightly more readable imo:

@if($product->flavors->isNotEmpty())
   <select id="product-flavor" class="bs-select">
    @foreach ($product->flavors as $flavor)
       <option value="{{ $flavor->id }}">{{ $flavor->name }}</option>
    @endforeach
  </select>
@endif
1 like

Please or to participate in this conversation.