Laravel Cart is a highly customizable package that enables you to easily add shopping cart functionality to your Laravel applications. With flexible options for item management, persistent storage, and deep integration with Laravel, it is perfect for building e-commerce or custom shopping features.
To install the package, use Composer:
composer require isapp/laravel-cart
To modify the default configuration, publish the configuration file using the following Artisan command:
php artisan vendor:publish --provider="Isapp\LaravelCart\CartServiceProvider" --tag="config"
This command will create a config/laravel-cart.php file where you can customize package settings as needed.
To publish the migration files provided by the Laravel Cart package, use the following Artisan command:
php artisan vendor:publish --provider="Isapp\LaravelCart\CartServiceProvider" --tag="migrations"
This command will copy the migration files to your project's database/migrations directory.
Once the migration files are published, you can apply the migrations to your database using the following command:
php artisan migrate
getUser(): ?AuthenticatableReturns the currently authenticated user or null if no user is set.
$user = Cart::getUser();
setUser(Authenticatable $user): DriverSets a specific user for cart operations. Useful for admin operations or impersonation.
$user = User::find(1);
Cart::setUser($user)->storeItem($item);
setGuard(string $guard): DriverSets the authentication guard to use (default is 'web').
Cart::setGuard('admin')->getUser();
get(): Model|CartGets or creates the cart for the current user or session. For authenticated users, finds or creates cart by user_id. For guests, uses session_id.
$cart = Cart::get();
echo "Cart has " . $cart->items->count() . " items";
storeItem(CartItemContract $item): DriverStores a single item in the cart. If the item already exists, increases its quantity instead.
$product = Product::find(1);
$cartItem = new CartItem();
$cartItem->itemable()->associate($product);
Cart::storeItem($cartItem);
Throws:
NotImplementedException - if itemable doesn't implement CartItemProductItemAssociatedWithDifferentCartException - if trying to add item from another cartstoreItems(Collection $items): staticStores multiple items in the cart at once.
$items = collect([
$cartItem1,
$cartItem2,
$cartItem3
]);
Cart::storeItems($items);
increaseQuantity(CartItemContract $item, int $quantity = 1): staticIncreases the quantity of a specific cart item.
// Increase by 1 (default)
Cart::increaseQuantity($cartItem);
// Increase by specific amount
Cart::increaseQuantity($cartItem, 5);
Throws:
NotFoundException - if item doesn't exist in cartdecreaseQuantity(CartItemContract $item, int $quantity = 1): DriverDecreases the quantity of a specific cart item.
// Decrease by 1 (default)
Cart::decreaseQuantity($cartItem);
// Decrease by specific amount
Cart::decreaseQuantity($cartItem, 3);
Throws:
NotFoundException - if item doesn't exist in cartremoveItem(CartItemContract $item): DriverRemoves a specific item from the cart completely.
Cart::removeItem($cartItem);
emptyCart(): staticRemoves all items from the cart.
Cart::emptyCart();
getItemPrice(CartItemContract $item, bool $incTaxes = true): stringCalculates the total price for a cart item (price × quantity). Returns a string for precision.
// With taxes (default)
$totalPrice = Cart::getItemPrice($cartItem);
// Without taxes
$totalPrice = Cart::getItemPrice($cartItem, false);
getItemPricePerUnit(CartItemContract $item, bool $incTaxes = true): stringGets the price per single unit of a cart item.
// With taxes (default)
$unitPrice = Cart::getItemPricePerUnit($cartItem);
// Without taxes
$unitPrice = Cart::getItemPricePerUnit($cartItem, false);
getTotalPrice(bool $incTaxes = true): stringCalculates the total price of all items in the cart.
// With taxes (default)
$total = Cart::getTotalPrice();
// Without taxes
$total = Cart::getTotalPrice(false);
use Isapp\LaravelCart\Facades\Cart;
use App\Models\Product;
use Isapp\LaravelCart\Models\CartItem;
// Create and add item to cart
$product = Product::find(1);
$cartItem = new CartItem();
$cartItem->itemable()->associate($product);
Cart::storeItem($cartItem);
// Get cart with items
$cart = Cart::get();
echo "Items in cart: " . $cart->items->count();
// Calculate totals
$total = Cart::getTotalPrice();
echo "Cart total: $" . $total;
// Admin adding items to user's cart
$user = User::find(123);
$product = Product::find(1);
$cartItem = new CartItem();
$cartItem->itemable()->associate($product);
Cart::setUser($user)->storeItem($cartItem);
// Get existing cart item
$cart = Cart::get();
$cartItem = $cart->items->first();
// Increase quantity
Cart::increaseQuantity($cartItem, 2);
// Decrease quantity
Cart::decreaseQuantity($cartItem, 1);
// Remove item completely
Cart::removeItem($cartItem);
$cart = Cart::get();
foreach ($cart->items as $item) {
$unitPrice = Cart::getItemPricePerUnit($item);
$totalItemPrice = Cart::getItemPrice($item);
echo "Unit: $unitPrice, Total: $totalItemPrice\n";
}
$grandTotal = Cart::getTotalPrice();
echo "Grand Total: $grandTotal";
The DatabaseDriver throws specific exceptions for different error conditions:
use Isapp\LaravelCart\Exceptions\NotFoundException;
use Isapp\LaravelCart\Exceptions\NotImplementedException;
use Isapp\LaravelCart\Exceptions\ItemAssociatedWithDifferentCartException;
try {
Cart::increaseQuantity($cartItem, 5);
} catch (NotFoundException $e) {
// Item not found in cart
return response()->json(['error' => 'Item not found'], 404);
} catch (NotImplementedException $e) {
// Itemable doesn't implement required interface
return response()->json(['error' => 'Invalid item'], 400);
} catch (ItemAssociatedWithDifferentCartException $e) {
// Trying to add item from another cart
return response()->json(['error' => 'Item belongs to different cart'], 400);
}
CartItemProduct interfaceIf you need to add a custom driver to the Cart facade, you can do so by extending it within a service provider.
Here is an example demonstrating how to achieve this:
Create a custom driver class, for example:
namespace App\Services;
use Isapp\LaravelCart\Contracts\Driver;
class CustomCartDriver implements Driver
{
// Implement methods as per the contract and your needs
public function storeItem(CartItemContract $item): Driver
{
// Custom implementation
}
public function increaseQuantity(CartItemContract $item, int $quantity = 1): static
{
// Custom implementation
}
// Other required methods...
}
Register the custom driver in a service provider:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Isapp\LaravelCart\Facades\Cart;
class CartServiceProvider extends ServiceProvider
{
public function boot()
{
Cart::extend('custom', function () {
return new \App\Services\CustomCartDriver;
});
}
}
Contributions are welcome! If you have suggestions for improvements, new features, or find any issues, feel free to submit a pull request or open an issue in this repository.
Thank you for helping make this package better for the community!
This project is open-sourced software licensed under the MIT License.
You are free to use, modify, and distribute it in your projects, as long as you comply with the terms of the license.
Maintained by ISAPP and ISAP OÜ.
Check out our software development services at isapp.be.
How can I help you explore Laravel packages today?