【问题标题】:Laravel View Composer not workingLaravel View Composer 不工作
【发布时间】:2018-09-19 04:38:30
【问题描述】:

我创建了以下 View Composer:

Http\Providers\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' => 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>

我已经通过将它添加到提供者数组来注册它:

App\Providers\ComposerServiceProvider::class,

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

有什么建议吗?谢谢

【问题讨论】:

  • 检查您的错误日志?查看/storage/logs 和您的网络服务器日志所在的位置。
  • @aynber 确实,查看 /storage/logs 帮助我找出了问题所在。谢谢你的建议。有没有办法在屏幕上“激活”错误日志?

标签: php laravel laravel-5.5


【解决方案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()
    {
        //
    }
}

views\layouts\cart.blade.php 使用 $cart['total_items'] 而不是 $cart->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>

【讨论】:

  • 不,我仍然遇到同样的错误。顺便说一句,我看不出你的服务提供商和我的有什么区别。你在使用 View 门面,而我使用 helper,我认为这没有什么不同,我错了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2019-05-18
  • 1970-01-01
相关资源
最近更新 更多