如何使用AppServiceProvider中的帮助程序将帮助程序数据传递给Laravel 5中的所有视图?

时间:2017-05-24 02:30:02

标签: php laravel laravel-5

我想移动一个帮助器以显示在所有视图中。帮助者是 - >

  

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;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

由于您在辅助函数中通过引用传递变量,因此需要在调用之前定义它们。将您的视图共享代码更改为此。

public function boot()
{
    $cart = null;
    $total = 0;

    helperFunctions::getPageInfo($cart, $total);

    $data = [
        'cart' => $cart,
        'total' => $total,
    ];

    View::share($data);
}

然后,您可以在所有观看次数中访问$cart$total

或者,如果你想让事情变得更清洁,那么让helper函数返回数据数组并将其传递给视图。