Laravel Cart

repository·1.x·Indexed 19 days ago

https://github.com/binafy/laravel-cart

A customizable package for adding shopping cart functionality to Laravel applications. It supports multiple storage drivers, including session and database, and provides a LaravelCart facade for managing items, quantities, and custom attributes. The package includes the Cartable interface for model compatibility, Eloquent models for cart and item management, and a set of events to trigger custom business logic.

Tokens
4.3K
Snippets
16
Records
21
Agent score
63%

What's inside laravel-cart

  1. Implement the Cartable interface

    1.x

    To make a model compatible with the cart (allowing it to be stored as an item), your model must implement the Binafy\LaravelCart\Cartable interface and define a getPrice() method.

    use Binafy\LaravelCart\Cartable;
    
    class Product extends Model implements Cartable
    {
        public function getPrice(): int
        {
            // Return the price of the product
        }
    }
  2. Publish Laravel Cart configuration and migrations

    1.x

    You can publish the configuration file, migrations, or all assets at once using Artisan commands.

    To publish only the config:

    php artisan vendor:publish --tag="laravel-cart-config"

    To publish only the migrations:

    php artisan vendor:publish --tag="laravel-cart-migrations"

    To publish everything (config, migrations, etc.) at once:

    php artisan vendor:publish --provider="Binafy\LaravelCart\Providers\LaravelCartServiceProvider"

    Note: After publishing migrations, you must run php artisan migrate to update your database schema.

    php artisan vendor:publish --provider="Binafy\LaravelCart\Providers\LaravelCartServiceProvider"
  3. Configure foreign key types for UUID or ULID

    1.x

    If your application uses uuid or ulid for user identifiers, update the foreign_key_type in config/laravel-cart.php. Ensure your models include the relevant traits for these ID types.

    'users' => [
        ...
    
        /*
         * Specify the type of foreign key being used (e.g., 'id', 'uuid', 'ulid').
         * For non-standard IDs, make sure to add the relevant traits to your models.
         */
        'foreign_key_type' => 'id', // Options: uuid, ulid, id
    ],
  4. Manage carts and items using the Cart Model

    1.x

    You can use the Binafy\LaravelCart\Models\Cart Eloquent model to interact directly with cart data.

    Core Operations

    Create or retrieve a cart:

    use \Binafy\LaravelCart\Models\Cart;
    
    $cart = Cart::query()->firstOrCreate(['user_id' => $user->id]);

    Store items in a cart:

    • Single item (Model): $cart->storeItem($product);
    • Single item (Array): $cart->storeItem(['itemable' => $product, 'quantity' => 1]);
    • Multiple items: $cart->storeItems([ ['itemable' => $p1, 'quantity' => 2], ... ]);
    • Create cart and store item in one go: Cart::query()->firstOrCreateWithStoreItems(item: $product, quantity: 1, userId: $user->id);

    Remove items:

    • Single item: $cart->removeItem($product);
    • All items: $cart->emptyCart();

    Update quantities:

    • Increase: $cart->increaseQuantity(item: $item, quantity: 2); (Default is 1)
    • Decrease: $cart->decreaseQuantity(item: $item, quantity: 2); (Default is 1)

    Accessing data:

    • Use the items relation to get all items in a cart.
    • Use the itemable relation on a CartItem to get the original model instance.
    use \Binafy\LaravelCart\Models\Cart;
    
    // Example: Storing multiple items
    $items = [
        ['itemable' => $product1, 'quantity' => 2],
        ['itemable' => $product2, 'quantity' => 1],
    ];
    
    $cart = Cart::query()->firstOrCreate(['user_id' => $user->id]);
    $cart->storeItems($items);
  5. Use the Laravel Cart Facade

    1.x

    The LaravelCart facade provides a convenient way to manage carts using different drivers.

    Supported Drivers:

    • session: Stores cart data in the session.
    • database: Stores cart data in the database (Default).

    To switch drivers on the fly, use the driver() method.

    <?php
    
    use Binafy\
    LaravelCart\
    LaravelCart;
    
    // Using a specific driver
    LaravelCart::driver('session')->storeItem($item, $userId|null);
    
    // Using the default driver
    LaravelCart::storeItem($item, $userId|null);
    
    // Removing an item using a specific driver
    LaravelCart::driver('session')->removeItem($item);
  6. Configure the default Laravel Cart driver

    1.x

    The default driver used by the cart is determined by the laravel-cart.driver.default configuration key. You can switch between available drivers by updating this value in your configuration files.

    // Example configuration setting in config/laravel-cart.php
    'driver' => [
        'default' => 'session', // or 'database'
    ],
  7. Listen to Laravel Cart events

    1.x

    You can hook into the following events to trigger custom business logic (e.g., logging, analytics, or notifications):

    EventTriggered When
    LaravelCartStoreItemEventAn item is added to the cart
    LaravelCartRemoveItemEventAn item is removed from the cart
    LaravelCartEmptyEventAll items are removed from the cart
    LaravelCartIncreaseQuantityEventAn item's quantity is increased
    LaravelCartDecreaseQuantityEventAn item's quantity is decreased