如何自定义Laravel whereBetween子句使上限无限制?

I have been working on laravel using eloquent query builders. I have a situation in which I am filtering records based on search queries. I have an integer field, for which I want to filter data in ranges. User can select any of available ranges for example; 0-15, 15-30 and 30 and above. For this purpose I found Query-builders whereBetween() clause very helping. But It becomes difficult for me for last option when I want to select for 30 and above. I would really appreciate if someone could help me with some trick make this query

->whereBetween('time_taken', [$lower-limit,$uper_limt])

working for all cases. I don't want to write an additional line for this case, at which I can use simple where clause

->where('time_taken','>=',$uper_limt).

The practical solution here is to just choose the appropriate SQL condition (I'm using a ternary operator here to keep it more compact):

$query = App\Operation::query();

(empty($upper_limit)) ? $query->where('time_taken','>=', $lower_limit)
                      : $query->whereBetween('time_taken', [$lower_limit, $upper_limit]);

$results = $query->get();

Sure it would be nice to have just one line:

$results = App\Operation::whereBetween('time_taken', [$lower_limit, $upper_limit])->get();

But that's not possible in this case, not unless you want to extend the Laravel Query Builder and modify the way it handles empty parameters in the range passed as the value.


Writing clean and concise code is something we all strive to achieve, but one line solutions are not always possible. So my advice is to stop fixating (something I sometimes do myself) on things like this, because in some cases it's a lost cause that just ends up wasting time.

You can try any of these:

Method 1:

->whereBetween('time_taken', [$lower-limit,ModelName::max('time_taken')])

Method 2:

->whereBetween('time_taken', [$lower-limit,DB::table('table_name')->max('time_taken')]) 

Method 3:

$max = ModelName::max('time_taken');
//or
$max = DB::table('table_name')->max('time_taken');
//then
->whereBetween('time_taken', [$lower-limit,$max]) 

max() returns the highest value from your corespondent column.