Reputation: 1323
I've created the following 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]);
}
}
Just for the sake of testing, I'm returning a hardcoded array ['total_items' => 7]
And now my view which is included via @include in my header.blade.php:
views\layouts\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>
I've registered it by adding it to the providers array:
App\Providers\ComposerServiceProvider::class,
When I access my page I'm getting a 'Page is Not Responding' error. I can't even see the Laravel error.
Any suggestion? Thanks
Upvotes: 0
Views: 803
Reputation: 43
Use this ComposerServiceProvider file
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 use $cart['total_items'] instead of $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>
Upvotes: 2