Laravel user login continue with same cart

Viewed 614

I am implementing this shipping cart for laravel (https://github.com/darryldecode/laravelshoppingcart/issues/250). When a user logs in I would like to continue their cart, for this to happen I would need to save the session id then merge that data on login.

The problem I am having is that when i flash the cart inside \app\Http\Controllers\Auth\LoginController.php, the session id changes. It seems that all files inside Auth changes when getId().

session()->flash('guest_cart', [
    'session' => session()->getId(),
    'data' => cart()->getContent()
]);

So if I flash the session else where, how do I merge it into the new user cart on login if I am not able to retrieve the the original getId()?

When I output dd(session()->all()); inside LoginController it shows an empty array. I would somehow need to capture session('guest_cart.data'); during login.

I tried adding this to LoginController.php

protected function authenticated(Request $request, $user){
    if(Auth::check()){

        $session_id = \Session::getId();
        $cartObj = \Cart::session($session_id)->getContent();

          if (\Auth::guest()) {
              session()->flash('guest_cart', [
                  'session' => $session_id,
                  'data' => $cartObj
              ]);
          }


        dd(session()->all());   
    }

but again guest_cart returns an empty array because $session_id = \Session::getId(); has changed.

1 Answers

where would I create an event to retrieve during login? Can you point me towards a direction on how to accomplish this?

We can just override the authenticated() method in Auth\LoginController.php to save anything to the session. If you want to store only few values then just update it.

authenticated() method is called just after the user is logged in & it is defined empty in the trait AuthenticatesUsers used in LoginController.

use Illuminate\Http\Request; 

protected function authenticated(Request $request, $user)
    {
        if(Auth::check){
            //assuming that you have a cart relationship with user.
            $cartData = Auth::user()->cart()->getContent();
            $request->session()->put('cart_data', $cartData);

        }
        
        return redirect()->intended($this->redirectPath());
    }

If you have a lot of things to do you can then create an event, then use listeners to listen to that event. We will call the event from authenticated method itself.

Related