Ich habe diese Index-Funktion mit Variablen $product
, $categories
, $most_views
, $show
, $check
, $checkforid
.Umgang mit undefinierten Variablen
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]);
}
, wenn eine dieser Variablen existieren doesnot,
return View('product.index',['products'=>$products,'mostviews'=>$mostviews,'show'=>$show,'checkforid'=>$checkforid,'categories'=>$categories]);
ein Fehler nicht definierte Variable und ganze Indexseite dort kommt betroffen ist. also möchte ich die Variable überspringen, die nicht existiert. Was ist die beste Lösung dafür?
Bis jetzt habe ich alle Variablen auf null initialisiert. Wenn eine Variable nicht existiert, wird null übergeben. ist es eine gute Praxis?
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();
...
}
möglich duplizieren http://stackoverflow.com/questions/17767094/check-if-array-value-isset-and- is-null –
if (isset ($ someVar)) zu überprüfen –