我想移动一个帮助器以显示在所有视图中。帮助者是 - >
helperFunctions :: getPageInfo($ cart,$ total);
此时我必须在每个控制器中定义这些信息,例如:
public function show($id, Request $request)
{
$category = Category::find($id);
if (strtoupper($request->sort) == 'NEWEST') {
$products = $category->products()->orderBy('created_at', 'desc')->paginate(40);
} elseif (strtoupper($request->sort) == 'HIGHEST') {
$products = $category->products()->orderBy('price', 'desc')->paginate(40);
} elseif (strtoupper($request->sort) == 'LOWEST') {
$products = $category->products()->orderBy('price', 'asc')->paginate(40);
} else {
$products = $category->products()->paginate(40);
}
helperFunctions::getPageInfo($sections, $cart, $total);
return view('site.category', compact('cart', 'total', 'category', 'products'));
}
我阅读并尝试将该帮助程序移动到Boot()函数内的AppServiceProvider.php。
public function boot()
{
helperFunctions::getPageInfo($cart,$total);
View::share('cart','total');
}
但我收到错误信息:
未定义变量:总计
- - - - UPDATE --------
使用getPageInfo
的我的类助手class helperFunctions
{
public static function getPageInfo(&$cart,&$total)
{
if (Auth::user()) {
$cart = Auth::user()->cart;
} else {
$cart = new Collection;
if (Session::has('cart')) {
foreach (Session::get('cart') as $item) {
$elem = new Cart;
$elem->product_id = $item['product_id'];
$elem->amount = $item['qty'];
if (isset($item['options'])) {
$elem->options = $item['options'];
}
$cart->add($elem);
}
}
}
$total = 0;
foreach ($cart as $item) {
$total += $item->product->price*$item->amount;
}
}
}
答案 0 :(得分:1)
由于您在辅助函数中通过引用传递变量,因此需要在调用之前定义它们。将您的视图共享代码更改为此。
public function boot()
{
$cart = null;
$total = 0;
helperFunctions::getPageInfo($cart, $total);
$data = [
'cart' => $cart,
'total' => $total,
];
View::share($data);
}
然后,您可以在所有观看次数中访问$cart
和$total
。
或者,如果你想让事情变得更清洁,那么让helper函数返回数据数组并将其传递给视图。