Question:
How to access cookie data in all view-Laravel?

Solution

View composer allows you to share data with all views in Laravel. Whenever a view is rendered, a view composer will help you bind logic to a view. You can build a view composer that gets the required cookie data and shares it with all views in order to access cookie data in all views.


The following is the code of custom middleware:


class ShareCartData

{

    public function handle($request, Closure $next)

    {

        $cart = json_decode($request->cookie('cart'), true) ?? [];

        View::share('cartItemsCookie', $cart);


        return $next($request);

    }

}


Register the middleware in the app/Http/Kernel.php file within the $middlewareGroups array:


protected $middlewareGroups = [

    'web' => [

        // ...

        \App\Http\Middleware\ShareCartData::class,

    ],

    // ...

];


After this you could easily access the cartItemsCookie variable in all your views.


Suggested blogs:

>How to register a schedule with the controller?

>How to resolve the Composer dependency conflicts (Symfony)?

>How to get item details of Woo Commerce in custom email content?

>PHP cURL to upload video to azure blob storage

>How to merge cells with HTML, CSS, and PHP?


Nisha Patel

Nisha Patel

Submit
0 Answers