Diego Cespedes
Diego Cespedes

Reputation: 1353

Laravel 5.1 - Show my session cart

to show in header menu my products of my cart session, I'm passing the session "cart" from my controller to my view, like this:

FrontController:

public function index()
    {
        $cart = \Session::get('cart');

        return view('index',compact('cart'));
    }

Routes.php

Route::get('/','FrontController@index');

my layout principal.blade.php ( it work well)

@foreach ($cart as $item)

all items of my session cart

@endforeach

MY QUESTION:

there is a way to pass the cart session directly to all my views?? OR I must always pass the cart Session for each view ? i have about 24 views, i must do each view like my view homepage index.php ??

Thank you for your help!

Upvotes: 1

Views: 1205

Answers (3)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Why you want to pass session data from controller? Sessions are available everywhere. This should work without passing anything from a controller:

@foreach (session()->get('cart') as $item)
    all items of my session cart
@endforeach

Upvotes: 1

JasonK
JasonK

Reputation: 5294

This is a perfect job for Laravel's View Composers.

Create a new service provider, let's call it ComposerServiceProvider:

<?php

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()
    {
        // Share $_cart to every view
        view()->composer('*', function ($view) {
            view()->share('_cart', \Session::get('cart'));
        });
    }

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

Don't forget to add the service provider within config/app.php. You can also compose variables to specific views only by replacing the * wildcard.

You may noticed I've added a underscore prefix _cart to the variable. I do this so you know the variable is shared and not passed by the controller.

Upvotes: 1

huuuk
huuuk

Reputation: 4795

use data sharing

add to boot method in your AppServiceProvider

view()->share('cart', \Session::get('cart'));

Upvotes: 2

Related Questions