Reputation: 533
I want to create a filter with these fields
if i dont fill some fields and submitted null values the following query not works.
$posts = Post::where('brand',$brand)
->where('country',$country)
->where('city',$city)
->where('car_type',$car_type)
->where('color','LIKE',$color)
->whereBetween('year',[$from_year,$to_year])
->whereBetween('milage',[$min_milage,$max_milage])
->whereBetween('price',[$min_price,$max_price])
->where('warranty',$warranty)
->where('seller_type',$seller_type)
->paginate(4);
Upvotes: 0
Views: 153
Reputation: 1673
That's because you tell eloquent to check for NULL in the database, which results in a query like this:
WHERE brand IS NULL AND ... AND seller_type IS NULL
To avoid it, you must not apply filters on your query if you actually don't want to filter. Filter for set values only like this:
$posts = Post::all();
if( !is_null($brand) )
$posts = $posts->where('brand', $brand)
// ...
if( !is_null($seller_type) )
$posts = $posts->where('seller_type', $seller_type)
$posts = $posts->paginate(4);
Note: You can get the query that's being generated with the toSQL
method:
dd( $posts->toSql() );
Very handy for debugging.
Upvotes: 3