Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Oa Laravel Cart Laravel Package

offline-agency/oa-laravel-cart

A shopping cart package for Laravel that handles cart storage, item management, quantities, and totals, giving your app a ready-made foundation for adding products to the cart, updating quantities, and calculating prices without writing cart logic from scratch.

View on GitHub
Deep Wiki
Context7

Getting Started

  • Install the package: composer require offline-agency/laravel-cart.
  • Publish package assets and run migrations:
    php artisan vendor:publish --provider="OfflineAgency\LaravelCart\CartServiceProvider"
    php artisan migrate
    
  • Add the package trait to your authenticatable model:
    use OfflineAgency\LaravelCart\Traits\HasCart;
    
    class User extends Authenticatable
    {
        use HasCart;
    }
    
  • Open config/cart.php first. Confirm the storage driver (session vs database), cart model, item model, the guest-transfer option, and — new in 4.2.0 — the tax allocation settings (rate source, inclusive vs exclusive pricing, rounding strategy, and whether tax is allocated per item or per cart).
  • First use case: add a product to the cart and read it back, including tax:
    use OfflineAgency\LaravelCart\Facades\Cart;
    
    Cart::add($product, 1);
    $items = Cart::content();
    $tax   = Cart::tax();   // verify accessor name in your installed version
    
  • Where to look next: Cart facade methods, HasCart trait, package events, the published migrations, and — for 4.2.0 — the tax allocation classes and the cart recipe/executable definitions in src/. The two new areas to verify against your app are payable tax allocation (how per-line tax is computed and where it surfaces on the cart, items, and checkout totals) and executable cart recipes (how a named sequence of cart operations is defined, registered, and run).
  • Because 4.2.0 is a minor release, an upgrade from 4.1.x should be non-breaking; still run your cart/checkout test suite and diff any published config or migration stubs after re-publishing.

Implementation Patterns

  • Keep controllers thin. Put cart operations in a dedicated service or action class, then call Cart::add(), Cart::update(), Cart::remove(), and Cart::clear() from there. This keeps checkout, product pages, and API endpoints consistent.
  • Use the database driver for anything beyond simple session carts. Atomic cart mutations (4.1.0) are most valuable when carts are persisted and multiple requests may touch the same cart — and that is also the driver where payable tax allocation is easiest to audit after the fact.
  • Treat tax as first-class data, not a display concern. Read tax from the cart/line API rather than recomputing it in Blade or in your order builder, and persist the allocated tax amounts onto the order and order lines at checkout so a later rate change cannot retroactively alter historical payables:
    DB::transaction(function () use ($cart) {
        $order = Order::createFromCart($cart->content(), [
            'tax_total' => $cart->tax(),
        ]);
        // copy per-line allocated tax onto order items
    });
    
  • Decide inclusive vs exclusive pricing once, in config, and make product pricing consistent with it. Mixing tax-inclusive catalog prices with exclusive cart math is the most common source of off-by-a-cent totals in checkout.
  • Use executable cart recipes for repeated multi-step cart workflows instead of duplicating them across controllers — e.g. "apply bundle", "seed a starter cart", "re-apply a saved cart", "convert a quote into a cart". Define the recipe once, keep each step as a small cart operation, and invoke it from a service or a queued job:
    // shape depends on the package API — verify the entry point in src/
    Cart::recipe(StarterCartRecipe::class)->execute($user);
    
  • Keep recipes deterministic and idempotent where possible. If a recipe adds items, make the caller's intent explicit (replace vs merge) so re-running it after a failed request does not double the cart.
  • Because recipes chain multiple cart mutations, wrap recipe execution in your own transaction when the recipe is part of a larger application write, exactly as with ad-hoc cart calls:
    DB::transaction(fn () => Cart::recipe($recipe)->execute($user));
    
    The package guarantees per-mutation atomicity; it does not give you a transaction boundary across the whole recipe plus your own writes.
  • Guest transfer is opt-in. Enable it in config/cart.php and explicitly trigger the transfer after authentication. A typical pattern is a listener on Laravel’s Login event or a small middleware:
    public function handle(Login $event): void
    {
        Cart::transferGuestCart($event->user);
    }
    
    Verify the exact method name against the package API for your installed version, but the workflow is: guest cart exists in session, user logs in, transfer runs, authenticated user cart is merged. With 4.2.0, confirm how tax allocation behaves across the merge — merged lines should carry their own allocated tax, not inherit the destination cart's rate.
  • Use package events for side effects instead of hard-coding them into controllers. Listen for item-added, item-updated, cart-cleared, cart-merged, and any recipe-executed events to update analytics, inventory reservations, or promotional totals.
  • If you support both guests and authenticated users, test the complete path: add as guest (including a taxed item), log in, confirm cart contents and tax totals, then log out. The transfer must be enabled and invoked intentionally; it is not automatic.
  • For custom persistence, bind your own cart storage implementation in a service provider. Keep the Cart facade usage the same so application code does not depend on the driver — and make sure the custom driver can surface the tax allocation data the package expects.
  • In tests, prefer the database driver with RefreshDatabase when verifying persistence, tax allocation, and transfer behavior. For unit tests, resolve the cart manager from the container and use a fresh session/store per test. Add at least one test asserting per-line tax + cart tax sums to the expected total for a multi-rate cart.

Gotchas and Tips

  • Payable tax allocation is the headline of 4.2.0. Read the PR (#51) and the source before wiring it into checkout — confirm whether tax is derived from a rate on the product, a cart-level configuration, or a tax resolver you must bind, and confirm which object exposes the allocated amount (cart, item, or both).
  • Rounding is where tax bugs live. Allocate tax per line and sum the lines; do not sum untaxed lines and apply tax once at the end (or vice versa) — the two approaches diverge by cents on multi-line carts. Pick one strategy and assert it in tests.
  • Store money as integers in the smallest currency unit. Do not introduce floats in cart totals, tax allocation, discounts, or recipe-computed prices.
  • Executable cart recipes run code, not markup. Treat a recipe like a domain action: validate its inputs, keep it free of HTTP/session assumptions, and do not let it fire side effects directly — emit events instead.
  • Recipes executed from a queued job or a console command may not have the same cart identity as a web request. Resolve the cart for a concrete user/session before executing, or the recipe may operate on an empty or unrelated cart.
  • Guest transfer is opt-in (unchanged from 4.1.0). If you upgrade expecting automatic merge-on-login, you will not get it. Enable the config option and add the login hook yourself.
  • Atomic mutations depend on the underlying storage. Session carts cannot provide the same concurrency guarantees as database carts. Use the database driver in production if you expect concurrent requests, multiple tabs, or high-traffic checkout flows.
  • Clear config cache after changing cart or tax settings:
    php artisan config:clear
    
    Re-publish the package config after a minor upgrade to see whether 4.2.0 added tax keys — but diff before overwriting your customisations.
  • Cart identity is easy to get wrong. Guest carts are typically keyed by session; authenticated carts by user ID. After login, verify the merge path and decide what should happen when both carts contain the same product — including which tax rate wins.
  • Events fired during a transaction may execute before the transaction commits. If a listener sends email, dispatches a job, or calls an external API, queue it after commit or use Laravel’s afterCommit behavior.
  • Check the published migration indexes and foreign keys. Cart lookups by user/session and cart item lookups by cart are common query paths; if 4.2.0 added tax columns, index anything you filter or report on.
  • If your product model uses a morph map, configure it before storing cart items. Changing morph aliases later can break existing cart rows.
  • Cart contents can go stale. Recalculate prices, availability, and tax at checkout rather than trusting the cart row totals alone — tax rates change more often than prices do.
  • When clearing a cart after order placement, fire the appropriate package event so listeners can clean up promotions, reservations, or analytics state.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin