The Shopping cart – How to craft a e-shop with Laravel

In this second part of the tutorial we will see how to create the shopping cart for our e-shop. The cart will be associated to the customer and stored into the database. Using this approach a customer that will leave our shop and come back after some time will found his cart as he left it.

The first thing we need to create is the forms to let the customer signing up an login the application. All the releative logic is already present in the Laravel basic application, we only need to define the view and the routes.

Let start by creating  a new folder into the view and call it auth. Inside this folder create two files register.blade.php and login.blade.php

The code for both files is below, copy and paste it

Once both register and login view is in place will be enough to define the auth routes to make the login and register process working. Paste the code below into the routes.php file

Now if you run the application you will be able to register, login and logout as a customer. The link to the register and login form was already coded into the template file in the navbar. The result will be something like show in the picture.

Schermata 2015-09-15 alle 20.31.02

As you can see, as soon as you register a new user its redirected to http://localhost:8000/home, but it’s different from our home page. To change this behaviour a simple variable declaration is needed into the AuthController.php file. Add the line below to the controller and after login or register you will be redirected to the product catalog.

The shopping cart

As we said at the begin of the tutorial the shopping cart will be store in the database. To make it possible we need two tables. Create the migration files for both tables using artisan command line :

php artisan make:migration create_table_carts

php artisan make:migration create_table_carts_item

The first table cart will be used to store cart basic information and the relation with the customer

The second table will contain for each row the relation with a product and the cart.

As we created the database table we need now the models to represent the entity in our application.

php artisan make:model Cart

php artisan make:model CartItem

Like specified in the table definition, we have to define the relation also in the model class. The Cart model belong to a User and have many CartItem.

Different from the Cart the CartItem model belong both to the Cart and the Product.

To take things separated all the function relative to the cart operation will be defined in a CartController. Create it by using artisan

php artisan make:controller CartController

Let explain the code of the CartController. As you can see the first method is the _construct. Here we instruct this controller to use always the auth middleware. This is needed because we want only the logged in customer to view the cart and add product to it.

The second function is the AddItem. This function first search for the cart associated to the currently logged user. If the retrieve fails, mean this is the first time the user use the cart, so we need to create a new instance of it and save to the database. Once we have the Cart instance a new CartItem is created and associated to it and to the product_id passed as the function argument. When the product is added to the cart a redirect is performed to the /cart url.

The /cart route will be served by the showCart function. This function, like the addProduct retrieve the Cart associated to the user from the database, if not present it create it. Then it loop trough all the items in the cart to calculate the total price and return a view passing the $item array and the calculated $total.

Last functin is the removeItem, basically it destroy the CartItem row in the database and the relation with the Cart.

Just a single view is needed to represent the shopping cart and the code for it is reported below, create a cart folder and a view.blade.php file and paste the code below into it :

In the view we basically loop through the $items array and for each a table row is created with the product information and a remove button pointing to the right function with the right parameter. At the bottom a checkout and continue shopping buttons complete the view.Schermata 2015-09-15 alle 21.14.39

As always we need to define the route to the controller functions. Paste the code below :

Now if you test the application, after the user login you will be able to put products in the shopping cart and remove it. If you log out the user the bars button will disappear and you cannot access anymore the cart. Once the customer come back and log again to the shop it will get the same cart left when logged out.

Our shop is almost done in every basic part. We just need a way to pay goods and transform the cart into an order where the user get the link to download the products he bought. We will see this in the next part of the tutorial.


  • A.latheef Abdul wajeeth

    very helpful tutorial Thank you so much.
    can you upload admin login panel for this tutorial?

  • Aquino Tegar

    so, where’s the next tutorial?

  • bima

    where the authcontroller login&register function??

  • If you could help me for a quick min i would appreciate it. I am having trouble with the cart controller.

    public function addItem ($productId){

    $cart = Cart::where('user_id', Sentinel::getUser()->id)->first();

    if(!$cart){

    $cart = new Cart();

    $cart->user_id=Sentinel::getUser()->id;

    $cart->save();

    }

    $cartItem = new Cartitem();

    $cartItem->product_id=$productId;

    $cartItem->cart_id= $cart->id;

    $cartItem->save();

    return redirect('/shop/cart');

    }

    public function cart(){

    $cart = Cart::where('user_id', Sentinel::getUser()->id)->first();

    if(!$cart){

    $cart = new Cart();

    $cart->user_id=Sentinel::getUser()->id;

    $cart->save();

    }

    $items = $cart->cartItems;

    $total=0;

    foreach($items as $item){

    $total+=$item->product->price;

    }

    return view('frontend.shop.cart',['items'=>$items,'total'=>$total]);

    }

    It will not add products to the cart can you see an error in my code?

    • Kishan Kalariya

      you write a new code for add to cart:-

      public function insertcart(Request $request,$id)

      {

      $users=DB::select(‘select * from products where pid=?’,[$id]);

      $pid=$users[0]->pid;

      $qty=1;

      $photo=$users[0]->photo;

      $price=$users[0]->price;

      $total=$price;

      $date=date(‘Y-m-d’);

      $uid=12;

      DB::insert(‘insert into tempcart (pid,photo,qty,price,total,date,uid) values(?,?,?,?,?,?,?)’, [$pid,$photo,$qty,$price,$total,$date,$uid]);

      return redirect(‘/cart’);

      }

      any help my email:-kishankalariya111@gmail.com

Shares
Share This

Share This

Share this post with your friends!

Shares