Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stephen waweru's avatar

unable to save data when a user is logged in or using session in laravel

I have an eCommerce project whereby a user adds his product to cart whether they are logged in or not..when they are logged in their user_id is saved on the database and when they arent, the session_id is saved for the and the user_id is saved as zero..I want to achieve this, for the user to proceed to the checkout page they have to log in or create an account. this works perfectly for the users who added products to the cart when they were logged in but for the users who logged in at the cart section, at the checkout page the products in the cart disappear. how can I show the products in the checkout using the sesssion_id..

0 likes
8 replies
stephen waweru's avatar

@Sinnbeck this is my checkout function

	public function checkout()
	{
  		$events=Events::latest()->take(4)->get();
    	$usercartitems=Cart::usercartitems();
        $delivaddresses=shipping_charge::all();
         return view('frontend.product.checkout')->with(compact('events','usercartitems','delivaddresses'));
     }

this is the usercartitems function in the cart model

     {
         if(Auth::check()){
           $usercartitems=Cart::with(['product'=>function($query)
           {
                $query->select('id','merch_name','merch_image','merch_code');
           }])->where('user_id',Auth::id())->orderby('id','desc')->get();
       }else{
            $usercartitems=Cart::with(['product'=>function($query)
				{
						$query->select('id','merch_name','merch_image','merch_code');
               	}])->where('session_id',Session::get('session_id'))->orderby('id','desc')->get();
       }
            return  $usercartitems;
     }```
Sinnbeck's avatar

@stephen waweru Any chance that you get them to log in, before this is handled? If so, your auth check will return true

Sinnbeck's avatar

@stephen waweru In what order is the methods run? Checkout first and then login? Or login first and then checkout?

You might want to consider changing the login function to check if there is cart items in the session, and then transfer them to the user. Then the user can log in at any point without losing the cart.

Sinnbeck's avatar

@stephen waweru Personally I have a controller to handle logins. Its in app\Http\Controller\Auth\LoginController.php

If you have a similar file, you can add the logic in there instead :)

stephen waweru's avatar

@Sinnbeck i am using the authenticated sessioncontroller,which logic should i add and where should i add in the authenticated sessioncontroller

Please or to participate in this conversation.