Laravel 10 : Xây dựng giỏ hàng với session

Laravel 10 : Xây dựng giỏ hàng với session

Xây dựng giỏ hàng là 1 phần quan trọng trong mỗi website : người dùng có thể tương tác mua các sản phẩm trong website với giỏ hàng .Mặc dù có rất nhiều package xây dựng giỏ hàng nhưng hôm nay mình sẽ code đơn giản giỏ hàng để hiểu về cơ chế và quy tắc

1 Cài đặt laravel

Đầu tiên chúng ta cài đặt laravel với terminal :

composer create-project laravel/laravel laravel10giohang

2 Tạo product 

Ở đây chúng ta tạo demo 1 list danh sách các sản phẩm demo bằng terminal sau : 

php artían make:model Product -a

Câu lệnh này giúp ta tạo đầy đủ các file cần thiết gồm model ,migration ,factory ,controller 

Ở file database/migrations/2024_01_12_134541_create_products_table.php

Code trong file này như sau : 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name',400);
            $table->unsignedBigInteger('prince');
            $table->longText('description')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Ở đây do làm demo nên mình sẽ tạo các trường cơ bản .Trên thực tế thì sản phẩm sẽ gồm rất nhiều trường 

Tiếp theo chúng ta sẽ auto tạo fake danh sách sản phẩm với file database/factories/ProductFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->text,
            'price' => fake()->numberBetween(30000,70000),
            'description'=>fake()->paragraph,
        ];
    }
}

Giờ chỉ cần chạy terminal :

php artisan migrate --seed

3 Xây dựng cấu trúc giỏ hàng :

Ở đây mình xây dựng cấu trúc 1 giỏ hàng như sau chỉ gồm list danh sách sản phẩm 

<?php


namespace App\Helps;


use App\Models\Product;

class Cart
{
    protected array $products = array();
    /**
     * @return array
     */
    public function __construct($cart)
    {
        if ($cart){
            $this->products = $cart->products;
        }
    }

    public function getProducts(): array
    {
        return $this->products;
    }
    public function addProduct(int $id,int $number =1)
    {
        $data = Product::find($id);
        $new_product =  ['quantity' => 0,'product_id'=>$id];
        if ($this->products){
            if(array_key_exists($id,$this->products)){
                $new_product = $this->products[$id];
            }
        }
        $new_product['quantity'] += $number;
        $this->products[$id] = $new_product;
    }
    public function removeProduct(int $id,int $number=1)
    {
        if(array_key_exists($id,$this->products)){
            $this->products[$id]['quantity'] -= $number ;
            if($this->products[$id]['quantity'] <1)
            {
                unset($this->products[$id]);
            }
        }
    }
}

4 Tạo controller CartController

Để xử lý các vấn đề liên quan đến thêm và xoá các sản phẩm trong giỏ hàng :

<?php

namespace App\Http\Controllers;

use App\Helps\Cart;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function addcart(Request $request,$id)
    {
        $product = Product::find($id);
        if ($product != null)
        {
            $oldCart = Session::get('cart') ? Session::get('cart') : null;
            $newCart = new Cart($oldCart);
            $newCart->addProduct($id);
            $request->session()->put('cart', $newCart);
        }
        return redirect()->back();
    }
    public function removeCart(Request $request,$id)
    {
        $oldCart = Session::get('cart') ? Session::get('cart') : null;
        $newCart = new Cart($oldCart);
        $newCart->removeProduct($id);
        $request->session()->put('cart', $newCart);
        return redirect()->back();
    }
}

5 Tạo router cho thêm và xoá sản phẩm trong giỏ hàng

Vào file routes/web.php :   thêm các router sau vào 

Route::get('/products',[\App\Http\Controllers\ProductController::class,'index']);
Route::get('/cart/add/{id}',[\App\Http\Controllers\CartController::class,'addcart'])->name('add_cart');
Route::get('/cart/removeCart/{id}',[\App\Http\Controllers\CartController::class,'removeCart'])->name('remove_cart');

6 Show giỏ hàng

Chúng ta tạo 1 component với lệnh sau :

php artían make:component Cart

Tại file app/View/Components/Cart.php

<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Session;
use Illuminate\View\Component;

class Cart extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {

    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        $cart = Session::get('cart');
        if ($cart)
        {
            $data_cart = new \App\Helps\Cart($cart);
            $products = ($data_cart->getProducts());
            $total = count($products);

            return view('components.cart',compact('products'));
        }
    }
}

Ở đây chúng ta gọi cart từ trong session ra nếu có cart trong session thì sẽ lấy dữ liệu để xử lý

Vậy là các bước cơ bản để tạo 1 giỏ hàng đơn giản đã xong ,Các bạn có thể dựa vào giỏ hàng đơn giản này để phát triển theo ý mình .

Cảm ơn các bạn đã đọc bài viết của mình .Có gì cần góp ý bạn hãy liên hệ với mình nhé