Question:
Help me with the Laravel 10 access cookie data service provider

Problem

To add a shopping cart which is viewable from all pages on my Laravel webpage I created a service provider:


<?php


namespace App\Providers;

use Illuminate\Support\Facades\Cookie;

use Illuminate\Support\Facades\View;

use Illuminate\Support\ServiceProvider;


class ViewServiceProvider extends ServiceProvider

{

    /**

     * Register services.

     */

    public function register(): void

    {

        //


    }


    /**

     * Bootstrap services.

     */

    public function boot(): void

    {

        //

        $cart = json_decode(Cookie::get('cart'), true) ?? ["abcs"];

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

    }

}


However the value of $cart is always ["abcs"], because for some reason the (Cookie::get('cart') is empty.


However in different views when I add in the controller for example:


public function index(Request $request)

{

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

    return view('cart.index', compact('cartItems'));

}



Than the expected values for the cart are visible.


How can I share cookie data with all views?


Solution

You could try 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,

    ],

    // ...

];


Then, you could access the cartItemsCookie variable in all your views.


Answered by: >Sven van den Boogaart

Credit: >StackOverflow


Blog Links: 

>How do I customize controller actions in Laravel Jetstream?

>Run Laravel Project to Active Local Server

>How to show encrypted user id in URL in Laravel?

>How to fix Laravel LiveWire listener?


Nisha Patel

Nisha Patel

Submit
0 Answers