Skip to content

Products

Complete reference for the Product model, types, relationships, stock, pricing, and media.

Products are the core of your e-commerce catalog. Each product has a type that determines its capabilities: a Standard product is a simple physical item, a Variant product has multiple options like size and color, a Virtual product is a digital download, and an External product is sourced from another supplier.

How Products Work

Shopper uses a type-driven product system. When you create a product, you choose one of four types, and the system enables the right features automatically.

TypeShippingVariantsAttributesStockUse case
StandardYesNoYesOn the product itselfA book, a poster, a mug
VariantYesYesYesOn each variantA t-shirt with sizes and colors
VirtualNoNoYesNot trackedAn ebook, a software license, a course
ExternalNoNoNoNot trackedA product sourced from a supplier, identified by the supplier's reference

Standard products hold their own price, stock, and media. They are the simplest product type and work for anything that does not need size/color options.

Variant products are parents that hold the product description, images, and categories, but delegate pricing and stock to their child variants. Each variant represents a specific combination of options (e.g., "Blue / Large"). See the Product Variants documentation for details.

Virtual products behave like Standard products except they skip shipping and the cart does not check their stock. The files media collection holds the downloadable files your storefront delivers to customers after purchase.

External products are sourced from another supplier. The admin form asks for the supplier's identifier for the product, stored in external_id, and for the supplier when the supplier feature is enabled. They have no shipping and no attributes, and the cart does not check their stock.

You can check a product's type and capabilities using the following methods:

$product->isStandard();
$product->isVariant();
$product->isVirtual();
$product->isExternal();

$product->canUseShipping();
$product->canUseAttributes();
$product->canUseVariants();
$product->tracksInventory();

tracksInventory() returns true for Standard and Variant products only. For Virtual and External products, the cart skips the stock check and order creation does not reserve stock. You can still record stock movements on them.

Model

The model used is Shopper\Models\Product, which extends Shopper\Core\Models\Product. The core model provides the business logic, relationships, scopes, stock management, pricing, and reviews, and declares the media collections. The admin model registers those collections and the image conversions with Spatie MediaLibrary.

The product model uses SoftDeletes. A deleted product row stays in the database and Eloquent excludes it from queries automatically, so storefront queries do not need to filter soft-deleted products. When a product is deleted, the ProductObserver also permanently deletes its media records, its prices and its stock history.

Extending the Model

To add custom behavior, extend the admin model and update your configuration:

namespace App\Models;

use Shopper\Models\Product as ShopperProduct;

class Product extends ShopperProduct
{
}

Update config/shopper/models.php:

return [
    'product' => \App\Models\Product::class,
];

Database Schema

ColumnTypeNullableDefaultDescription
idbigintnoautoPrimary key
namestringno-Product name
slugstringyesnullURL-friendly identifier (unique). Any value you set is slugified and suffixed (-1, -2) when taken. The admin form fills it from the name
skustringyesnullStock Keeping Unit (unique)
barcodestringyesnullProduct barcode (unique)
descriptionlongtextyesnullFull product description (rich text)
summarytextyesnullShort product summary
typestringyesnullProduct type enum value
is_visiblebooleannofalseVisibility on storefront
featuredbooleannofalseFeatured product flag
allow_backorderbooleannofalseAllow adding to cart when out of stock. The admin has no field for it on products, set it in code
security_stockintegeryes0Minimum stock alert threshold
published_atdatetimeTznomigration datePublication date (supports scheduling). The column default is the date the migration ran, so set it when you create a product
seo_titlestring(60)yesnullSEO meta title
seo_descriptionstring(160)yesnullSEO meta description
weight_unitstringnokgWeight unit (kg, g, lbs)
weight_valuedecimal(10,2)yes0.00Weight value
height_unitstringnocmHeight unit (m, cm, mm, ft, in)
height_valuedecimal(10,2)yes0.00Height value
width_unitstringnocmWidth unit
width_valuedecimal(10,2)yes0.00Width value
depth_unitstringnocmDepth unit
depth_valuedecimal(10,2)yes0.00Depth value
volume_unitstringnolVolume unit (l, ml, gal, floz)
volume_valuedecimal(10,2)yes0.00Volume value
external_idstringyesnullExternal system reference
metadatajsonbyesnullAdditional custom data
brand_idbigintyesnullForeign key to brands
supplier_idbigintyesnullForeign key to suppliers
deleted_attimestampyesnullSoft delete timestamp
created_attimestampyesnullCreation timestamp
updated_attimestampyesnullLast update timestamp

Relationships

Brand

Each product can belong to a brand. This is a standard BelongsTo relationship.

$product->brand;

To query products by brand:

Product::query()
    ->whereHas('brand', fn ($q) => $q->where('slug', 'nike'))
    ->get();

Categories

Products have a polymorphic many-to-many relationship with categories through the product_has_relations table.

$product->categories;

$product->categories()->attach([$categoryId1, $categoryId2]);
$product->categories()->sync([$categoryId1, $categoryId2]);

Collections

Products can belong to multiple collections. Collections can also be automatic (rule-based): every time a product is saved, the ProductObserver queues a SyncProductWithCollectionsJob that evaluates the collection rules.

$product->collections;

$product->collections()->attach($collectionId);

Channels

Products can be assigned to multiple sales channels for multi-channel publishing.

$product->channels;

$product->channels()->attach($channelId);

Variants

For products with type = ProductType::Variant, the variants() relationship returns all child variants, ordered by position. Each variant has its own SKU, price, stock, and dimensions.

$product->variants;

$product->variants()->create([
    'name' => 'Blue / Large',
    'sku' => 'TSHIRT-BLU-L',
]);

The variants_stock computed attribute returns the total stock across all variants. It adds up the stock of each variant, so batch-load that stock first: otherwise each variant runs its own query, or throws a LazyStockLoadingException when ProductVariant::preventLazyStockLoading() is enabled (see Avoiding N+1 Queries).

use Shopper\Models\ProductVariant;

ProductVariant::loadCurrentStock($product->variants);

$product->variants_stock;

See the Product Variants documentation for the full variant API.

Tags

Products can have multiple tags for cross-cutting organization. Unlike categories (hierarchical) or collections (manual or rule-based), tags are simple flat labels.

$product->tags;

$product->tags()->attach([$tagId1, $tagId2]);

See the Product Tags documentation for details.

Supplier

Each product can optionally be linked to a supplier.

$product->supplier;

Attributes (Options)

Product attributes are accessed via the options() relationship. The name options is used instead of attributes to avoid collision with Eloquent's $attributes property.

$product->options;

Each pivot row stores either a selected attribute value (attribute_value_id, for checkbox, color picker and select attributes) or a freeform custom value (attribute_custom_value, for text, number, rich text and date attributes), never both. A checkbox or color picker attribute gets one row per selected value.

$product->options()->attach($colorAttributeId, [
    'attribute_value_id' => $navyBlueValueId,
]);

$product->options()->attach($engravingAttributeId, [
    'attribute_custom_value' => 'Happy birthday, Anna',
]);

You can link products together as related items for cross-selling on the storefront.

$product->relatedProducts;

$product->relatedProducts()->attach([$productId1, $productId2]);

Discounts

Products can be associated with discounts through a polymorphic relationship.

$product->discounts;

See the Discounts documentation for details on discount rules and conditions.

Query Scopes

Published Products

The publish() scope filters products where is_visible is true and the published_at date is today or earlier. This is the primary scope for storefront queries. It compares the date only, not the time, so a product scheduled for 18:00 today is already included in the morning.

use Shopper\Models\Product;

Product::query()->publish()->get();

Filter by Channel

The forChannel() scope filters products assigned to one or more sales channels. Pass a channel ID or an array of channel IDs.

Product::query()->forChannel($channelId)->get();

Product::query()->forChannel([$webChannelId, $mobileChannelId])->get();

Publication Check

The isPublished() method checks if a specific product is currently visible on the storefront. Unlike the publish() scope, it compares the full published_at timestamp with the current time.

$product->isPublished();

Media

Products support three media collections through Spatie MediaLibrary. The collection names for the default gallery and thumbnail are defined in config/shopper/media.php.

CollectionConfig keyBehaviorDescription
Default galleryshopper.media.storage.collection_nameMultiple filesProduct gallery images
Thumbnailshopper.media.storage.thumbnail_collectionSingle fileMain product image for listings
files-Multiple filesDownloadable files for virtual products. Accepts the mime types listed in shopper.media.accepts_file_types

To add a product thumbnail:

$collection = config('shopper.media.storage.thumbnail_collection');

$product->addMedia($file)->toMediaCollection($collection);

To add gallery images:

$collection = config('shopper.media.storage.collection_name');

$product->addMedia($file)->toMediaCollection($collection);

Image conversions are defined in shopper.media.conversions (large at 800x800 and medium at 500x500 by default). To retrieve the thumbnail URL with a specific conversion:

$collection = config('shopper.media.storage.thumbnail_collection');

$url = $product->getFirstMediaUrl($collection, 'medium');

Downloadable Files

For virtual products (ebooks, software, courses), the files collection stores the downloadable assets you deliver to customers after purchase. Shopper does not send them: your storefront decides when and how a customer downloads them. Unlike the thumbnail and gallery collections, the files collection name is not configurable.

$product->addMedia($pdfPath)->toMediaCollection('files');

$downloadUrl = $product->getFirstMediaUrl('files');

To get all downloadable files for a product:

$product->getMedia('files');

Pricing

Products use the HasPrices trait for multi-currency pricing. Each product can have multiple prices, one per currency, stored in the prices table through a polymorphic relationship.

To get the price for a specific currency:

$price = $product->getPrice('USD');

getPrice() returns null when the product has no price in that currency. Without an argument, it uses the store's default currency.

To format the price for display, use the shopper_money_format helper. Prices are stored in cents.

shopper_money_format($price->amount, 'USD');

See the Pricing documentation for details on creating and managing prices.

Stock Management

Products use the HasStock trait for inventory management. Stock is not stored as a column on the product. Instead, every stock change creates a record in the inventory_histories table, and the current stock is computed as the sum of all mutations. This gives you a complete audit trail of every stock movement.

Every stock mutation is tied to an inventory location (warehouse, store, fulfillment center), so you must always provide an $inventoryId when modifying stock.

Querying Stock

To get the current total stock across all locations:

$product->stock;

For variant products, use variants_stock to get the combined stock across all variants, after batch-loading the stock of the variants:

use Shopper\Models\ProductVariant;

ProductVariant::loadCurrentStock($product->variants);

$product->variants_stock;

To get stock at a specific point in time, useful for reporting. A date string is read as midnight at the start of that day:

$product->getStock('2026-01-15');
$product->getStock(now()->subDays(7));

To get stock for a specific inventory location:

$product->stockInventory($warehouseId);

To check that a quantity is available (the stock is above zero and at least the requested quantity):

$product->inStock(3);

To check the stock alert threshold:

if ($product->stock <= $product->security_stock) {
    // low stock
}

Modifying Stock

To increase stock (for example, when receiving a shipment from a supplier):

$product->mutateStock(
    inventoryId: $inventory->id,
    quantity: 50,
    event: 'Shipment received',
    description: 'PO #12345 - Spring collection restock',
);

mutateStock() and decreaseStock() also accept a userId (who made the change) and a reference model (for example, the order that caused the movement). Both are stored on the history record.

To decrease stock (for example, when fulfilling an order):

$product->decreaseStock(
    inventoryId: $inventory->id,
    quantity: 2,
    event: 'Order fulfilled',
    description: 'Order #1042',
);

To set the product's total stock to an exact quantity. This calculates the delta from $product->stock, which sums all locations, and records that delta on the given location as a single mutation. It returns null when the stock already matches. With several locations, the given location does not end up at newQuantity: use mutateStock() or decreaseStock() to correct one location after a physical count.

$product->setStock(
    newQuantity: 75,
    inventoryId: $inventory->id,
    event: 'Inventory count',
    description: 'Q1 2026 physical count adjustment',
);

To clear all stock history and optionally set a new starting quantity:

$product->clearStock(
    inventoryId: $inventory->id,
    newQuantity: 100,
    event: 'Stock reset',
);

clearStock() deletes all inventory history records for the product. Use it only for resets or corrections, not for regular stock adjustments.

For variant products, stock is managed on each variant individually. See the Product Variants stock management section.

Avoiding N+1 Queries

Accessing $product->stock triggers an individual SUM(quantity) query on the inventory_histories table for each product. When iterating over a collection, this results in N separate queries.

Use loadCurrentStock() to batch-load stock for an entire collection in a single query:

use Illuminate\Database\Eloquent\Collection;
use Shopper\Models\Product;
use Shopper\Models\ProductVariant;

$products = Product::query()->with('variants')->get();

Product::loadCurrentStock($products);

$variants = Collection::make(
    $products->filter(fn ($p) => $p->canUseVariants())->flatMap->variants
);

ProductVariant::loadCurrentStock($variants);

loadCurrentStock() expects an Eloquent collection. flatMap returns a base collection, which is why the variants are wrapped in Collection::make().

You can also batch-load stock for a specific inventory location. After this call, $product->stock returns the stock at that location, not the total:

Product::loadStockForInventory($products, $inventoryId);

Preventing Lazy Stock Loading

Following the same pattern as Laravel's Model::preventLazyLoading(), you can catch unoptimized stock access during development. When enabled, accessing $product->stock without prior batch-loading throws a LazyStockLoadingException.

use Shopper\Models\Product;
use Shopper\Models\ProductVariant;

Product::preventLazyStockLoading(! app()->isProduction());
ProductVariant::preventLazyStockLoading(! app()->isProduction());

Call it in the boot() method of a service provider. The setting is kept per model class, so enabling it on Product does not cover ProductVariant.

Dimensions

The HasDimensions trait provides computed attributes that return formatted dimension strings combining the value and unit.

$product->weight;
$product->height;
$product->width;
$product->depth;
$product->volume;

For a product with weight_value = 1.50 and weight_unit = Weight::KG, $product->weight returns "1.50 kg". Each attribute returns null when its value column is null.

Events

The admin panel dispatches these events when a product is created, updated or deleted from its pages. Saving a product with Eloquent in your own code (Product::query()->create(), $product->update()) does not dispatch them:

use Shopper\Core\Events\Products\ProductCreated;
use Shopper\Core\Events\Products\ProductUpdated;
use Shopper\Core\Events\Products\ProductDeleted;

The ProductObserver also dispatches a SyncProductWithCollectionsJob every time a product is saved, from the admin or from your code, which evaluates automatic collection rules to add or remove the product from rule-based collections. The job is queued and runs after the database transaction commits, so automatic collections update only when a queue worker processes it (or immediately with the sync queue driver).

For the full events reference including payload details, see the Events page.

Creating Products

To create a standard product with a price and category:

use Shopper\Models\Product;
use Shopper\Core\Enum\ProductType;

$product = Product::query()->create([
    'name' => 'Classic T-Shirt',
    'slug' => 'classic-t-shirt',
    'sku' => 'TSHIRT-001',
    'type' => ProductType::Standard,
    'description' => 'A comfortable cotton t-shirt available in multiple colors.',
    'is_visible' => true,
    'published_at' => now(),
    'brand_id' => $brandId,
]);

$product->prices()->create([
    'amount' => 2999,
    'currency_id' => $currencyId,
]);

$product->categories()->attach([$categoryId]);

To add a thumbnail image:

$collection = config('shopper.media.storage.thumbnail_collection');

$product->addMediaFromUrl('https://example.com/tshirt.jpg')
    ->toMediaCollection($collection);

Retrieving Products

The findBySlug static method looks up a product by its slug and throws a ModelNotFoundException if not found:

$product = Product::findBySlug('classic-t-shirt');

To get all published products with their relationships:

$products = Product::query()
    ->publish()
    ->with(['brand', 'categories', 'media'])
    ->get();

To get featured products:

$featured = Product::query()
    ->publish()
    ->where('featured', true)
    ->take(8)
    ->get();

To get products by category:

$products = Product::query()
    ->publish()
    ->whereHas('categories', fn ($q) => $q->where('slug', 'clothing'))
    ->get();

Permissions

The admin panel generates permissions for product management and its related features:

Products

PermissionDescription
browse_productsView the products list
read_productsView a single product
add_productsCreate new products
edit_productsEdit existing products
delete_productsDelete products

Product Variants

PermissionDescription
browse_product_variantsView variants on a product
read_product_variantsView a single variant
add_product_variantsCreate new variants
edit_product_variantsEdit existing variants
delete_product_variantsDelete variants

Components

You can publish the Livewire components to customize the admin UI for products:

php artisan shopper:component:publish product

This creates config/shopper/components/product.php where you can replace any page or form component with your own implementation.

Last updated on

Edit on GitHub