User Experience in Laravel e-Commerce Web App

When it comes to e-Commerce web applications, customer experience can NEVER be neglected. One of the most important things that we need to do to improve customer experience is to keep products that the customer added to cart intact, unless they buy or remove these products themselves.

In this article, I’m going to  show you how you can keep products inside customers cart, even if they close the browser by using Laravel e-commerce project. First of all, in order to keep the products inside the cart you can use two approaches:

The first one is  by creating a “carts” table and store user_id and the selected products using its ids (I’ll explain that in detail shortly). Nevertheless, there is a much easier approach, that’s increasing session lifetime, so it will store cart items for a longer time than normal.

1. First Approach: Increasing Session Lifetime

So how can you increase session lifetime so that it stores cart items for a very long time?

Well, it’s super simple. Just as I taught you how to use sessions in the Laravel e-commerce store course, you can head on over to the configuration folder “config” and open up the session.php file

“config/session.php”

Then open the “session.php”file.

By default, Laravel sets the session lifetime to only 2 hours (120 minuets).

Now increase that number (which is the session lifetime in minutes) you can increase it to a big number, hence, if the user comes back after weeks, they will still find there products in cart!

This approach is much easier than creating a table to store cart items. Because we would not have to make requests to our own server each time user changes Cart products.

However, I’m going to show you how to use the other method, which is creating “carts” table to store customers products as long as they do not pay and buy.

 

2. Second Approach: Create a Table to Store Cart Items

The first step is to create a table called “carts”. You can simply head on over to PhpMyAdmin and create that table and it should have the following fields:

id (int),    user_id (varchar),    product_id (int),   quantity (int),   totalSinglePrice (float),    created_at(text),    updated _at(text)

Then each time a customer adds a product, we need to store that product id in the “carts” table. So all the work will be in the controller ProductsController.php

********* (The user MUST be logged in, in order to be able to use Auth class)*****

*******(if the user is a Guest -not logged in- then you can use their IP address as a unique id. In such a case, you would have to replace each Auth::user()->id with $request->ip()  in the code below in order to user their ip address) ******

First, if the user adds product to cart then we have got to store that product in “carts” table


  public function addProductToCart(Request $request,$id){

        $productAlreadyAdded = DB::table('carts')->where('user_id', Auth::user()->id)->where('product_id',$id)->exists();

            if($productAlreadyAdded == true){

                        $product = DB::table('carts')->where('user_id', Auth::user()->id)->where('product_id',$id)->get()[0];
                                
                        $updatedQuantity = $product->quantity+1;
                        $updatedTotalSinglePrice = $product->totalSinglePrice * $updatedQuantity;
            
                        DB::table('carts')->where('user_id',Auth::user()->id)->where('product_id',$id)->update(['quantity'=>$updatedQuantity, 'totalSinglePrice'=>$updatedTotalSinglePrice]);
                }else{
                        $product = Product::find($id);
                        DB::table('carts')->insert(['user_id'=> Auth::user()->id, 'product_id'=>$id, 'quantity'=>1, 'totalSinglePrice'=>$product->price]);
                    
                }
            

        return redirect()->back()->with('msg','The Item has been added to Cart');

if the user decided to buy, then we gotta delete all their products from cart


 public function createNewOrder(Request $request){
        $cartItems = DB::table('carts')->where('user_id',Auth::user()->id)
        ->join('products','carts.product_id','=','products.id')->get();

        //cart is not empty
        $cartItems->totalQuantity = $cartItems->sum('quantity');
        $cartItems->totalPrice = $cartItems->sum('totalSinglePrice');
        
       $first_name = $request->input('first_name');
       $address = $request->input('address');
       $last_name = $request->input('last_name');
       $zip = $request->input('zip');
       $phone = $request->input('phone');
       $email = $request->input('email');


     $isUserLoggedIn = Auth::check();
     if($isUserLoggedIn){
          $user_id = Auth::id(); //OR $user_id = Auth::user()->id;
     }else{
     
        $user_id = 0;
     
     }
  

        //cart is not empty
        if($cartItems) {
           //dd($cartItems);
            $date = date('Y-m-d H:i:s');
            $newOrderArray = array("user_id"=> $user_id,"status"=>"on_hold","date"=>$date,"del_date"=>$date,"price"=>$cartItems->totalPrice,
            "first_name"=>$first_name, "address"=> $address, 'last_name'=>$last_name, 'zip'=>$zip,'email'=>$email,'phone'=>$phone);
            
            $created_order = DB::table("orders")->insert($newOrderArray);
            $order_id = DB::getPdo()->lastInsertId();;


            foreach ($cartItems as $item){
                $item_id = $item->id;
                $item_name = $item->name;
                $item_price = $item->price;
                $newItemsInCurrentOrder = array("item_id"=>$item_id,"order_id"=>$order_id,"item_name"=>$item_name,"item_price"=>$item_price);
                $created_order_items = DB::table("order_items")->insert($newItemsInCurrentOrder);
            }

          
          
            
             $payment_info = $newOrderArray;
             $payment_info['order_id'] = $order_id;
             $request->session()->put('payment_info', $payment_info);
             DB::table('carts')->where('user_id',Auth::user()->id)->delete();
        
            
         return redirect()->route("showPaymentPage");

        }else{

           return redirect()->route("allProducts");

        
        }


    }


 

If the customer removes a single item from the cart then we gotta make a query that removes that item from “carts” table


    public function deleteItemFromCart(Request $request,$id){
         DB::table('carts')->where(['user_id'=>Auth::user()->id, 'product_id'=>$id])->delete();
        return redirect()->route('cartproducts');
    }

To display all cart products


    public function showCart(){
      $cart = DB::table('carts')->where('user_id',Auth::user()->id)
                ->join('products','carts.product_id','=','products.id')->get();

       //cart is not empty
       $cart->totalQuantity = $cart->sum('quantity');
        $cart->totalPrice = $cart->sum('totalSinglePrice');

        if($cart){
            return view('cartproducts',['cartItems'=> $cart]);
         //cart is empty
        }else{
            return redirect()->route("allProducts");
        }

    }

As you can see both methods will lead to the same goal, that is, the user will have great experience. Remember that consistent improvement to customer experience would lead to more happy and satisfied customers and obviously more sales. If you want the complete code please let me know and I’ll send it to you.

close

Learn the 4 Secrets to Becoming a Professional Freelance Programmer!

Get Your Free E-Book Now!

Leave a Reply

Your email address will not be published. Required fields are marked *