Laravel View Composer无法正常工作

时间:2018-04-09 17:45:15

标签: php laravel laravel-5.5

我创建了以下View Composer:

HTTP \提供商\ ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            'layouts.cart',
            'App\Http\ViewComposers\CartComposer'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

HTTP \ ViewComposers \ CartComposer

<?php

namespace App\Http\ViewComposers;

use Iluminate\View\View;
use App\Order;

class CartComposer
{
    public cartDetails = null;

    public function __construct()
    {
        //dd('here1');
        $orderToken = session('o_token');
        $this->cartDetails = Order::getOrderDetails($orderToken);
    }

    public function compose(View $view)
    {
        //dd('here2');
        $view->with('cart', ['total_items' => 7]);
    }
}

为了测试,我正在返回一个硬编码数组['total_items'=&gt; 7]

现在我的视图通过@include包含在我的header.blade.php中:

视图\布局\ cart.blade.php

<div class="cart-menu">
  <i class="black large cart icon"></i>
  @if (/*isset($cart->total_items) &&*/ $cart->total_items > 0)
  <div class="floating ui red label cart-items-badge">{{ $cart->total_items }}</div>
  @endif
</div>

我通过将它添加到providers数组中来注册它:

  

应用\提供商\ ComposerServiceProvider ::类,

当我访问我的页面时,我收到“页面无响应”错误。我甚至看不到Laravel错误。

有什么建议吗?感谢

1 个答案:

答案 0 :(得分:1)

使用此ComposerServiceProvider文件

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer(
            'layouts.cart',
            'App\Http\ViewComposers\CartComposer'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
使用$ cart ['total_items']代替$ cart-&gt; total_items

<div class="cart-menu">
  <i class="black large cart icon"></i>
  @if ($cart['total_items'] > 0)
  <div class="floating ui red label cart-items-badge">{{ $cart['total_items'] }}</div>
  @endif
</div>