Searching between two numbers(prices) in Laravel

13,994

You're looking for whereBetween(). First, put the Eloquent query in your controller:

$inventory = Inventory::where('category', $cat)
    ->where('title', 'like', '%' . $search_query . '%')
    ->whereBetween('price', [$min_price, $max_price])
    ->get();

Then, pass the $inventory variable to your view:

return view('my.view.path', compact('inventory'));

Finally, in your view, you can loop through the results:

@foreach($inventory as $search_results)

See the Laravel Docs for more info.

Share:
13,994
Brandon
Author by

Brandon

Web Developer by Day. Volunteer Firefighter by night.

Updated on July 28, 2022

Comments

  • Brandon
    Brandon over 1 year

    I'm trying to run an eloquent query to filter results by category, then title, then price. category and title work as they should but when i added BETWEEN for searching between two prices it broke. Does anyone know how i could fix my query?

    @foreach(Inventory::where('category', '=', $cat)->where('title', 'LIKE', '%'. $search_query .'%')->where('price', 'BETWEEN', $min_price, 'AND', $max_price)->get() as $search_results)
    
  • Brandon
    Brandon over 8 years
    This worked perfectly, I would had never realized there was a whereBetween for eloquent. Thanks a bunch.
  • Stuart Wagner
    Stuart Wagner over 8 years
    @Brandon Glad to help :)