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

option's avatar

Laravel Query - Be greater or equal to X but be less then Z

So I am running a query as follows:

$wealth = DB::table('users')
            ->select('users.id','users.cash','wealth.wealth','wealth.min_cash','wealth.max_cash')
            ->join('wealth', 'users.cash', '>=', 'wealth.min_cash')
            ->where('users.id', '=', $user->id)
            ->get()
            ->first();

Basically within my Table I have Wealth, min_cash, max_cash.

If the users cash is greater than or equal to the minimum cash AND lower than the max cash then display the wealth for that specific column.

I've tried numerous ways but nothing seems to work..

Can someone shed some light on where I am going wrong please.

0 likes
3 replies
Parasoul's avatar
Parasoul
Best Answer
Level 3

I assume you already queried your user. Then just query the wealth :

$wealth = DB::table('wealth')
            ->select('wealth','min_cash','max_cash')
            ->where('min_cash', '<=',  $user->cash)
            ->where('max_cash', '>',  $user->cash)
            ->get()
            ->first();

2 likes
option's avatar

This seems to throw back:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '800' in 'where clause' (SQL: select `wealth`, `min_cash`, `max_cash` from `wealth` where `800` >= min_cash and `800` < max_cash)

Yes $user is called within the function.

option's avatar

It works, i just had to tweak your settings slightly:

$wealth = DB::table('wealth')
            ->select('wealth','min_cash','max_cash')
            ->where('min_cash', '<=',  $user->cash)
            ->where('max_cash', '>',  $user->cash)
            ->get()
            ->first();
1 like

Please or to participate in this conversation.