Home > database >  query builder spatie laravel sort pricr by low and high
query builder spatie laravel sort pricr by low and high

Time:01-13

I want get product by price low price and max price but result has mistake in my product model

public function scopeminPrice(Builder $query, $min_price): Builder
{
    return $query->where('price', '>=', ($min_price));
}
public function scopemaxPrice(Builder $query, $max_price): Builder
{
    return $query->where('price', '<=', ($max_price));
}

and my controller

public function index(Request $request)
{
    $products = QueryBuilder::for(Product::class)
        ->allowedFilters([
            AllowedFilter::scope('min_price' ),
            AllowedFilter::scope('max_price' ),
        ])


        ->with('category')->paginate('4')
        ->appends(request()->query());


    return view('frontend.product.index',
        compact(

            'products',
        ));
}

and my form

<form method="GET" id="jobfilter-form" enctype="multipart/form-data" content="{{ csrf_token() }}">
<div >
    <ul >
        <li>
            <input  type="text" id="minPrice"  name="minPrice"  value=""  @if ((explode(',', request()->input('filter.min_price')))) @endif  oninput="this.nextElementSibling.value = this.value" placeholder="min price">
        </li>
        <li>
            <input  type="text" id="maxPrice"  name="maxPrice" value="" @if ((explode(',', request()->input('filter.max_price')))) @endif oninput="this.nextElementSibling.value = this.value"  placeholder="max price">

        </li>
    </ul>
</div>
<button  type="button" id="filter">search</button></form>

and scripts

<script>
    function getIds(checkboxName) {
        let checkBoxes = document.getElementsByName(checkboxName);
        let ids = Array.prototype.slice.call(checkBoxes)
            .filter(ch => ch.checked == true).map(ch => ch.value);
        return ids;
    }
    function filterResults() {
        let minPrice = document.getElementById("minPrice").value;
        let maxPrice = document.getElementById("maxPrice").value;
     
        document.location.href = href;
    }

    $("#jobfilter-form #filter").on("click", e => {
        filterResults();
    });
</script>

result is not true for example when min price is 60000 only show 60000 but product have 50000 and 45000

CodePudding user response:

I am not sure but reason may be the type of your request variables.

Validate as integers "price", "min_price" and "max_price" or specify the type like that;

return $query->where('price', '>=', (int)($min_price));
  •  Tags:  
  • Related