Laravel Add to Cart Example Using Ajax Request

Hello devs

In this brand new tutorial i am going to show you that how we can create a add to cart system in laravel using ajax request. From this laravel add to cart tutorial, you will learn, add to cart, update cart using ajax request and finaly delete or remove cart using page refresh.

You know that for an ecommerce website this cart system is a core part part or main feature of this website. We can create add to cart system using many packages like laravel shopping cart. But in this example i am going to create this cart system without package and using ajax request.

So from this laravel add to cart ajax tutorial, i will show you, update quantity shopping cart laravel using ajax and also show you add to cart remove from cart without refreshing the page in laravel. 

Hope you will enjoy this tutorial. I will show you from scratch or step by step so that you can understand better and use this code in your laravel project. In this example i will use seeder to create some dummy products.

 

Step 1: Install Laravel

In this first step we need to get fresh Laravel 8 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

 

Step 2: Create Table, Seeder and Model

In this second step, we need to create products table, model and add some dummy records with seeder.

Create Migration

php artisan make:migration create_products_table

 

Update the database migration file like below:

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

  

class CreateProductsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name", 255)->nullable();
            $table->text("description")->nullable();
            $table->string("image", 255)->nullable();
            $table->decimal("price", 6, 2);
            $table->timestamps();
        });
    }

 

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('products');

    }

}

 

Run this command to migrate:

php artisan migrate

 

Create Model

Run bellow command for creating Product model:

php artisan make:model Product

 

Update model like:

app/Models/Products.php

namespace App\Models;

   

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

  

class Product extends Model

{

    use HasFactory;

    protected $fillable = [
        'name', 'price', 'description', 'image'
    ];

}

 

Create Seeder

Now in this step run bellow command to create Product seeder:

php artisan make:seed ProductSeeder

 

After running the command, update product seeder like that:

database/seeders/ProductSeeder.php

namespace Database\Seeders;

  

use Illuminate\Database\Seeder;

use App\Models\Product;

  

class ProductSeeder extends Seeder

{

    /**

     * Run the database seeds.

     *

     * @return void

     */

    public function run()

    {

        $products = [
            [
                'name' => 'Samsung Galaxy',
                'description' => 'Samsung Brand',
                'image' => 'https://dummyimage.com/200x300/000/fff&text=Samsung',
                'price' => 100
            ],

            [
                'name' => 'Apple iPhone 12',
                'description' => 'Apple Brand',
                'image' => 'https://dummyimage.com/200x300/000/fff&text=Iphone',
                'price' => 500
            ],

            [
                'name' => 'Google Pixel 2 XL',
                'description' => 'Google Pixel Brand',
                'image' => 'https://dummyimage.com/200x300/000/fff&text=Google',
                'price' => 400

            ],

            [
                'name' => 'LG V10 H800',
                'description' => 'LG Brand',
                'image' => 'https://dummyimage.com/200x300/000/fff&text=LG',
                'price' => 200
            ]
        ];


        foreach ($products as $key => $value) {
            Product::create($value);
        }

    }

}

 

Now in this step we have to run our product seeder. So run it.

php artisan db:seed --class=ProductSeeder

 

Step 3: Create Route

In this third step we need to create some routes for add to cart function.

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::get('/', [ProductController::class, 'index']);  
Route::get('cart', [ProductController::class, 'cart'])->name('cart');
Route::get('add-to-cart/{id}', [ProductController::class, 'addToCart'])->name('add.to.cart');
Route::patch('update-cart', [ProductController::class, 'update'])->name('update.cart');
Route::delete('remove-from-cart', [ProductController::class, 'remove'])->name('remove.from.cart');

 

Step 4: Create Controller

in this fourth step, we need to create ProductController and add following code on that file:

app/Http/Controllers/ProductController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller

{
    public function index()

    {
        $products = Product::all();
        return view('products', compact('products'));
    }

  

    public function cart()

    {
        return view('cart');
    }


    public function addToCart($id)

    {
        $product = Product::findOrFail($id);
        $cart = session()->get('cart', []);

        if(isset($cart[$id])) {
            $cart[$id]['quantity']++;

        } else {

            $cart[$id] = [

                "name" => $product->name,
                "quantity" => 1,
                "price" => $product->price,
                "image" => $product->image
            ];
        }

        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }

  
    public function update(Request $request)

    {

        if($request->id && $request->quantity){
            $cart = session()->get('cart');
            $cart[$request->id]["quantity"] = $request->quantity;
            session()->put('cart', $cart);
            session()->flash('success', 'Cart updated successfully');
        }
    }

  

    public function remove(Request $request)
    {
        if($request->id) {
            $cart = session()->get('cart');
            if(isset($cart[$request->id])) {
                unset($cart[$request->id]);
                session()->put('cart', $cart);
            }
            session()->flash('success', 'Product removed successfully');
        }
    }
}

 

Step 5: Create Blade Files

Almost all are set to go. Just now we need to create blade files for layout, products and cart page. so let's create one by one files:

resources/views/layout.blade.php

 

resources/views/products.blade.php

 

And finally our cart file need to be updated like that:

resources/views/cart.blade.php

 

Now everything is set to go and we are ready to run our example so run bellow command so quick run:

php artisan serve

 

And visit this following url:

 

url
http://localhost:8000

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js