Advanced operations with Collection:where in Laravel 5.2
In Laravel, you can use Collection:where()
to filter records which meet particular criteria. The where
method uses strict comparisons when checking item values. A simple scenario of using where()
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$collection = collect([ ['product' => 'Belt', 'price' => 200], ['product' => 'Suit', 'price' => 6000], ['product' => 'Shoe', 'price' => 1500], ['product' => 'Blazer', 'price' => 1000], ]); $filtered = $collection->where('price', '>', 1499); $filtered->all(); /* [ ['product' => 'Suit', 'price' => 6000], ['product' => 'Shoe', 'price' => 1500], ] */ |
In e-commerce application we have to filter the records which meet multiple criteria like brand, vendor, size, color, price, sorting, searching and so on.
Lets say we have to find product records having category shoes, brand_name Puma, color white, price between 2000 and 4000,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
$categoryIdArr = array(); if(!is_null($categoryId) && !empty($categoryId)) { $categories = \App\Category::where('id', $categoryId) ->orWhere('parent_category_id', $categoryId)->get(); foreach($categories as $category) { array_push($categoryIdArr, $category->id); } } Product::where('product_status', '=', 'PUBLISHED') ->where('in_stock', '=', 1) ->where(function($query) use ($price, $categoryId, $brand, $color) { $priceSplit = !empty($price) ? explode("|", $price) : null; if(!is_null($priceSplit)) { $query->whereBetween('offer_price', [$priceSplit[0], $priceSplit[1]]); } if(!is_null($categoryId) && !empty($categoryId)) { $query->whereIn('category_id', $categoryIdArr); } if(!is_null($brand) && !empty($brand)) { $query->where('brand_id', '=', $brand); } if(!is_null($color) && !empty($color)) { $query->where('product_color', '=', $color); } }) ->inRandomOrder()->orderBy($key, $value)->paginate($perPage); |
In above code snippet we are filtering records in random order and records are ordered by $key
and $value
specified. Collection records can be paginated by using paginate()
method.