There's a great article related on what you want to do here https://laraveldaily.com/less-know-way-conditional-queries/
Pretty much you want to change the if statements into when statements. Here's a "optimized" version of your top code..
$page_slug = $request->get('page_slug');
$min_price = $request->input('min_price', false);
$max_price = $request->input('max_price', false);
$product_condition = $request->input('product_condition', false);
$products = null;
$products2 = null;
// Get the categories
$getCatlvl1 = Category::whereCategorySlug($page_slug);
$getCatlvl2 = SubCategory::whereCategorySlug($page_slug);
$getCatlvl3 = SubCategoryLvl3::whereCategorySlug($page_slug);
// Do we have a count?
if ($getCatlvl1->count()) {
// Get the category levels
$category_level1_id = $getCatlvl1->pluck('id')
->toArray();
$category_level2_id = SubCategory::where('parent_category', $category_level1_id)
->pluck('id')
->toArray();
$category_level3_id = SubCategoryLvl3::whereIn('parent_category', $category_level2_id)
->pluck('id')
->toArray();
$product_lookup_1 = DB::table('products')
->where('category_level', 3)
->whereIn('category', $category_level3_id)
->when($product_condition, function($query, $product_condition) {
$query->where('product_condition', $product_condition);
})
->when(($min_price AND $max_price), function($query, $min_price, $max_price) {
$query->whereBetween('selling_price', [
$min_price,
$max_price
]);
});
$product_lookup_2 = DB::table('products')
->where('category_level', 3)
->whereIn('category', $category_level3_id)
->when($product_condition, function($query, $product_condition) {
$query->where('product_condition', $product_condition);
})
->when(($min_price AND $max_price), function($query, $min_price, $max_price) {
$query->whereBetween('selling_price', [
$min_price,
$max_price
]);
})
$products = $product_lookup_1->paginate(40);
$products2 = $product_lookup_2->get();
}
It can certainly be refactored down to one DB call for products but you get the idea ;-)