Collections
Complete reference for the Collection model, automatic rules, and usage in Shopper.
Collections are curated groups of products for marketing and merchandising. Unlike categories, collections can be manually curated or automatically populated based on rules.
Model
The model used is Shopper\Models\Collection, which extends Shopper\Core\Models\Collection. The core model provides the business logic, relationships, scopes, rule evaluation, and slug generation. The admin model adds media collections and conversions through Spatie MediaLibrary.
The core model implements Shopper\Core\Models\Contracts\Collection and uses the HasSlug trait to keep slugs unique.
Extending the Model
To add custom behavior, extend the admin model and update your configuration:
namespace App\Models;
use Shopper\Models\Collection as ShopperCollection;
class Collection extends ShopperCollection
{
}Update config/shopper/models.php:
return [
'collection' => \App\Models\Collection::class,
];Database Schema
Collection Table
| Column | Type | Nullable | Default | Description |
|---|---|---|---|---|
id | bigint | no | auto | Primary key |
name | string | no | - | Collection name |
slug | string | yes | null | URL-friendly identifier (unique) |
description | longtext | yes | null | Collection description |
type | string | no | - | Collection type (manual or auto) |
sort | string | yes | null | Product sorting method (Shopper does not read it) |
match_conditions | string | yes | null | Rule matching logic (all or any) |
published_at | datetimeTz | no | migration date | Publication date. The column default is the date the migration ran, so a collection created without it is published at once |
seo_title | string(60) | yes | null | SEO meta title |
seo_description | string(160) | yes | null | SEO meta description |
metadata | jsonb | yes | null | Additional custom data |
created_at | timestamp | yes | null | Creation timestamp |
updated_at | timestamp | yes | null | Last update timestamp |
CollectionRule Table
| Column | Type | Nullable | Description |
|---|---|---|---|
id | bigint | no | Primary key |
rule | string | no | Rule type (Rule enum value) |
operator | string | no | Comparison operator (Operator enum value) |
value | string | no | Value to compare against: cents for price rules, a Y-m-d date for the creation date rule, 1 or 0 for the featured rule |
collection_id | bigint | no | Foreign key to collection. Rules are deleted with their collection |
created_at | timestamp | yes | Creation timestamp |
updated_at | timestamp | yes | Last update timestamp |
Collection Types
use Shopper\Core\Enum\CollectionType;
CollectionType::Manual // Products are manually selected
CollectionType::Auto // Products are added based on rulesType Checking
$collection->isManual(); // true for manual collections
$collection->isAutomatic(); // true for automatic collectionsRelationships
Products
A collection groups products together for merchandising, such as "Summer Essentials", "New Arrivals", or "Black Friday Deals". For manual collections, you explicitly attach and detach products. For automatic collections, products are matched by rules (see Collection Rules) and products holds the last synced matches.
$collection->products;For manual collections, manage products with the standard Eloquent relationship methods:
$collection->products()->attach([$productId1, $productId2]);
$collection->products()->detach($productId);
$collection->products()->sync($productIds);Zones
Collections can be scoped to specific geographic zones. This is useful when a promotion or product group only applies to certain markets.
$collection->zones;
$collection->zones()->attach([$zoneId1, $zoneId2]);
$collection->zones()->detach($zoneId);
$collection->zones()->sync($zoneIds);From the zone side, you can retrieve all associated collections:
use Shopper\Core\Models\Zone;
$zone = Zone::query()->find($id);
$zone->collections;Rules (Automatic Collections)
Automatic collections use rules to determine which products belong to them. Each rule defines a condition that products must match.
$collection->rules;Add a rule that matches products whose title contains "summer":
use Shopper\Core\Enum\Operator;
use Shopper\Core\Enum\Rule;
$collection->rules()->create([
'rule' => Rule::ProductTitle,
'operator' => Operator::Contains,
'value' => 'summer',
]);Slug & Lookup
When you assign a slug, the HasSlug trait passes it through Str::slug() and appends -1, -2 and so on when another collection already uses it. The trait does not build the slug from name: the admin fills it from the name, but in code you pass it yourself.
The findBySlug() static method returns the collection or throws a ModelNotFoundException, which Laravel turns into a 404 response:
use Shopper\Models\Collection;
$collection = Collection::findBySlug('summer-essentials');Query Scopes
Filter collections by type:
Collection::query()->manual()->get();
Collection::query()->automatic()->get();The published scope filters collections that have a published_at date in the past or present:
Collection::query()->published()->get();Collection Rules
Rule Types
use Shopper\Core\Enum\Rule;
Rule::ProductTitle // Match product title
Rule::ProductPrice // Match product price
Rule::CompareAtPrice // Match compare at price
Rule::InventoryStock // Match stock level
Rule::ProductBrand // Match product brand
Rule::ProductCategory // Match product category
Rule::ProductCreatedAt // Match product creation date
Rule::ProductFeatured // Match featured status
Rule::ProductRating // Match average rating
Rule::ProductSalesCount // Match total units sold| Rule | Database Value | Description |
|---|---|---|
| Product Title | product_title | Match against product name |
| Product Price | product_price | Match against amount on prices table (stored in cents) |
| Compare At Price | compare_at_price | Match against compare_amount on prices table (stored in cents) |
| Inventory Stock | inventory_stock | Match against the product's total stock across all locations |
| Product Brand | product_brand | Match against brand name |
| Product Category | product_category | Match against category name |
| Product Created Date | product_created_at | Match against creation date (Y-m-d) |
| Product Featured | product_featured | Match featured status (1 or 0) |
| Product Rating | product_rating | Match average approved rating |
| Product Sales Count | product_sales_count | Match total units sold (orders with status processing or completed and payment status paid) |
Price rules (ProductPrice, CompareAtPrice) store values in cents. Pass the value in cents directly (e.g., '5000' for $50.00). For a zero-decimal currency, pass the amount as-is, like prices. Price rules are evaluated against the shop's default currency.
Sales count (ProductSalesCount) only counts units from orders with the status processing or completed and the payment status paid.
Operators
use Shopper\Core\Enum\Operator;
Operator::EqualsTo // equals_to
Operator::NotEqualTo // not_equal_to
Operator::GreaterThan // greater_than
Operator::LessThan // less_than
Operator::StartsWith // starts_with
Operator::EndsWith // ends_with
Operator::Contains // contains
Operator::NotContains // not_containsEach rule accepts a subset of these operators, returned by Rule::allowedOperators(). Text rules (title, brand, category) accept equals_to, not_equal_to, starts_with, ends_with, contains and not_contains. Numeric rules (prices, stock, rating, sales count) accept equals_to, not_equal_to, greater_than and less_than.
use Shopper\Core\Enum\Rule;
$operators = Rule::ProductPrice->allowedOperators();Match Conditions
When a collection has multiple rules, match_conditions determines how they combine. With all, every rule must match. With any, a single matching rule is enough. The column has no default: any value other than all, including null, behaves as any.
$collection->match_conditions = 'all';
$collection->match_conditions = 'any';Display Helpers
The firstRule() method returns a summary of an automatic collection's first rule and the number of other rules, like Product title Contains summer + 2 other(s). The labels come from the translation files and price values are formatted with shopper_money_format(). It returns null for manual collections:
$collection->firstRule();Creating Collections
Manual Collection
use Shopper\Models\Collection;
use Shopper\Core\Enum\CollectionType;
$collection = Collection::query()->create([
'name' => 'Summer Essentials',
'slug' => 'summer-essentials',
'type' => CollectionType::Manual,
'published_at' => now(),
]);
$collection->products()->attach([$product1->id, $product2->id]);Automatic Collection
Automatic collections populate themselves based on rules. Here's a "Sale Items" collection that matches products under $50 with "sale" in the title:
use Shopper\Core\Enum\CollectionType;
use Shopper\Core\Enum\Operator;
use Shopper\Core\Enum\Rule;
use Shopper\Models\Collection;
$collection = Collection::query()->create([
'name' => 'Sale Items',
'slug' => 'sale-items',
'type' => CollectionType::Auto,
'match_conditions' => 'all',
'published_at' => now(),
]);
$collection->rules()->createMany([
[
'rule' => Rule::ProductPrice,
'operator' => Operator::LessThan,
'value' => '5000',
],
[
'rule' => Rule::ProductTitle,
'operator' => Operator::Contains,
'value' => 'sale',
],
]);getProducts() and productsQuery() evaluate these rules right away. Rules created in code do not fill the products relationship on their own: run the sync action after creating them.
Best Sellers Collection
A collection that automatically includes products with more than 10 units sold in paid orders:
$collection = Collection::query()->create([
'name' => 'Best Sellers',
'slug' => 'best-sellers',
'type' => CollectionType::Auto,
'match_conditions' => 'all',
'published_at' => now(),
]);
$collection->rules()->create([
'rule' => Rule::ProductSalesCount,
'operator' => Operator::GreaterThan,
'value' => '10',
]);Top Rated Collection
A collection of products whose average approved rating is above 3:
$collection = Collection::query()->create([
'name' => 'Top Rated',
'slug' => 'top-rated',
'type' => CollectionType::Auto,
'match_conditions' => 'all',
'published_at' => now(),
]);
$collection->rules()->create([
'rule' => Rule::ProductRating,
'operator' => Operator::GreaterThan,
'value' => '3',
]);Retrieving Collections
All published collections:
$collections = Collection::query()->published()->get();A collection with its products. productsQuery() only returns published products, so you do not filter them again:
$collection = Collection::findBySlug('summer-essentials');
$products = $collection->productsQuery()->get();Filter by type:
$manualCollections = Collection::query()->manual()->get();
$autoCollections = Collection::query()
->automatic()
->with('rules')
->get();Retrieving Products
Shopper provides built-in methods to retrieve products from collections, handling both manual and automatic collections transparently.
Basic Usage
The getProducts() method works for both collection types. For manual collections it returns the attached products. For automatic collections it evaluates the rules and returns the matching products. In both cases, only published products (visible, with a published_at date in the past or present) are returned.
$collection = Collection::query()->find($id);
$products = $collection->getProducts();For pagination or additional filtering, use productsQuery() which returns an Eloquent builder:
$products = $collection->productsQuery()->paginate(12);
$products = $collection->productsQuery()
->where('featured', true)
->orderBy('name')
->get();How It Works
For manual collections, getProducts() returns the published products attached through the products() relationship.
For automatic collections, getProducts() evaluates all defined rules and returns matching products. A collection without rules returns no products:
- Match All:
match_conditionsisall, all rules must be satisfied (AND logic) - Match Any: any other value, at least one rule must be satisfied (OR logic)
$collection = Collection::query()
->where('slug', 'sale-items')
->with('rules')
->first();
$products = $collection->getProducts();Rule Evaluation
The CollectionProductsQuery class handles rule evaluation for all supported rules:
| Rule | Column/Relation | Supported Operators |
|---|---|---|
ProductTitle | name | Text operators |
ProductPrice | amount (prices table) | Numeric operators |
CompareAtPrice | compare_amount (prices table) | Numeric operators |
InventoryStock | inventoryHistories (SUM quantity) | Numeric operators |
ProductBrand | brand relation | Text operators |
ProductCategory | categories relation | Text operators |
ProductCreatedAt | created_at | equals_to, less_than, greater_than |
ProductFeatured | featured | equals_to |
ProductRating | ratings relation (AVG) | Numeric operators |
ProductSalesCount | order_items (SUM quantity) | Numeric operators |
Price, stock and sales count rules read the product's own prices, inventory movements and order lines: the prices, stock and sales of its variants are not counted. A product with no price in the default currency, no inventory movement or no approved review never matches a price, stock or rating rule. ProductFeatured ignores the operator and compares featured with the value.
use Shopper\Core\Queries\CollectionProductsQuery;
$query = new CollectionProductsQuery();
$products = $query->get($collection);For further customization, use the query builder:
$builder = $query->query($collection);
$products = $builder->with('brand')->paginate(10);To check a single product against the rules, use matches(). It returns false for manual collections and for collections without rules:
$isMatching = $query->matches($collection, $product);Automatic Synchronization
For automatic collections, Shopper also stores the matching products in the product_has_relations pivot table, so $collection->products, $product->collections and withCount('products') work as they do for manual collections. getProducts() and productsQuery() do not read this table: they always evaluate the rules.
How Sync Works
Two events start a sync:
| Event | Action |
|---|---|
| Product saved (created or updated) | SyncProductWithCollectionsJob adds the product to, or removes it from, every automatic collection |
| Conditions saved in the admin | SyncCollectionProductsJob re-syncs that collection |
Nothing else starts a sync. Creating or updating a collection or its rules in code leaves the pivot table as it was, and so do changes to prices, stock, orders or reviews, because they do not save the product. Run the sync action after changing rules in code, and schedule the sync command if you use price, stock, rating or sales count rules.
Manual Sync Command
You can manually sync automatic collections using the artisan command:
# Sync all automatic collections
php artisan shopper:collections:sync
# Sync a specific collection
php artisan shopper:collections:sync --collection=1To keep automatic collections current, schedule the command in routes/console.php:
use Illuminate\Support\Facades\Schedule;
Schedule::command('shopper:collections:sync')->hourly();Sync Action
For programmatic sync, use the SyncCollectionProductsAction. It replaces the collection's products with the current matches and returns how many products matched. Manual collections are left untouched and return 0:
use Shopper\Core\Actions\SyncCollectionProductsAction;
use Shopper\Models\Collection;
$collection = Collection::query()->find($id);
$action = new SyncCollectionProductsAction();
$syncedCount = $action->execute($collection);Background Jobs
Sync operations run in queued jobs to avoid blocking requests:
Shopper\Core\Jobs\SyncCollectionProductsJob- Syncs a single collectionShopper\Core\Jobs\SyncProductWithCollectionsJob- Syncs a product with all automatic collections
You can dispatch them yourself:
use Shopper\Core\Jobs\SyncCollectionProductsJob;
SyncCollectionProductsJob::dispatch($collection);Configure your queue worker to process these jobs:
php artisan queue:workMedia
Collections support two media collections through Spatie MediaLibrary, using the same config-driven collection names as products.
| Collection | Config key | Behavior | Description |
|---|---|---|---|
| Default gallery | shopper.media.storage.collection_name | Multiple files | Collection images |
| Thumbnail | shopper.media.storage.thumbnail_collection | Single file | Collection cover image |
To add a collection cover image:
$mediaCollection = config('shopper.media.storage.thumbnail_collection');
$collection->addMedia($file)->toMediaCollection($mediaCollection);To retrieve the cover URL:
$mediaCollection = config('shopper.media.storage.thumbnail_collection');
$url = $collection->getFirstMediaUrl($mediaCollection, 'medium');Configuration
Disabling Collections
// config/shopper/features.php
use Shopper\Enum\FeatureState;
return [
'collection' => FeatureState::Disabled,
];This removes the collection pages and their sidebar entry from the admin and hides the collections field in the product forms. The models, the queries and the product sync keep working.
Permissions
The admin panel generates five permissions for collection management:
| Permission | Description |
|---|---|
browse_collections | View the collections list |
read_collections | View a single collection |
add_collections | Create new collections |
edit_collections | Edit existing collections |
delete_collections | Delete collections |
Components
To customize the admin UI for collection management:
php artisan shopper:component:publish collectionCreates config/shopper/components/collection.php:
use Shopper\Livewire;
return [
'pages' => [
'collection-index' => Livewire\Pages\Collection\Index::class,
'collection-edit' => Livewire\Pages\Collection\Edit::class,
],
'components' => [
'collections.products' => Livewire\Components\Collection\CollectionProducts::class,
'slide-overs.collection-rules' => Livewire\SlideOvers\CollectionRules::class,
'slide-overs.add-collection-form' => Livewire\SlideOvers\AddCollectionForm::class,
'slide-overs.collection-products-list' => Livewire\SlideOvers\CollectionProductsList::class,
],
];Storefront Example
namespace App\Http\Controllers;
use Shopper\Models\Collection;
class CollectionController extends Controller
{
public function index()
{
$collections = Collection::query()
->published()
->withCount('products')
->get();
return view('collections.index', compact('collections'));
}
public function show(string $slug)
{
$collection = Collection::findBySlug($slug);
// Works for both manual and automatic collections
$products = $collection->productsQuery()
->with(['brand', 'media'])
->paginate(12);
return view('collections.show', compact('collection', 'products'));
}
}withCount('products') counts rows in the pivot table: every attached product for a manual collection, published or not, and the last synced matches for an automatic one.
Use Cases
| Type | Example | Description |
|---|---|---|
| Manual | Gift Guides | Curated selection of gift ideas |
| Manual | Editor's Picks | Hand-picked featured products |
| Auto | New Arrivals | ProductCreatedAt greater than a fixed date, such as 2026-09-01 |
| Auto | Sale Items | CompareAtPrice greater than 0 |
| Auto | Low Stock | InventoryStock less than 5 |
| Auto | Featured | ProductFeatured equals 1 |
| Auto | Best Sellers | ProductSalesCount greater than 10 |
| Auto | Top Rated | ProductRating greater than 3 |
Last updated on
Edit on GitHub