我有这个索引函数与变量$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]);
}
如果这些变量中的任何一个不存在,
return View('product.index',['products'=>$products,'mostviews'=>$mostviews,'show'=>$show,'checkforid'=>$checkforid,'categories'=>$categories]);
出现错误未定义的变量,整个索引页面都会受到影响.所以我想跳过传递不存在的变量.什么是最好的解决方案?
到目前为止,我已将所有变量初始化为null.如果任何变量不存在,则传递null.这是一个好习惯吗?
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();
...
}
解决方法:
据我所知,你唯一的问题是$checkforid.只需将其初始化为空数组:
$checkforid = [];
if(Auth::check())
{
...
$checkforid[]= ...
...
}
一个好的IDE会警告并告诉你类似“$checkforid可能没有被定义”的东西.