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

Shiva's avatar
Level 5

Advice on session and shopping cart

Hi, I would like some advice. I've created a shopping cart site on my localhost and with the way I've done it the shopping cart and the user log in is both using session. In the begining I had a problem where I couldn't get my menu to display the login sign when I logged out instead it had user profile. So I added Session::flush(); to my logout function but that also cleared my cart.

What I would like to know is, is that ok. Is it ok to clear the cart when the user logs out. Or is there a way to only clear the session to only one section.

Just in case you want to see the menu bit here it is

<ul class="dropdown-menu">
    @if(Auth::guard('customer_admin')->check())
        <li><a href="{!! route('customer.dashboard') !!}">User Profile</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="{!! route('logout') !!}">Logout</a></li>
    @else
        <li><a href="{!! route('customer.signup') !!}">Sign up</a></li>
        <li><a href="{!! route('login') !!}">Login</a></li>
    @endif
</ul>

So what the menu is doing is checking if the customer has logged in and displayes the user profile and logout else if the user isn't logged in then it shows the sign up and login links.

If there is anything else please let me know

0 likes
15 replies
Screenbeetle's avatar

Morning.

It's probably a bit annoying to lose your cart when you log out. You should be able to do this by deleting a specific item from your session though: $request->session()->forget('item');

atishrajput's avatar

Session::flush(); removes all the session of current application.

you should use $request->session()->forget('item_name'); to remove particular session.

but from my point of view you should save cart data of users (with user id) into some table so you can display the cart values when user login again. and clear the cart data from table when user remove item from cart or buy item. and use Session::flush(); at the time of logout :)

1 like
Shiva's avatar
Level 5

How would I get the item? Is it like a different session name? for example the cart uses cart_session and the user uses user_session

atishrajput's avatar

just create a table carts

cart_id : auto increment primary key

user_id : int

data : text

cart_session includes the data of a single user. when user logout simply flush all sessions

store data:

user_id: Auth::id() (user login id)

data: json_encode(cart_session)

thoasty's avatar

My advice on the usability-part: it is perfectly okay to clear the cart on logout.

Think about it this way: The main reason, so in most of the usecases, to logout is to leave your shop. If the user logs out, he does not want the next user of "this computer" to see what he has done inside your shop. If you didnt clear the cart, that would not be sufficient.

Actually even amazon does it the same way.

atishrajput's avatar

@thoasty we are talking about login users not visitors. amazon saves the cart data if user login

1 like
Shiva's avatar
Level 5

@atishrajput - Sorry if I'm asking to many silly questions. This is the first time I've ever created a cart and I want to get it right.

What you are saying is I create 2 tables

Table 1 is carts and table 2 is cart_session.

In Cart table I add

cart_id : auto increment primary key

user_id : int

data : text

and in Cart_session table I add

user_id: Auth::id() (user login id)

data: json_encode(cart_session)

My next question is the data in both Cart and Cart_session is that the products that is in the cart?

atishrajput's avatar
  1. you have to create a single table name "carts"

Table Structure:-

cart_id (int auto_increment primary_key)

user_id (int foreign key users table user_id)

data (text)

  1. at the time of logout (before logout)

    $cart_data = Session::get('Cart_session');

    $cart = [

     'data'      => json_encode($cart_data);
    

    ];

$carts_tbl = DB::table('carts')->where(['user_id' => Auth::id()])->first();

if(isset($carts_tbl)){

    DB::table('carts')->where(['user_id' => Auth::id()])->update($cart);

} else{

    $cart['user_id'] =   Auth::id(),
DB::table('carts')->insert($cart);

}

Session::flush();

  1. at the time of login (after login)

    $carts_tbl = DB::table('carts')->where(['user_id' => Auth::id()])->first();

    if(isset($carts_tbl)){

     $cart_data = json_decode($carts_tbl->data);
     Session::set('Cart_session',$cart_data);
    

    }

  1. Display Cart

    Session::get('Cart_session');

update cart session when user add or remove products 
1 like
thoasty's avatar

@Shiva asking questions is never wrong, but better be aware of bad code here.

If the relation is 1 user -- 1 cart and 1 guest -- 1 cart:

  1. create a cart
  2. save the cart into the session if the user is not logged in.
  3. save the cart into the user (user has a cart_id) if he is logged in or when he logs in.
  4. flush the session on logout
Shiva's avatar
Level 5

I've saved the session into the database and I'm trying to only show the qty that is being saved, but I keep getting this error

ErrorException in CustomersController.php line 77:
Undefined property: stdClass::$qty

Line 77 is

print_r($show_session->qty);

Here is the full login code

public function postLogin(Request $request)
    {

        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if(Customer::where('email', '=', Input::get('email'))->exists())
        {
            if(auth('customer_admin')->attempt(array('email' => $request->input('email'), 'password' => $request->input('password'))))
            {
                if(auth()->guard('customer_admin')->user()->is_activated == '0')
                {
                    $this->logout();
                    return back()->with('error', 'Please activate your account');
                }
                $name = auth()->guard('customer_admin')->user()->name;
                $customer_id = auth()->guard('customer_admin')->user()->id;

                $carts_tbl = DB::table('cart_session')->where(['customer_id' => $customer_id])->first();

                if(isset($carts_tbl))
                {
                        $cart_data = json_decode($carts_tbl->data);
                        Session::put('cart_session_test', $cart_data);
                        $show_session = Session::get('cart_session_test');

                        echo "<PRE>";
                        print_r($show_session->qty);
                        die();
                }

                return redirect()->route('customer.dashboard');
            }else{
                return back()->with('error', 'Your email/password combination is wrong');
            }
        }else{
            return back()->with('error', 'Please <a href="'.route('customer.signup').'">sign up</a>');
        }
    }
Shiva's avatar
Level 5

@atishrajput - here is the result

stdClass Object
(
    [18d6934483b994fb9943b43b7d7646bf] => stdClass Object
        (
            [rowId] => 18d6934483b994fb9943b43b7d7646bf
            [id] => 8
            [name] => Product 8
            [qty] => 1
            [price] => 80
            [image] => ["hot-dog.jpg"]
            [options] => Array
                (
                )

            [tax] => 16.8
            [subtotal] => 80
        )

)

and here is my CustomersController.php

<?php

namespace App\Modules\Customers\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Modules\Menus\Models\Menu;
use App\Modules\Customers\Models\Customer;
use App\Modules\Customers\Models\Address;
use App\Modules\Open\Models\CartSession;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Support\Facades\Input;
use Validator;
use DB;
Use Mail;
use Auth;
use Session;

class CustomersController extends Controller
{
    

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'email|required|unique:customers',
            'password' => 'required|min:6',
            'confirm_password' => 'required|same:password',
        ]);
    }

    protected function publicCreate(array $data)
    {
        return Customer::create([
            'name' => $data['name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'is_activated' => 0,
        ]);
    }

    public function dashboard()
    {
        $menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
        return view('customers::profile.dashboard', compact('menus_child'));
    }

    public function postLogin(Request $request)
    {

        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if(Customer::where('email', '=', Input::get('email'))->exists())
        {
            if(auth('customer_admin')->attempt(array('email' => $request->input('email'), 'password' => $request->input('password'))))
            {
                if(auth()->guard('customer_admin')->user()->is_activated == '0')
                {
                    $this->logout();
                    return back()->with('error', 'Please activate your account');
                }
                $name = auth()->guard('customer_admin')->user()->name;
                $customer_id = auth()->guard('customer_admin')->user()->id;

                $carts_tbl = DB::table('cart_session')->where(['customer_id' => $customer_id])->first();

                if(isset($carts_tbl))
                {
                        $cart_data = json_decode($carts_tbl->data);
                        Session::put('cart_session_test', $cart_data);
                        $show_session = Session::get('cart_session_test');

                        echo "<PRE>";
                        print_r($show_session);
                        die();
                }

                return redirect()->route('customer.dashboard');
            }else{
                return back()->with('error', 'Your email/password combination is wrong');
            }
        }else{
            return back()->with('error', 'Please <a href="'.route('customer.signup').'">sign up</a>');
        }
    }

    public function logout(Request $request)
    {
            $cart_data = Session::get('cart_session_test');
            $customer_id = auth()->guard('customer_admin')->user()->id;

            $cart_data = Cart::content();

            $cart = [

             'data'      => json_encode($cart_data),

            ];

        $carts_tbl = DB::table('cart_session')->where(['customer_id' => $customer_id])->first();

        if(isset($carts_tbl)){

            DB::table('cart_session')->where(['customer_id' => $customer_id])->update($cart);

        } else{

            $cart['customer_id'] =   $customer_id;
            DB::table('cart_session')->insert($cart);

        }

        Auth::logout();

        $request->session()->forget('customer_admin');
        return redirect()->route('login')->with('success', 'You`ve been successfully logged out');
    }
}

atishrajput's avatar
Level 1

@Shiva use below code :)

foreach($show_session as $sess){

// print_r($sess);

echo $qty = $sess->qty;

}

1 like

Please or to participate in this conversation.