I have this function with variable index $product, $categories, $most_views, $show, $check, $checkforid.
public function index()
{
$products=Product::where(['status'=>'1'])->orderBy('most_viewed','desc')->with('category')->get();
$categories=Category::all();
$mostviews=Product::where(['status'=>'On sale'])->orderBy('most_viewed','desc')->limit(10)->get();
$show=Product::orderBy('most_viewed','desc')->with('category')
->with('user')
->with('productbrand.brand')
->first();
if(Auth::check())
{
$check=Watchlist::where(['user_id'=>Auth::user()->id])->get()->toArray();
foreach($check as $che)
{
$checkforid[]=$che['product_id'];
}
}
return View('product.index',['products'=>$products,'mostviews'=>$mostviews,'show'=>$show,'checkforid'=>$checkforid,'categories'=>$categories]);
}
if any of these variables does not exist,
return View('product.index',['products'=>$products,'mostviews'=>$mostviews,'show'=>$show,'checkforid'=>$checkforid,'categories'=>$categories]);
an undefined error occurs, the variable is changed and the entire index page. so I want to skip passing the variable that exists. what is the best solution for this?
So far, I have initialized all the variables in null.so if any variable doesnot exist null is passed. is this a good practice?
public function index()
{
$products=null;
$show=null;
$check=null;
$checkforid=null;
$mostviews=null;
$categories=null;
$products=Product::where(['status'=>'1'])->orderBy('most_viewed','desc')->with('category')->get();
$categories=Category::all();
$mostviews=Product::where(['status'=>'On sale'])->orderBy('most_viewed','desc')->limit(10)->get();
...
}