laravel shopping cart – Best 7 Steps to Add to Cart and Checkout Code in Laravel

laravel shopping cart : In this article i will sample demonstrate how to create a shopping cart with php using laravel framework. i will be using laravel 5.6 but you can also use any other latest version.

laravel shopping cart

laravel shopping cart – here you can learn to step by step Creating a Shopping Cart With Laravel. This is best article of the Laravel E-Commerce Application Development step by step also i will start implementing the laravel shopping cart step by step without Install Shopping Cart Package.

Step 1: Installation

In your local development path type this command to install laravel 5.6.

composer create-project laravel/laravel shopping-basket  "5.6.*" --prefer-dist

And then step by step successful installation be sure that there is a created a“.env” file in the root path of the web application. If not then take a copy of “.env.example” after that this file simply rename it to “.env” then in type this command in the terminal.

php artisan key:generate

Now laravel shopping cart – laravel successfully installed and you can be sure by visiting http://your-domain-name.com/shopping-basket/public/.

Step 2: Preparing Database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shopping_basket
DB_USERNAME=<your db username>
DB_PASSWORD=<your db password>

Next we will be using laravel migration to create tables so ype this command in terminal.

php artisan make:model Item -m

The above command will make a Item model and -m for migration.

Now go to database > migrations and open up the migration we just created for items table.

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}

I will be adding some more fields to the up() function therefor add this php laravel source code after $table->increments(‘id’)

$table->string("name", 255)->nullable();
$table->text("information")->nullable();
$table->string("item_img", 255)->nullable();
$table->decimal("price", 6, 2);

Now migrate your tables by this command:

php artisan migrate

Now let’s create a Seeder to populate our items table with some data to work with. Run this command to generate a seeder.

php artisan make:seed ItemsSeeder

Go to database>seeds>ItemsSeeder. Then inside run() function add this code.

DB::table('items')->insert([
           'name' => 'Apple Galaxy S9',
           'information' => 'Laptops : Shop for laptops & mini laptops online at best prices in India at Amazon​.in. Get Free 1 or 2 day delivery with Amazon Prime',
           'item_img' => 'https://i.ebayimg.com/00/s/ODY0WDgwMA==/z/9S4AAOSwMZRanqb7/$_35.JPG?set_id=89040003C1',
           'price' => 7878.88
        ]);
        DB::table('items')->insert([
            'name' => 'Apple iPhone X',
            'information' => 'Laptop Prices in India - Buy Laptops Online at Lowest Prices on Flipkart.com Choose from a wide range of Laptops from best brands like HP, Dell, Lenovo, Acer',
            'item_img' => 'https://i.ebayimg.com/00/s/MTYwMFg5OTU=/z/9UAAAOSwFyhaFXZJ/$_35.JPG?set_id=89040003C1',
            'price' => 7778.00
        ]);
        DB::table('items')->insert([
            'name' => 'Dell Pixel 2 XL',
            'information' => 'Get the best Laptops Online from Reliance Digital. Shop from top Laptop Brands like Apple, HP, Lenovo, Microsoft, Dell, iBall & more.',
            'item_img' => 'https://i.ebayimg.com/00/s/MTYwMFg4MzA=/z/G2YAAOSwUJlZ4yQd/$_35.JPG?set_id=89040003C1',
            'price' => 7587.00
        ]);
        DB::table('items')->insert([
            'name' => 'Asser V10 H900',
            'information' => 'A laptop, laptop computer, or notebook computer is a small, portable personal computer (PC) with a screen and alphanumeric keyboard. ',
            'item_img' => 'https://i.ebayimg.com/00/s/NjQxWDQyNA==/z/VDoAAOSwgk1XF2oo/$_35.JPG?set_id=89040003C1',
            'price' => 7852.99
        ]);
        DB::table('items')->insert([
            'name' => 'Iphone Elate',
            'information' => 'Planning for Online Mobile Shopping? Visit us now to explore mobile phones including mobile prices, reviews, comparisons, features, videos, accessories',
            'item_img' => 'https://ssli.ebayimg.com/images/g/aJ0AAOSw7zlaldY2/s-l640.jpg',
            'price' => 5288.00
        ]);
        DB::table('items')->insert([
            'name' => 'HTC One M10',
            'information' => 'Buy latest Mobile Phones at best prices online at Croma.Com. Choose smartphones from brands like Apple, Samsung, MI, OnePlus and get best.',
            'item_img' => 'https://i.ebayimg.com/images/g/u-kAAOSw9p9aXNyf/s-l500.jpg',
            'price' => 7845.99
        ]);

Now run this command to seed your data.

php artisan db:seed --class=ItemsSeeder

Don’t Miss : PHP Shopping Cart

Step 3: Controller & Views

Let’s create a controller for our items and basket called “ItemsController”.

php artisan make:controller ItemsController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Item;
class ItemsController extends Controller
{
}

Now these actions in the above controller as shown:

    public function index()
    {
        return view('items');
    }
    public function basket()
    {
        return view('basket');
    }
    public function addToCart($id)
    {
    }

In the above code we created two actions for our items and basket pages and one action for add to basket.

Read Also:  crud operations in php using mysqli - PHP Crud Operations - Select, Insert, Update, Delete - PHP Tutorial For Beginners

Next we will create three views with dummy data:

  • layout.blade.php: this is the main layout view.
  • items.blade.php: this is the view that will display our items.
  • basket.blade.php: this is the basket view.

In the layout.blade.php simple copy and paste this source code.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>@yield('title')</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12 col-sm-12 col-12 main-section">
            <div class="dropdown">
                <button type="button" class="btn btn-info" data-toggle="dropdown">
                    <i class="fa fa-shopping-basket" aria-hidden="true"></i> Cart <span class="badge badge-pill badge-danger">3</span>
                </button>
                <div class="dropdown-menu">
                    <div class="row total-header-section">
                        <div class="col-lg-6 col-sm-6 col-6">
                            <i class="fa fa-shopping-basket" aria-hidden="true"></i> <span class="badge badge-pill badge-danger">3</span>
                        </div>
                        <div class="col-lg-6 col-sm-6 col-6 total-section text-right">
                            <p>Total: <span class="text-info">$2,978.24</span></p>
                        </div>
                    </div>
                    <div class="row basket-info">
                        <div class="col-lg-4 col-sm-4 col-4 basket-info-img">
                            <img src="https://images-na.ssl-images-amazon.com/images/I/811OyrCd5hL._SX425_.jpg">
                        </div>
                        <div class="col-lg-8 col-sm-8 col-8 basket-info-item">
                            <p>Sony DSC-RX100M..</p>
                            <span class="price text-info"> $250.22</span> <span class="count"> Quantity:01</span>
                        </div>
                    </div>
                    <div class="row basket-info">
                        <div class="col-lg-4 col-sm-4 col-4 basket-info-img">
                            <img src="https://cdn2.gsmarena.com/vv/pics/blu/blu-vivo-48-1.jpg">
                        </div>
                        <div class="col-lg-8 col-sm-8 col-8 basket-info-item">
                            <p>Vivo DSC-RX100M..</p>
                            <span class="price text-info"> $500.40</span> <span class="count"> Quantity:01</span>
                        </div>
                    </div>
                    <div class="row basket-info">
                        <div class="col-lg-4 col-sm-4 col-4 basket-info-img">
                            <img src="https://static.toiimg.com/thumb/msid-55980052,width-640,resizemode-4/55980052.jpg">
                        </div>
                        <div class="col-lg-8 col-sm-8 col-8 basket-info-item">
                            <p>Lenovo DSC-RX100M..</p>
                            <span class="price text-info"> $445.78</span> <span class="count"> Quantity:01</span>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-12 col-sm-12 col-12 text-center checkout">
                            <a href="{{ url('basket') }}" class="btn btn-primary btn-block">View all</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container page">
    @yield('content')
</div>
@yield('scripts')
</body>
</html>

As shown in the above code we have included bootstrap and jquery and the main style.css file and in the template header we displayed the basket icon along with sample dummy data.

items.blade.php

@extends('layout')
@section('title', 'Items')
@section('content')
    <div class="container items">
        <div class="row">
            <div class="col-xs-18 col-sm-6 col-md-3">
                <div class="thumbnail">
                    <img src="http://placehold.it/500x300" alt="">
                    <div class="caption">
                        <h4>Item name</h4>
                        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p>
                        <p><strong>Price: </strong> 567.7$</p>
                        <p class="btn-holder"><a href="#" class="btn btn-warning btn-block text-center" role="button">Add to cart</a> </p>
                    </div>
                </div>
            </div>
            <div class="col-xs-18 col-sm-6 col-md-3">
                <div class="thumbnail">
                    <img src="http://placehold.it/500x300" alt="">
                    <div class="caption">
                        <h4>Item name</h4>
                        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p>
                        <p><strong>Price: </strong> 567.7$</p>
                        <p class="btn-holder"><a href="#" class="btn btn-warning btn-block text-center" role="button">Add to cart</a> </p>
                    </div>
                </div>
            </div>
            <div class="col-xs-18 col-sm-6 col-md-3">
                <div class="thumbnail">
                    <img src="http://placehold.it/500x300" alt="">
                    <div class="caption">
                        <h4>Item name</h4>
                        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p>
                        <p><strong>Price: </strong> 567.7$</p>
                        <p class="btn-holder"><a href="#" class="btn btn-warning btn-block text-center" role="button">Add to cart</a> </p>
                    </div>
                </div>
            </div>
            <div class="col-xs-18 col-sm-6 col-md-3">
                <div class="thumbnail">
                    <img src="http://placehold.it/500x300" alt="">
                    <div class="caption">
                        <h4>Item name</h4>
                        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p>
                        <p><strong>Price: </strong> 567.7$</p>
                        <p class="btn-holder"><a href="#" class="btn btn-warning btn-block text-center" role="button">Add to cart</a> </p>
                    </div>
                </div>
            </div>
        </div><!-- End row -->
    </div>
@endsection

basket.blade.php

@extends('layout')
@section('title', 'Cart')
@section('content')
    <table id="basket" class="table table-hover table-condensed">
        <thead>
        <tr>
            <th style="width:50%">Item</th>
            <th style="width:10%">Price</th>
            <th style="width:8%">Quantity</th>
            <th style="width:22%" class="text-center">Subtotal</th>
            <th style="width:10%"></th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td data-th="Item">
                <div class="row">
                    <div class="col-sm-3 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div>
                    <div class="col-sm-9">
                        <h4 class="nomargin">Item 1</h4>
                        <p>Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet.</p>
                    </div>
                </div>
            </td>
            <td data-th="Price">$1.99</td>
            <td data-th="Quantity">
                <input type="number" class="form-control text-center" value="1">
            </td>
            <td data-th="Subtotal" class="text-center">1.99</td>
            <td class="actions" data-th="">
                <button class="btn btn-info btn-sm"><i class="fa fa-refresh"></i></button>
                <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
            </td>
        </tr>
        </tbody>
        <tfoot>
        <tr class="visible-xs">
            <td class="text-center"><strong>Total 1.99</strong></td>
        </tr>
        <tr>
            <td><a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
            <td colspan="2" class="hidden-xs"></td>
            <td class="hidden-xs text-center"><strong>Total $1.99</strong></td>
        </tr>
        </tfoot>
    </table>
@endsection

style.css

.main-section{
    background-color: #F8F8F8;
}
.dropdown{
    float:right;
    padding-right: 30px;
}
.btn{
    border:0px;
    margin:10px 0px;
    box-shadow:none !important;
}
.dropdown .dropdown-menu{
    padding:20px;
    top:30px !important;
    width:350px !important;
    left:-110px !important;
    box-shadow:0px 5px 30px black;
}
.total-header-section{
    border-bottom:1px solid #d2d2d2;
}
.total-section p{
    margin-bottom:20px;
}
.basket-info{
    padding:15px 0px;
}
.basket-info-img img{
    width:100%;
    height:100%;
    padding-left:15px;
}
.basket-info-item p{
    margin:0px;
    color:#000;
    font-weight:500;
}
.basket-info .price{
    font-size:12px;
    margin-right:10px;
    font-weight:500;
}
.basket-info .count{
    color:#C2C2DC;
}
.checkout{
    border-top:1px solid #d2d2d2;
    padding-top: 15px;
}
.checkout .btn-primary{
    border-radius:50px;
    height:50px;
}
.dropdown-menu:before{
    content: " ";
    position:absolute;
    top:-20px;
    right:50px;
    border:10px solid transparent;
    border-bottom-color:#fff;
}
.thumbnail {
    position: relative;
    padding: 0px;
    margin-bottom: 20px;
}
.thumbnail img {
    width: 100%;
}
.thumbnail .caption{
    margin: 7px;
}
.page {
    margin-top: 50px;
}
.btn-holder{
    text-align: center;
}
.table>tbody>tr>td, .table>tfoot>tr>td{
    vertical-align: middle;
}
@media screen and (max-width: 600px) {
    table#basket tbody td .form-control{
        width:20%;
        display: inline !important;
    }
    .actions .btn{
        width:36%;
        margin:1.5em 0;
    }
    .actions .btn-info{
        float:left;
    }
    .actions .btn-danger{
        float:right;
    }
    table#basket thead { display: none; }
    table#basket tbody td { display: block; padding: .6rem; min-width:320px;}
    table#basket tbody tr td:first-child { background: #333; color: #fff; }
    table#basket tbody td:before {
        content: attr(data-th); font-weight: bold;
        display: inline-block; width: 8rem;
    }
    table#basket tfoot td{display:block; }
    table#basket tfoot td .btn{display:block;}
}

Don’t Miss : Vue Shopping Cart

Read Also:  How to Open URL in New Tab using Laravel

Step 4: Routes for laravel shopping cart

At this point go to routes > web.php and add the following routes:

<?php
/*
|--------------------------------------------------------------------------
| Web Routes - laravel shopping cart
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', '[email protected]');
Route::get('basket', '[email protected]');
Route::get('add-to-basket/{id}', '[email protected]');

Now visit http://your-domain-name.com/shopping-basket/public/ and http://your-domain-name.com/shopping-basket/public/basket you will see our items and basket page respectively.

Displaying Items

Go to ItemsController.php in the index function add the below source code

public function index()
    {
        $items = Item::all();
        return view('items', compact('items'));
    }

Here i fetch all items as well as sent them to the items view.

for “laravel shopping cart” – Now go to resources > views > items.blade.php as well as replace the sample data with the below source code

@extends('layout')
@section('title', 'Items')
@section('content')
    <div class="container items">
        <div class="row">
            @foreach($items as $item)
                <div class="col-xs-18 col-sm-6 col-md-3">
                    <div class="thumbnail">
                        <img src="{{ $item->item_img }}" width="500" height="300">
                        <div class="caption">
                            <h4>{{ $item->name }}</h4>
                            <p>{{ str_limit(strtolower($item->information), 50) }}</p>
                            <p><strong>Price: </strong> {{ $item->price }}$</p>
                            <p class="btn-holder"><a href="{{ url('add-to-basket/'.$item->id) }}" class="btn btn-warning btn-block text-center" role="button">Add to cart</a> </p>
                        </div>
                    </div>
                </div>
            @endforeach
        </div><!-- End row -->
    </div>
@endsection

Great work now you can see the actual items by going to http://your-domain-name.com/shopping-basket/public/

Step 5: Processing the basket

Now this is time to add logic for when user clicks on add to basket button. I will do this in the addToCart function in ItemsController.php and i will store the basket item using laravel session.

public function addToCart($id)
    {
        $item = Item::find($id);
        if(!$item) {
            abort(404);
        }
        $basket = session()->get('basket');
        // if basket is empty then this the first item
        if(!$basket) {
            $basket = [
                    $id => [
                        "name" => $item->name,
                        "item_qty" => 1,
                        "price" => $item->price,
                        "item_img" => $item->item_img
                    ]
            ];
            session()->put('basket', $basket);
            return redirect()->back()->with('success', 'Item added to basket successfully!');
        }
        // if basket not empty then check if this item exist then increment item_qty
        if(isset($basket[$id])) {
            $basket[$id]['item_qty']++;
            session()->put('basket', $basket);
            return redirect()->back()->with('success', 'Item added to basket successfully!');
        }
        // if item not exist in basket then add to basket with item_qty = 1
        $basket[$id] = [
            "name" => $item->name,
            "item_qty" => 1,
            "price" => $item->price,
            "item_img" => $item->item_img
        ];
        session()->put('basket', $basket);
        return redirect()->back()->with('success', 'Item added to basket successfully!');
    }

In the above source code first i fetch the item and checked if it exist or not then i check if there is a basket exist in the session.

If basket is empty then i treated the item as the first item and insert it along with item_qty and price.

If basket not empty i checked if the item already exist and increment its item_qty.

Step 6: Displaying the basket contents

At this point i have a basket with items let’s display it in the basket view.

Go to resources > views > basket.blade.php and update the view with below source code:

@extends('layout')
@section('title', 'Cart')
@section('content')
    <table id="basket" class="table table-hover table-condensed">
        <thead>
        <tr>
            <th style="width:50%">Item</th>
            <th style="width:10%">Price</th>
            <th style="width:8%">Quantity</th>
            <th style="width:22%" class="text-center">Subtotal</th>
            <th style="width:10%"></th>
        </tr>
        </thead>
        <tbody>
        <?php $total = 0 ?>
        @if(session('basket'))
            @foreach(session('basket') as $id => $infos)
                <?php $total += $infos['price'] * $infos['item_qty'] ?>
                <tr>
                    <td data-th="Item">
                        <div class="row">
                            <div class="col-sm-3 hidden-xs"><img src="{{ $infos['item_img'] }}" width="100" height="100" class="img-responsive"/></div>
                            <div class="col-sm-9">
                                <h4 class="nomargin">{{ $infos['name'] }}</h4>
                            </div>
                        </div>
                    </td>
                    <td data-th="Price">${{ $infos['price'] }}</td>
                    <td data-th="Quantity">
                        <input type="number" value="{{ $infos['item_qty'] }}" class="form-control item_qty" />
                    </td>
                    <td data-th="Subtotal" class="text-center">${{ $infos['price'] * $infos['item_qty'] }}</td>
                    <td class="actions" data-th="">
                        <button class="btn btn-info btn-sm update-basket" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
                        <button class="btn btn-danger btn-sm remove-from-basket" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
                    </td>
                </tr>
            @endforeach
        @endif
        </tbody>
        <tfoot>
        <tr class="visible-xs">
            <td class="text-center"><strong>Total {{ $total }}</strong></td>
        </tr>
        <tr>
            <td><a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
            <td colspan="2" class="hidden-xs"></td>
            <td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
        </tr>
        </tfoot>
    </table>
@endsection

And also update the main layout view page layout.blade.php

<!DOCTYPE html>
<html>
<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>@yield('title') - laravel shopping cart</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">

    <div class="row">
        <div class="col-lg-12 col-sm-12 col-12 main-section">
            <div class="dropdown">
                <button type="button" class="btn btn-info" data-toggle="dropdown">
                    <i class="fa fa-shopping-basket" aria-hidden="true"></i> Cart <span class="badge badge-pill badge-danger">{{ count((array) session('basket')) }}</span>
                </button>
                <div class="dropdown-menu">
                    <div class="row total-header-section">
                        <div class="col-lg-6 col-sm-6 col-6">
                            <i class="fa fa-shopping-basket" aria-hidden="true"></i> <span class="badge badge-pill badge-danger">{{ count((array) session('basket')) }}</span>
                        </div>

                        <?php $total = 0 ?>
                        @foreach((array) session('basket') as $id => $infos)
                            <?php $total += $infos['price'] * $infos['item_qty'] ?>
                        @endforeach

                        <div class="col-lg-6 col-sm-6 col-6 total-section text-right">
                            <p>Total: <span class="text-info">$ {{ $total }}</span></p>
                        </div>
                    </div>

                    @if(session('basket'))
                        @foreach(session('basket') as $id => $infos)
                            <div class="row basket-info">
                                <div class="col-lg-4 col-sm-4 col-4 basket-info-img">
                                    <img src="{{ $infos['item_img'] }}" />
                                </div>
                                <div class="col-lg-8 col-sm-8 col-8 basket-info-item">
                                    <p>{{ $infos['name'] }}</p>
                                    <span class="price text-info"> ${{ $infos['price'] }}</span> <span class="count"> Quantity:{{ $infos['item_qty'] }}</span>
                                </div>
                            </div>
                        @endforeach
                    @endif
                    <div class="row">
                        <div class="col-lg-12 col-sm-12 col-12 text-center checkout">
                            <a href="{{ url('basket') }}" class="btn btn-primary btn-block">View all</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container page">
    @yield('content')
</div>

@yield('scripts')

</body>
</html>

Step 7: Updating & removing from the basket

Last step to remove/delete or update an item in the basket we will create two actions in the ItemsController as follows:

public function update(Request $request)
    {
        if($request->id and $request->item_qty)
        {
            $basket = session()->get('basket');
            $basket[$request->id]["item_qty"] = $request->item_qty;
            session()->put('basket', $basket);
            session()->flash('success', 'Your Cart updated successfully');
        }
    }
    public function remove(Request $request)
    {
        if($request->id) {
            $basket = session()->get('basket');
            if(isset($basket[$request->id])) {
                unset($basket[$request->id]);
                session()->put('basket', $basket);
            }
            session()->flash('success', 'Item removed successfully');
        }
    }

Let’s make main 2 other web routes

Read Also:  Server-side processing Laravel DataTables

Route::patch('update-basket', '[email protected]');
Route::delete('remove-from-basket', '[email protected]');

Now go to resources > views > basket.blade.php and add this full source code at the bottom

@section('scripts')
    <script type="text/javascript">
        $(".update-basket").click(function (e) {
           e.preventDefault();
           var ele = $(this);
            $.ajax({
               url: '{{ url('update-basket') }}',
               method: "patch",
               data: {_token: '{{ csrf_token() }}', id: ele.attr("data-id"), item_qty: ele.parents("tr").find(".item_qty").val()},
               success: function (response) {
                   window.location.reload();
               }
            });
        });
        $(".remove-from-basket").click(function (e) {
            e.preventDefault();
            var ele = $(this);
            if(confirm("Are you sure")) {
                $.ajax({
                    url: '{{ url('remove-from-basket') }}',
                    method: "DELETE",
                    data: {_token: '{{ csrf_token() }}', id: ele.attr("data-id")},
                    success: function (response) {
                        window.location.reload();
                    }
                });
            }
        });
    </script>
@endsection

As shown above I added main 2 types of the listeners for buttons update as well as remove and for each button just send jquery ajax request to update and remove items.

laravel shopping cart
laravel shopping cart

I hope you get an idea about laravel shopping cart.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.