0

I write a function as below: and wonder why got this error? When the cat_id and price selected is fine. Price selected also go well. Just when i choose only the Categories it doesn't any effect and show the error Undefined offset: 1

public function productsCat(Request $request){
    $cat_id = $request->cat_id;
    $price = explode("-",$request->price);

    $start = $price[0];
    $end = $price[1];

    if($cat_id!="" && $price!="0"){
        $data = DB::table('products')
            ->join('cats','cats.id','products.cat_id')
            ->where('products.cat_id',$cat_id)
            ->where('products.pro_price', ">=", $start)
            ->where('products.pro_price', "<=", $end)
            ->get();

    }

    else if($price!=""){
        $data = DB::table('products')
            ->join('cats','cats.id','products.cat_id')
            ->where('products.pro_price', ">=", $start)
            ->where('products.pro_price', "<=", $end)
            ->get();
    }
    else if($cat_id!=""){
        $data = DB::table('products')
            ->join('cats','cats.id','products.cat_id')
            ->where('products.cat_id',$cat_id)
            ->get();
    }
    else{
        return "<h1 align='center'>Please select at least one filter from drop down list</h1>";

    }
    if(count($data)=="0"){
        echo "<h1 align='center'>no products found under this Category</h1>";
    }else{
        return view('front.productsPage',[
            'data' => $data, 'catByUser' => $data[0]->cat_name
        ]);
    }

}

user10354117
  • 71
  • 2
  • 14

1 Answers1

0

use this code it will work for you

public function productsCat(Request $request){
    $cat_id = $request->cat_id;
    $price = explode("-",$request->price);

    $start = $price[0];
    $end = $price[1];


    $data = DB::table('products');
    if (!empty($cat_id)) {
        $data->join('cats','cats.id','products.cat_id')
            ->where('products.cat_id',$cat_id);
    }
    if(!empty($start) && !empty($end)){
        $data->where('products.pro_price', ">=", $start)
            ->where('products.pro_price', "<=", $end)
    }
    $data->get();
    if(empty($cat_id) && empty($request->price))
    {
        return "<h1 align='center'>Please select at least one filter from drop down list</h1>";

    }
    if(count($data)==0){
        echo "<h1 align='center'>no products found under this Category</h1>";
    }
    else
    {
        return view('front.productsPage',[
            'data' => $data, 'catByUser' => $data[0]->cat_name
        ]);
    }
}
Shailendra Gupta
  • 1,054
  • 6
  • 15