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

pimous's avatar

How to use a where with two fields of the same table ?

Hi, I try to have the products whose stock is smaller or equal than the minimum stock. So I have this :

 $products = PRODUCT::with('category')->where('stock', '<=', 'stock_min')->get();

But it doesn't work ! Because only the products with 0 stock is displaying, it doesn't care about the 'stock_min' value. (The stock and stock_min fields are "double" type.)

0 likes
5 replies
pimous's avatar

I could take the test directly in the view

@if($product->stock <= $product->stock_min)
...

But it's not very clean, I prefer to have the maximum logic outside the view. So anyone has a solution ?

kadari's avatar
kadari
Best Answer
Level 1

Hello, you can use whereRaw:

$products = PRODUCT::with('category')->whereRaw('stock <= stock_min')->get();
6 likes
cm's avatar
$products = PRODUCT::with('category')->where('stock', '<=', 'stock_min')->get();

This doesn't work, because the third parameter of where() expects a value. stock_min is not a value, but another column. The resulting SQL statement would look something like this:

SELECT * FROM product WHERE stock <= 'stock_min'

@kadari is right, use whereRaw()

2 likes
pimous's avatar

@kadari whereRaw('stock <= stock_min') works perfectly ! Thx a lot :)

@cm Thanks for your explanations :)

alekser's avatar

Product::with('category')->whereColumn('stock', '<=', 'stock_min')->get();

laravel has built in method "whereColumn" for this...

4 likes

Please or to participate in this conversation.