Installation:
composer require darryldecode/cart
Add to config/app.php:
'providers' => [
Darryldecode\Cart\CartServiceProvider::class,
],
'aliases' => [
'Cart' => Darryldecode\Cart\Facades\CartFacade::class,
]
Publish Config (Optional):
php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"
(Edit config/cart.php for customization like session driver, default conditions, etc.)
First Use Case: Add an item to the cart in a controller:
use Cart;
public function addToCart(Request $request) {
$product = Product::find($request->product_id);
Cart::add([
'id' => $product->id,
'name' => $product->name,
'qty' => 1,
'price' => $product->price,
'attributes' => ['color' => $request->color],
]);
return redirect()->back()->with('success', 'Added to cart!');
}
View Cart Contents:
$cartItems = Cart::getContent();
$total = Cart::getTotal();
(Use in Blade templates with @foreach($cartItems as $item))
Adding Items:
Cart::add([
'id' => $id,
'name' => $name,
'qty' => $qty,
'price' => $price,
'attributes' => ['key' => 'value'], // Optional
]);
Cart::add($productModel->toCartArray());
(Define toCartArray() in your model for consistency.)Updating Items:
Cart::update($id, [
'qty' => 3, // Update quantity
'price' => $newPrice, // Update price
]);
Removing Items:
Cart::remove($id); // Remove by ID
Cart::remove($id, $rowId); // Remove specific row (if duplicates allowed)
Cart::clear(); // Empty entire cart
Conditions (Rules):
Cart::condition(function($cart) {
if ($cart->totalQty > 10) {
return ['max_items' => 'You cannot have more than 10 items!'];
}
return true;
}, 'max_items');
Cart::add($item, ['conditions' => ['max_items']]);
Persistence:
config/cart.php:
'driver' => 'database',
'table_name' => 'cart_items',
(Run migrations after publishing config.)Taxes and Discounts:
Cart::tax([10 => 10]); // 10% tax on $10 items
Cart::discount($code); // Apply discount code
Checkout:
$order = Cart::getContent(); // Get items for order processing
Cart::clear(); // Clear cart after purchase
Blade Directives:
Use @cart directives for reusable cart logic in views:
@cart
@foreach($cartItems as $item)
<tr>
<td>{{ $item->name }}</td>
<td>{{ $item->qty }}</td>
</tr>
@endforeach
@endcart
Middleware for Cart Access:
public function handle($request, Closure $next) {
view()->share('cart', Cart::getContent());
return $next($request);
}
(Add to HandleCartData middleware.)
API Responses:
return response()->json([
'cart' => Cart::getContent(),
'total' => Cart::getTotal(),
]);
Testing:
Cart::instance('test')->add(...) for isolated test carts.Cart::instance('test')->clear();
Localization:
config/cart.php:
'locale' => [
'prefix' => 'cart.',
],
php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="lang"
Session Driver Issues:
config/session.php).AppServiceProvider boot method).session()->start();
Cart::add(...);
Duplicate Items:
id and attributes. To allow duplicates:
Cart::add($item, ['associate' => false]);
Price/Quantity Updates:
price or qty after addition may not reflect in the cart until the next request. Use Cart::update() to force changes:
Cart::update($id, ['qty' => $newQty, 'price' => $newPrice]);
Database Driver Quirks:
cart_items table exists (run migrations).user_id column is populated if using Cart::setUser().php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="migrations"
Condition Conflicts:
max_items, min_order_value).Caching:
Log Cart Contents:
\Log::debug('Cart Contents:', ['items' => Cart::getContent()]);
Check Conditions:
Cart::condition(function() { return true; }, 'debug_mode');
Verify Session Data:
\Log::debug('Session Cart:', ['cart' => session('cart')]);
Clear Stale Data:
cart_items table if corrupted:
php artisan db:table --truncate cart_items
Custom Drivers:
Darryldecode\Cart\Contracts\CartInterface for custom storage (e.g., Redis, Elasticsearch).$this->app->bind(
'Darryldecode\Cart\Contracts\CartInterface',
YourCustomCart::class
);
Event Listeners:
cart.item.added):
Cart::add($item);
event(new \Darryldecode\Cart\Events\CartItemAdded($item));
EventServiceProvider:
protected $listen = [
'Darryldecode\Cart\Events\CartItemAdded' => [
YourListener::class,
],
];
Custom Attributes:
CartItem model by binding a custom model:
$this->app->bind(
'Darryldecode\Cart\CartItem',
YourCustomCartItem::class
);
API Resources:
return new CartResource(Cart::getContent());
Webhooks:
Cart::add($item);
\Http::post('https://inventory-api.com/update', ['sku' => $item->id, 'qty' => $item->qty]);
How can I help you explore Laravel packages today?