Installation:
composer require binafy/laravel-cart
php artisan vendor:publish --provider="Binafy\Cart\CartServiceProvider" --tag="config"
php artisan migrate
config/cart.php is published and updated with your preferred driver (e.g., session, database, or redis).First Use Case: Add an item to the cart via the facade:
use Binafy\Cart\Facades\Cart;
Cart::add([
'id' => 'product_123',
'name' => 'Example Product',
'qty' => 1,
'price' => 9.99,
'options' => ['color' => 'blue']
]);
$cartItems = Cart::get();
config/cart.php (drivers, default settings).Binafy\Cart\Facades\Cart (core methods like add(), update(), remove()).Binafy\Cart\Models\Cart (if using the database driver).CartItemAdded, CartItemUpdated, CartItemRemoved (in app/Events).Adding Items:
Cart::add() with an associative array (required keys: id, qty, price).name, options, associatedModel (for database-driven carts).$price = $product->applyDiscount();
Cart::add([
'id' => $product->id,
'qty' => $request->qty,
'price' => $price,
'options' => ['discount_code' => $request->code]
]);
Updating/Cart Management:
Cart::update($id, ['qty' => 5]).Cart::remove($id).Cart::clear().Driver-Specific Patterns:
Cart::setDriver('session');
cart_items table).
Cart::setDriver('database');
Cart::add(['id' => '1', 'associatedModel' => Product::class]);
Cart::setDriver('redis');
Checkout Flow:
Cart::validate() (checks for stock, prices, etc.).$subtotal = Cart::subtotal();
$tax = Cart::tax();
$total = Cart::total();
Cart::clear().@foreach (Cart::get() as $item)
<div>{{ $item->name }} ({{ $item->qty }} x ${{ $item->price }})</div>
@endforeach
return response()->json([
'cart' => Cart::get(),
'subtotal' => Cart::subtotal(),
'tax' => Cart::tax(),
]);
Binafy\Cart\Http\Middleware\CartMiddleware to attach cart data to requests:
$middleware = [\Binafy\Cart\Http\Middleware\CartMiddleware::class];
CartItemAdded::dispatch($item);
Driver Mismatches:
database driver, ensure the cart_items table exists and the associatedModel is correctly set.php artisan migrate
config/cart.php for driver and connection settings.Session Driver Limitations:
session:driver=database in .env for persistence.ID Collisions:
id fields must be unique per cart item. Reusing IDs (e.g., product IDs) without context can cause overwrites.product_id_user_id) or leverage options for disambiguation.Tax/Subtotal Calculations:
'tax' => [
'enabled' => true,
'rate' => 0.08, // 8%
'calculation' => 'Binafy\Cart\Calculations\Tax::class',
],
Binafy\Cart\Calculations\Tax for dynamic rates (e.g., per-product taxes).Performance with Database Driver:
cart_id and id.->with('product') to eager-load relationships if using associatedModel.\Log::debug('Cart contents:', ['items' => Cart::get()->toArray()]);
storage/framework/sessions.cart_items table.redis-cli to inspect keys (e.g., cart:user_1).User Context:
Cart::setUser(auth()->id()); // Set user ID
'user_id_column' => 'user_id' in config/cart.php for database driver.Custom Models:
Binafy\Cart\Models\Cart or Binafy\Cart\Models\CartItem for additional fields:
php artisan make:model CartItemExtension --extends=Binafy\Cart\Models\CartItem
cart_items table.Caching:
database driver to reduce DB load:
'cache' => [
'enabled' => true,
'driver' => 'redis',
],
Custom Drivers:
Binafy\Cart\Contracts\Driver:
class MyDriver implements Driver {
public function get($userId = null) { ... }
public function add(array $item) { ... }
// ... other methods
}
config/cart.php:
'drivers' => [
'my_driver' => \App\Drivers\MyDriver::class,
],
Validation Rules:
Binafy\Cart\Rules\CartRule:
use Binafy\Cart\Rules\CartRule;
class MaxQuantityRule extends CartRule {
public function passes($errorBag, $attribute, $value) {
return $value <= 10; // Max 10 items
}
}
AppServiceProvider:
Validator::extend('max_quantity', function ($attribute, $value, $parameters, $validator) {
return (new MaxQuantityRule())->passes($validator, $attribute, $value);
});
Webhooks/Events:
CartItemAdded to update inventory:
CartItemAdded::listen(function ($event) {
Product::find($event->item->id)->decrement('stock', $event->item->qty);
});
How can I help you explore Laravel packages today?