Skip to content

Sharing total cart row count to all views [v5.4]

Mehmet Onur AKKAYA edited this page Mar 19, 2017 · 4 revisions

Problem

I was looking for a way to accomplish sharing the total number of items in the cart, to all views, in hopes of maintaining an icon in the menu bar. I tried \View::share() in my AppServiceProvider but it turns out the session is not started yet, so nothing is available. 👎

Solution

I found out the easiest way I could accomplish this behavior was to use a View Composer. This way, the session was initialized and I could retrieve the cart contents. 👍

I created a ComposerServiceProvider in my \App\Providers directory, which I took straight from the Laravel Docs. Then I just added a call to the Cart Facade and counted the collection returned from Cart::content(), like so.

<?php

namespace App\Providers;

use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        View::composer('*', function ($view) {
            /** @var \Illuminate\Contracts\View\View $view */
            $view->with('cart_qty', count(Cart::content()));
        });
    }
}

This provided the {{ $cart_qty }} variable to every view (specifically my main blade template layout) so I don't have to include the count in every created view from each controller. Win!

Menu with cart icon and count

You may need to add ComposerServiceProvider to providers in config/app.php

Clone this wiki locally