# Attributes (/1.x/attributes) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. # Brands (/1.x/brands) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. Unless you make your own products, you should always register the brands of your products in Shopper. If you sell your own products, you must at least create your company as a brand: this helps your customer find what they are looking for, and this can bring some valuable search engine points. ## Overview [#overview] The management of brands is exactly the same as the one done in most of the e-commerce website creation tools: only the name can change. It is mainly used to facilitate the navigation of customers in your catalog, as it is increasingly common to search for a specific brand. ![Brands](/images/v1/brands.png) New brands are automatically activated and available for your online store, even if they do not contain any products yet. You must deactivate them so that they do not appear online. ### Fields [#fields] The model used is `Shopper\Framework\Models\Shop\Product\Brand`. | Name | Type | Required | Notes | |-------------|-----------|------------|------------| | `id` | autoinc | | auto | | `name` | string | yes | | | `slug` | string | yes | Unique, default value is auto generated using brand name | | `website` | string | no | Nullable | | `description` | longText | no | Nullable | | `position` | string | no | Default `0` | | `is_enabled` | boolean | no | Default `false` | | `seo_title` | string | no | Nullable, for seo title max length is 60 | | `seo_description` | string | no | Nullable, for seo description max length is 160 | Models are customizable, and we recommend changing the **Brand** model when you configure your site. To change the model you need to look at the configuration file `config/shopper/system.php` at the key `models`. ```php return [ 'models' => [ /* * Eloquent model should be used to retrieve your brands. Of course, * it is often just the "Brand" model but you may use whatever you like. * * The model you want to use as a Brand model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Brand` model. */ 'brand' => \Shopper\Framework\Models\Shop\Product\Brand::class, /* * Eloquent model should be used to retrieve your categories. Of course, * it is often just the "Category" model but you may use whatever you like. * * The model you want to use as a Category model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Category` model. */ 'category' => \Shopper\Framework\Models\Shop\Product\Category::class, ] ]; ``` 1. Create your own model that you have to use ```bash php artisan make:model Brand ``` Once the `app/Models/Brand.php` model is created in our app folder, we will make it extend from the `Shopper\Framework\Models\Shop\Product\Brand` model available in Shopper. 2. Extend our Brand model from the Brand Shopper Model ```php namespace App\Models; use Shopper\Framework\Models\Shop\Product; class Brand extends Product\Brand { } ``` 3. Update `brand` key for the model on the `system.php` config file to use our new model ```php return [ 'models' => [ /* * Eloquent model should be used to retrieve your brands. Of course, * it is often just the "Brand" model but you may use whatever you like. * * The model you want to use as a Brand model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Brand` model. */ 'brand' => \App\Models\Brand::class, /* * Eloquent model should be used to retrieve your categories. Of course, * it is often just the "Category" model but you may use whatever you like. * * The model you want to use as a Category model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Category` model. */ 'category' => \Shopper\Framework\Models\Shop\Product\Category::class, ] ]; ``` ### Components [#components] Livewire components for managing brands are available in the component configuration file `config/shopper/components.php`. ```php use Shopper\Framework\Http\Livewire; return [ 'livewire' => [ 'brands.browse' => Livewire\Brands\Browse::class, 'brands.create' => Livewire\Brands\Create::class, 'brands.edit' => Livewire\Brands\Edit::class, 'tables.brands-table' => Livewire\Tables\BrandsTable::class, ]; ]; ``` For handling tables in Shopper, we use [Laravel Livewire Tables](https://github.com/rappasoft/laravel-livewire-tables) package by Anthony Rappa. ## Manage Brands [#manage-brands] The brands are accessible via the Brands Menu on the left sidebar. The display page is rendered by the Livewire component `Shopper\Framework\Http\Livewire\Brands\Browse` and for the display of the brands table is the component `Shopper\Framework\Http\Livewire\Tables\BrandsTable`. You can modify them in the component configuration file to use your own. ### Create brand [#create-brand] Click on the "Create" button on the brands page, and a creation form appears. ![Create brand](/images/v1/create-brand.png) Save your changes in order to be taken back to the brand's list. Required fields are marked with an **asterisk (*)** The SEO section allows you to define how your brand information should be displayed in search engines. To modify the content you click on the button "Edit SEO preview" ![brand seo form](/images/v1/brand-seo.png) By fill the data you will have a direct preview of the content. ### Delete brand [#delete-brand] To delete, deactivate or activate brands, you need to select the brand you want to delete and then click on the "Bulk Actions" button to choose the action you want to perform. ![delete brand](/images/v1/delete-brand.png) ## Retrieve Data [#retrieve-data] Once you have your brands and you want to display them in your store, you can retrieve them this way in your controller ```php namespace App\Http\Controllers; use App\Models\Brand; use App\Models\Product; use Carbon\Carbon; class HomeController extends Controller { public function home() { $products = Product::with('categories', 'attributes') ->publish() ->take(8) ->get() ->map(function ($product) { $product['is_new'] = $product->created_at ->addDays(8) ->greaterThanOrEqualTo(Carbon::now()); return $product; }); return view('home', [ 'products' => $products, 'brands' => Brand::query()->get()->take(12), ]); } } ``` Knowing that your brands can be displayed on several pages and places in your store, you can create a **View Composer** ([read more about View Composer](https://laravel.com/docs/9.x/views#view-composers)). - Create your brand composer undo a custom folder `app/View/Composers` ```php namespace App\View\Composers; use App\Models\Brand; use Illuminate\View\View; class BrandsComposer { public function compose(View $view) { $view->with('brands', Brand::enabled()->get()->take(12)); } } ``` - Then you have to add it in your **AppServiceProvider** ```php namespace App\Providers; use App\View\Composers\BrandsComposer; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function boot() { View::composer('partials.brands', BrandsComposer::class); } } ``` And in your front-end you can browse your brands to have a display like this ![Brands preview list](/images/v1/brand-lists.png) # Categories (/1.x/categories) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. For example, if you sell clothing, you might have “t-shirts”, “hoodies” and “pants” as categories. ## Overview [#overview] Shopper gives you a possibility to categorize your products in a very flexible way, which is one of the most vital functionalities of the modern e-commerce systems. The categories system in Shopper use the [Laravel Adjacency List](https://github.com/staudenmeir/laravel-adjacency-list) package to create categories trees like this ```text Category | |\__ Women | \_ T-Shirts | \_ Shirts | \_ Dresses | \_ Shoes | |\__ Men | \_ Accessories | |--> Bags | |--> Jeans | |--> Sunglasses | \_ Jeans | \_ T-shirts | \_ Shoes | ``` ![Categories](/images/v1/categories.png) ### Fields [#fields] The model used is `Shopper\Framework\Models\Shop\Product\Category`. | Name | Type | Required | Notes | |-------------|-----------|------------|------------| | `id` | autoinc | | auto | | `name` | string | yes | | | `slug` | string | yes | Unique, default value is generated using category name | | `description` | longText | no | Nullable | | `position` | string | no | Default `0` | | `is_enabled` | boolean | no | Default `false` | | `seo_title` | string | no | Nullable, for seo title max length is 60 | | `seo_description` | string | no | Nullable, for seo description max length is 160 | | `parent_id` | bigint | no | | Models are customizable, and we recommend changing the **Category** model when you configure your store. To change the model you need to look at the configuration file `config/shopper/system.php` at the key `models`. Let's keep in mind the modification that was made in the previous section regarding [Brands](/1.x/brands). ```php return [ 'models' => [ /* * Eloquent model should be used to retrieve your brands. Of course, * it is often just the "Brand" model but you may use whatever you like. * * The model you want to use as a Brand model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Brand` model. */ 'brand' => \App\Models\Brand::class, /* * Eloquent model should be used to retrieve your categories. Of course, * it is often just the "Category" model but you may use whatever you like. * * The model you want to use as a Category model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Category` model. */ 'category' => \Shopper\Framework\Models\Shop\Product\Category::class, ] ]; ``` 1. Create your own model that you have to use ```bash php artisan make:model Category ``` Once the `app/Models/Category.php` model is created in our app folder, we will make it extend from the `Shopper\Framework\Models\Shop\Product\Category` model available in Shopper. 2. Extend our Category model from the Category Shopper Model ```php namespace App\Models; use Shopper\Framework\Models\Shop\Product; class Category extends Product\Category { } ``` 3. Update `category` key for the model on the `system.php` config file to use our new model ```php return [ 'models' => [ /* * Eloquent model should be used to retrieve your brands. Of course, * it is often just the "Brand" model but you may use whatever you like. * * The model you want to use as a Brand model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Brand` model. */ 'brand' => \App\Models\Brand::class, /* * Eloquent model should be used to retrieve your categories. Of course, * it is often just the "Category" model but you may use whatever you like. * * The model you want to use as a Category model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Category` model. */ 'category' => \App\Models\Category::class, ] ]; ``` ### Components [#components] Livewire components for managing categories are available in the component configuration file `config/shopper/components.php`. ```php use Shopper\Framework\Http\Livewire; return [ 'livewire' => [ 'categories.browse' => Livewire\Categories\Browse::class, 'categories.create' => Livewire\Categories\Create::class, 'categories.edit' => Livewire\Categories\Edit::class, 'tables.categories-table' => Livewire\Tables\CategoriesTable::class, ]; ]; ``` ## Manage Categories [#manage-categories] Categories are determinant of how people will navigate on your site and search for your products. You should focus on your category tree and how categories are organized even before you start creating product sheets. The categories are accessible via the **Categories** Menu on the left sidebar. The display page is rendered by the Livewire component `Shopper\Framework\Http\Livewire\Categories\Browse` and for the display of the categories table is the component `Shopper\Framework\Http\Livewire\Tables\CategoriesTable`. You can modify them in the component configuration file to use your own. ### Create category [#create-category] Click on the "Create" button on the categories page, and a creation form appears. ![Create category form](/images/v1/create-category.png) Save your changes in order to be taken back to the categories list. Required fields are marked with an **asterisk (*)** The SEO section allows you to define how your category information should be displayed in search engines. To modify the content you click on the button "Edit SEO preview". It uses the same blade component as the brands. ![Seo form](/images/v1/seo-preview.gif) Once you have finished configuring your category, save it, and you are ready to fill it with products. If you use another interface (e.g. API) to save your categories, you can save directly using your Model ```php use App\Models\Category; $category = Category::create([ 'name' => $name = 'Clothes', 'slug' => $name, 'is_enabled' => true, ]); ``` The slug cannot be null, you have to fill in the value of the category name and according to that the slug will be generated. In case a slug already exists, the slug will be automatically extended to prevent duplicates: ```php use App\Models\Category; $category1 = Category::create(['name' => 'Category', 'slug' => 'Category']); $category2 = Category::create(['name' => 'Category', 'slug' => 'Category']); echo $category1->slug; // category echo $category2->slug; // category-1 ``` And if the category has a parent, the child's slug will be generated with the parent's directly This generation is done when adding a category in Shopper. But you can change this behavior by extending the category create [Shopper\Framework\Http\Livewire\Categories\Create](https://github.com/shopperlabs/framework/blob/main/src/Http/Livewire/Categories/Create.php) Livewire component or by creating a new one. ```php use App\Models\Category; $category = Category::create(['name' => 'Photo', 'slug' => 'photo']); $categoryChild = Category::create([ 'name' => 'Camera', 'slug' => $this->parent ? $this->parent->slug . '-' . 'Camera' : 'Camera', 'parent_id' => $caregory->id ]); echo $category->slug; // photo echo $categoryChild->slug; // photo-camera ``` #### Create Category with parent [#create-category-with-parent] ```php use App\Models\Category; $parent = Category::create([ 'name' => $name = 'Clothes', 'slug' => $name, 'is_enabled' => true, ]); $child = Category::create([ 'name' => 'Jeans', 'slug' => 'jeans', 'parent_id' => $parent->id, 'is_enabled' => true, ]); ``` On Shopper, to specify the parent category you just have to choose via the select field ![category parent](/images/v1/category-parent.png) ### Update category [#update-category] The "Modify" button allows you to modify the category. It is important to know that if you update the category name, the slug will automatically be updated as well. ![update category](/images/v1/update-category.png) ## Retrieve Data [#retrieve-data] With Shopper Framework you are the master of your front-end. After extending the model you can make all the necessary queries to retrieve your data. We just recommend that you always use the `enabled` scope to ensure that only active categories are visible ```php use App\Models\Category; $categories = Category::enabled()->get(), ``` To find a category with his children or parent, etc. The following functions are available. - `ancestors()`: The model's recursive parents. - `ancestorsAndSelf()`: The model's recursive parents and itself. - `bloodline()`: The model's ancestors, descendants and itself. - `children()`: The model's direct children. - `childrenAndSelf()`: The model's direct children and itself. - `descendants()`: The model's recursive children. - `descendantsAndSelf()`: The model's recursive children and itself. - `parent()`: The model's direct parent. - `parentAndSelf()`: The model's direct parent and itself. - `rootAncestor()`: The model's topmost parent. - `siblings()`: The parent's other children. - `siblingsAndSelf()`: All the parent's children. ```php $ancestors = Category::find($id)->ancestors; $categories = Category::with('descendants')->get(); $categories = Category::whereHas('siblings', function ($query) { $query->where('name', '=', 'Photo'); })->get(); $total = Category::find($id)->descendants()->count(); Category::find($id)->descendants()->update(['is_enabled' => false]); Category::find($id)->siblings()->delete(); ``` The complete documentation is available in the readme of [Laravel Adjacency List](https://github.com/staudenmeir/laravel-adjacency-list) # Collections (/1.x/collections) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. In most e-commerce tools, collections are considered as categories. And especially on Shopify, collections are a great feature for grouping products. And for the constitution of the collections we got closer to what Shopify offers in terms of configuration, and the management of collections in Shopper is inspired by Shopify. ## Context [#context] For example if you have a store that sells various electronic products, you will probably have categories like "Phones", "Computers", "Cameras" etc. Each of these categories may have several products that can be listed. And to try to group the products in an even more detailed way you can create for example a collection called "Gaming Collection" and specify in this collection that any product with certain conditions can be included. And that Gaming Collection can have products that even come from various categories in your site (desktop, laptop, monitor, and many others of the same type) or that don't even have categories (very rare case in e-commerce sites). Let's use Netflix as an example. Categories are essentially genres: adventure, action, horror, romance, etc., while collections are similar to a TV series or movie sequels that are ultimately meant to be viewed together. ## Collections vs Categories [#collections-vs-categories] The question is essential, it is difficult to find this type of configuration on e-commerce tools because most of the time categories, collections or taxonomies are used to perform the same action **group products**. The advantage of having collections in addition to categories in Shopper is to differentiate or optimize the search for products by customers in your store. ### Depth [#depth] A collection can't have a child or a parent like a category. So all the collections are at the same hierachical level. ### Condition [#condition] Where products can be added to any category, collections cannot. Depending on the type of collection you want to create (Manual or Automatic) you will find yourself creating conditions or rules for the products that should be in that collection. ## Overview [#overview] As mentioned above, the collections in Shopper are inspired by [Shopify collections](https://help.shopify.com/en/manual/products/collections). So there are also 2 types of collections: "Manual" and "Automatic" and the configuration for each is different. ![Collections](/images/v1/collections.png) ### Fields [#fields] As the collections can be automatic, they are managed by 2 Models, the Collection model and the model for rules associated with automatic collections. Manual collections do not need to have rules. - Collection model is `Shopper\Framework\Models\Shop\Product\Collection`. - Rule model is `Shopper\Framework\Models\Shop\Product\CollectionRule` **Collection Model** | Name | Type | Required | Notes | |-------------|-----------|------------|------------| | `id` | autoinc | | auto | | `name` | string | yes | | | `slug` | string | yes | Unique, default value is generated using collection name | | `description` | longText | no | Nullable | | `type` | enum | yes | Values `['manual', 'auto']` | | `sort` | string | no | Nullable, potential values `alpha_asc`, `alpha_desc`, `price_desc`, `price_asc`, `created_desc`, `created_asc` | | `match_conditions` | enum | no | Nullable, `['all', 'any']` | | `published_at` | dateTimeTz | no | Default `now()` | **CollectionRule Model** | Name | Type | Required | Notes | |-------------|-----------|------------|------------| | `id` | autoinc | | auto | | `rule` | string | yes | current values `product_title`, `product_price`, `compare_at_price`, `inventory_stock`, `product_brand`, `product_category` | | `operator` | string | yes | current values `equals_to`, `not_equals_to`, `less_than`, `greater_than`, `starts_with`, `ends_with`, `contains`, `not_contains` | | `value` | string | yes | | | `collection_id` | bigint | no | Collection ID | Models are customizable, and we recommend changing the **Collection** model when you configure your store. To change the model you need to look at the configuration file `config/shopper/system.php` at the key `models`. Let's keep in mind the modification that was made in the previous section regarding [Categories](/1.x/categories). ```php return [ 'models' => [ /* * Eloquent model should be used to retrieve your categories. Of course, * it is often just the "Category" model but you may use whatever you like. * * The model you want to use as a Category model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Category` model. */ 'category' => \App\Models\Category::class, /* * Eloquent model should be used to retrieve your collections. Of course, * it is often just the "Collection" model but you may use whatever you like. * * The model you want to use as a Collection model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Collection` model. */ 'collection' => \Shopper\Framework\Models\Shop\Product\Collection::class, ] ]; ``` 1. Create your own model that you have to use ```bash php artisan make:model Collection ``` Once the `app/Models/Collection.php` model is created in our app folder, we will make it extend from the `Shopper\Framework\Models\Shop\Product\Collection` model available in Shopper. 2. Extend our Collection model from the Collection Shopper Model ```php namespace App\Models; use Shopper\Framework\Models\Shop\Product; class Collection extends Product\Collection { } ``` 3. Update `Collection` key for the model on the `system.php` config file to use our new model ```php return [ 'models' => [ /* * Eloquent model should be used to retrieve your categories. Of course, * it is often just the "Category" model but you may use whatever you like. * * The model you want to use as a Category model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Category` model. */ 'category' => \App\Models\Category::class, /* * Eloquent model should be used to retrieve your collections. Of course, * it is often just the "Collection" model but you may use whatever you like. * * The model you want to use as a Collection model needs to extends the * `\Shopper\Framework\Models\Shop\Product\Collection` model. */ 'collection' => \App\Models\Collection::class, ] ]; ``` ### Components [#components] Livewire components for managing collections are available in the component configuration file `config/shopper/components.php`. ```php use Shopper\Framework\Http\Livewire; return [ 'livewire' => [ 'collections.browse' => Livewire\Collections\Browse::class, 'collections.create' => Livewire\Collections\Create::class, 'collections.edit' => Livewire\Collections\Edit::class, 'collections.products' => Livewire\Collections\Products::class, 'tables.collections-table' => Livewire\Tables\CollectionsTable::class, ]; ]; ``` ## Manage Collections [#manage-collections] Form your Shopper admin on the sidebar go to **Collections**. The display page is rendered by the Livewire component `Shopper\Framework\Http\Livewire\Collections\Browse` and for the display of the collections table is the component `Shopper\Framework\Http\Livewire\Tables\CollectionsTable`. By default you will see this page without data which is rendered by a blade component of Shopper called [empty state](/2.x/extending/empty-state). ![Collections empty data](/images/v1/collection-empty-state.png) ### Create collection [#create-collection] Click on the "Create" button on the collections page, and a creation form appears. ![Create collection form](/images/v1/create-collection.png) Save your changes in order to be taken back to the collections list. Required fields are marked with an **asterisk (*)**. You can create two types of collections as we said: Automatic and manual collection. Only automatic collections have rules for automating them. When you choose to create an automatic collection the rules section will be available in the creation form ![automatic collection rules](/images/v1/collection-rules.png) After you create a collection, you can't change its type. The Livewire component for collection creation is `Shopper\Framework\Http\Livewire\Collections\Create`. Here is the function to save a collection ```php namespace Shopper\Framework\Http\Livewire\Collections; use Shopper\Framework\Models\Shop\Product\CollectionRule; use Shopper\Framework\Repositories\Ecommerce\CollectionRepository; class Create extends Component { public function store() { $this->validate($this->rules()); $collection = (new CollectionRepository())->create([ 'name' => $this->name, 'slug' => $this->name, 'description' => $this->description, 'type' => $this->type, 'match_conditions' => $this->condition_match, 'seo_title' => $this->seoTitle, 'seo_description' => $this->seoDescription, 'published_at' => $this->publishedAt ?? now(), ]); if ($this->fileUrl) { $collection->addMedia($this->fileUrl) ->toMediaCollection(config('shopper.system.storage.disks.uploads')); } if ($this->type === 'auto' && count($this->conditions) > 0 && $this->rule) { foreach ($this->rule as $key => $value) { CollectionRule::query()->create([ 'collection_id' => $collection->id, 'rule' => $this->rule[$key], 'operator' => $this->operator[$key], 'value' => $this->value[$key], ]); } $this->conditions = []; $this->resetConditionsFields(); } session()->flash('success', __('Collection successfully added!')); $this->redirectRoute('shopper.collections.edit', $collection); } } ``` ## Retrieve Data [#retrieve-data] After extending the Shopper Collection model you can use your own model to retrieve data from the database. Here an example code. ```php use App\Models\Collection; // To retrieve only manual collections $collections = Collection::manual()->get(); // To retrieve collection by slug $collection = Collection::findBySlug('summers-clothes'); ``` To view the image of a collection you can consult the [media documentation](/1.x/media#retrieving-images). And you can display collections in your frontend. ![example collection rules](/images/v1/collections-preview.png) # Configuration (/1.x/configuration) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. ## Config Files [#config-files] With the installation of Shopper you will find new configurations files located in `config/shopper/`. They are PHP files named by area of responsibility. ```text config/shopper/ admin.php auth.php components.php core.php media.php models.php routes.php settings.php ``` And the `admin.php` is the main file, you can find various options to change the configuration of your Shopper installation. ## System [#system] All the basic configurations for using shopper can be found in this file. The management of the locale, the models to use and additional resources (scripts and styles) to the administration. ### Brand logo [#brand-logo] By default, the Shopper logo will be used as the brand logo in the administration panel. To update it you just have to fill in the logo link in your public folder ```php /* |-------------------------------------------------------------------------- | Brand Name |-------------------------------------------------------------------------- | | This will be displayed on the login page and in the sidebar's header. | */ 'brand' => '/images/v1/logo.svg', ``` ### Controllers [#controllers] By default Shopper loads controllers that are defined in this namespace. You can change it if you have a different structure. These controllers are used to extend and add functionalities in the administration. In your config file you have the controllers key that define the controller's namespace for your extended Controllers: ``` php 'controllers' => [ 'namespace' => 'App\\Http\\Controllers\\Shopper', ], ``` ### Models [#models] Models used are defined in the models key, if you want to use your own models you can replace them on the `models.php` config file. ``` php 'brand' => \Shopper\Core\Models\Brand::class, 'category' => \Shopper\Core\Models\Category::class, 'collection' => \Shopper\Core\Models\Collection::class, 'product' => \Shopper\Core\Models\Product::class, ``` ### Additional resources [#additional-resources] During your work you may need to add your own style tables or javascript scenarios globally for all the pages, so you need to add them to relevant arrays. ```php 'resources' => [ 'stylesheets' => [ //'css/custom.css', ], 'scripts' => [ //'js/custom.js', ], ], ``` ## Routes [#routes] The configuration of the routes allows you to specify a prefix to access your dashboard, the addition of middleware and the configuration file to add more routes to your administration. ### Prefix [#prefix] ```php // config/shopper/admin.php 'prefix' => env('SHOPPER_PREFIX', 'cpanel'), ``` The system installed on the website can be easily defined by the dashboard prefix, for example it is `wp-admin` for WordPress, and it gives an opportunity to automatically search for old vulnerable versions of software and gain control over it. There are other reasons but we won't speak of them in this section. The point is that Shopper allows to change dashboard prefix to every other name, `admin` or `administrator` for example. ### Middleware [#middleware] ```php // config/shopper/routes.php 'middleware' => [], ``` Shopper gives you the ability to add middleware to all of your routes. These middlewares will be applied to all the routes of your administration. ### Additional dashboard routes [#additional-dashboard-routes] ```php // Eg.: base_path('routes/shopper.php') 'custom_file' => null, ``` By default none of your routes in the `web.php` file will be accessible and loaded in the shopper administration. So that your routes added in the sidebar can have the middleware applied to the dashboard, you must fill in an additional routing file and this will be automatically loaded by Shopper's internal RouteServiceProvider. ## Components [#components] The main features of Shopper is to handle Livewire components to add new functionnalities to your admin panel. For this purpose you have a component file that lists all Livewire components used within Shopper. You can for each feature modify the associated or extends component to add functionality or even change the view to fit your own logic. Here is an example of some components ```php use Shopper\Http\Livewire\Components; return [ /* |-------------------------------------------------------------------------- | Livewire Components |-------------------------------------------------------------------------- | | Below you reference all the Livewire components that should be loaded | for your app. By default all components from Shopper Kit are loaded in. | */ 'livewire' => [ 'account.devices' => Components\Account\Devices::class, 'account.dropdown' => Components\Account\Dropdown::class, 'account.password' => Components\Account\Password::class, ], ]; ``` ## Settings [#settings] Settings are a very important part of an e-commerce site administration. Shopper has understood this very well and has set up a settings file, to allow you to add or modify the default settings of Shopper. In this file you can add parameters or delete those you don't need to simplify your store or to make it larger ```php return [ /* |-------------------------------------------------------------------------- | Setting Menu |-------------------------------------------------------------------------- | | The menu for the generation of the page settings and layout. | BladeUIKit Heroicon is the icon used. See https://blade-ui-kit.com/blade-icons?set=1 | */ 'items' => [ [ 'name' => 'General', 'description' => 'View and update your store information.', 'icon' => 'heroicon-o-cog', 'route' => 'shopper.settings.shop', 'permission' => null, ], [ 'name' => 'Staff & permissions', 'description' => 'View and manage what staff can see or do in your store.', 'icon' => 'heroicon-o-users', 'route' => 'shopper.settings.users', 'permission' => null, ], ], ]; ``` ## Mapbox [#mapbox] Shopper uses Mapbox to enter the geographic coordinates (latitude and longitude) of your store so that you can easily tell your customers your location. To activate mapbox you need to go to the [API](https://docs.mapbox.com/mapbox-gl-js/api/) documentation and create an API token. Once this is done you need to add the key `MAPBOX_PUBLIC_TOKEN` with the token value to your `.env` file ```bash MAPBOX_PUBLIC_TOKEN=your_token_here ``` ## Update Configurations [#update-configurations] In your `config/filesystems.php` config file add the following to the disks and links section: ``` php 'disks' => [ // Shopper Uploads Disks. [tl! highlight:13] 'avatars' => [ // [tl! collapse:start] 'driver' => 'local', 'root' => storage_path('app/avatars'), 'url' => env('APP_URL').'/avatars', 'visibility' => 'public', ], // [tl! collapse:end] 'uploads' => [ // [tl! collapse:start] 'driver' => 'local', 'root' => storage_path('app/uploads'), 'url' => env('APP_URL').'/uploads', 'visibility' => 'public', ], // [tl! collapse:end] ], /* |-------------------------------------------------------------------------- | Symbolic Links |-------------------------------------------------------------------------- | | Here you may configure the symbolic links that will be created when the | `storage:link` Artisan command is executed. The array keys should be | the locations of the links and the values should be their targets. | */ 'links' => [ // [tl! highlight:2] public_path('avatars') => storage_path('app/avatars'), public_path('uploads') => storage_path('app/uploads'), ], ``` ### Create New Folders [#create-new-folders] After adding the 2 entries in the filesystem config file, you must create them and add them to the .gitignore file. In your storage directory create 2 new folders called `avatars` and `uploads`. ```bash mkdir storage/app/avatars && mkdir storage/app/uploads ``` In each new folder that you have created (avatars and uploads) you must create a .gitignore file which will contain the following line ```bash * !.gitignore ``` # Contribution Guide (/1.x/contributing) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. ## Bug Reports [#bug-reports] To encourage active collaboration, Shopper strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test. ## Pull Requests [#pull-requests] - **Document any change in behaviour** - Make sure the `readme.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. **Happy coding**! ## Security Vulnerabilities [#security-vulnerabilities] If you discover a security vulnerability within Laravel, please send an email to the Shopper Team at [arthur@shopperlabs.co](mailto:arthur@shopperlabs.co). All security vulnerabilities will be promptly addressed. ## Coding Style [#coding-style] Laravel follows the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) coding standard and the [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md) autoloading standard. ## Code of Conduct [#code-of-conduct] As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of the level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. # Customers (/1.x/customers) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. The first page under the "Customers" menu gives you a list of all the registered users on your shop. ![Customers](/images/v1/customers.png) During the [installation](/1.x/installation#update-existing-files) of Shopper, one of the first things required is to inherit to our model User the features of the model User that is in Shopper. ## Fields [#fields] The model used is `App\Models\User` which extends the `\Shopper\Framework\Models\User\User` model. During the installation of Shopper, the `name` column of the users table is removed and replaced by 2 new fields which are `first_name` and `last_name`. | Name | Type | Required | Notes | |-------------|-----------|------------|------------| | `id` | autoinc | | auto | | `first_name` | string | no | Nullable | | `last_name` | string | yes | | | `email` | string | yes | Unique | | `password` | string | no | Nullable | | `email_verified_at` | timestamp | no | Nullable | | `gender` | enum | yes | values `['male', 'female']` | | `phone_number` | string | no | Nullable | | `birth_date` | date | no | Nullable | | `avatar_type` | string | no | default [ui-avatars](https://ui-avatars.com/) | | `avatar_location` | string | no | Nullable, picture filename | | `timezone` | string | no | Nullable | | `opt_in` | boolean | no | default `false`, this field is for mailing subcription | | `last_login_at` | timestamp | no | Nullable | | `last_login_ip` | string | no | Nullable | ## Components [#components] The components used to manage customers are found in the component configuration file `config/shopper/components.php`. ```php use Shopper\Framework\Http\Livewire; return [ 'livewire' => [ 'modals.delete-customer' => Livewire\Modals\DeleteCustomer::class, 'customers.addresses' => Livewire\Customers\Addresses::class, 'customers.browse' => Livewire\Customers\Browse::class, 'customers.create' => Livewire\Customers\Create::class, 'customers.orders' => Livewire\Customers\Orders::class, 'customers.profile' => Livewire\Customers\Profile::class, 'customers.show' => Livewire\Customers\Show::class, 'tables.customers-table' => Livewire\Tables\CustomersTable::class, ]; ]; ``` ## Manage Customers [#manage-customers] When a new customer places an order with your store, their name and information are automatically added to your customer list. A customer profile is created when a customer interacts with your store. Alternatively, you can add a customer to your store manually. ### Create customer [#create-customer] From your Shopper admin, go to Customers and click on "Add customer" button. ![Create customer](/images/v1/create-customer.png) When creating a customer manually, you should also fill in an address that will be used when he places an order in your store. ![customer address form](/images/v1/customer-address.png) _Optional_: If the customer has agreed to receive marketing emails, and you have entered an email address, then in the Customer overview section, check Customer agreed to receive marketing emails. And you can also check the **Send customer credentials** checkbox to sent an email to the customer with their login information. ![customer notification](/images/v1/customer-notification.png) The Livewire component used to create a client is `Shopper\Framework\Http\Livewire\Customers\Create` ```php $customer = (new UserRepository())->create([ 'last_name' => $this->last_name, 'first_name' => $this->first_name, 'email' => $this->email, 'password' => Hash::make($this->password), 'phone_number' => $this->phone_number, 'email_verified_at' => now()->toDateTimeString(), 'opt_in' => $this->opt_in, ]); $customer->assignRole(config('shopper.system.users.default_role')); ``` The clients that are displayed in the listing page are those that have the `user` profile which is the default role associated with all clients. ### Customer's Information [#customers-information] In the case where you would like to have more information on a given customer, you can click on the customer name row in the customer's list. A new page appears. ![customer informations](/images/v1/customer-informations.png) And in this page you can modify the information of a customer by clicking on the "update" button on the right of each information. The various sections provide you with some key data on the user: - **Customer information**, first and last name, e-mail address, picture, birth date, gender. - Registered **Addresses** - **Orders** Summary of purchases already made by the customer. Amount spent, payment type, order status. For more information on each order, click on the order number. Each of its pages are accessible via Livewire components, and are fully customizable to your needs. So don't hesitate to modify them. # Customization (/1.x/customization) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. Once you have installed Shopper, you need to set up a store to serve as your first location. After creating a new user, you need to login via the url `/shopper/login`. After logging in you need to fill in the required information to access the Shopper dashboard ![Shopper Config Example](/images/v1/customization.png) Defines your shop’s address country and state, where you are based as a seller. It determines default tax rates and customer locations. ## Global [#global] All thoses informations is stored using the **Setting** Model which is located `\Shopper\Core\Models\Setting` ```php namespace Shopper\Core\Models; use Illuminate\Database\Eloquent\Model; class Setting extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'display_name', 'key', 'value', 'locked', ]; } ``` ### Fields [#fields] | Name | Type | Notes | |--------------|-----------|------------| | `id` | autoinc | | | `key` | string | Unique, the configuration key that will be used to retrieve this information. | | `display_name` | string | Nullable, represents the display name for the key that has been set for better reading| | `value` | json | Nullable, represents the value of the key that will be displayed when the parameter is requested | | `locked` | boolean | default is false (0), allows to define if this parameter can be updated | ### Component [#component] Shopper is made of several Livewire components, to make the configuration easier and more adaptable to any kind of system. The component used to manage the configuration and customization of the store is found in the component configuration file `config/shopper/components.php`. So you can replace it and configure your store the way you want. Yes it's magic 🎩 ### Retrieving setting [#retrieving-setting] By default to retrieve the value of a key you can use the helper function `shopper_setting()` passing the desired key as parameter ```php shopper_setting('my_key') ``` This value is cached for one day and under the key `shopper-setting-{$key}` ## Store [#store] When you launch your store the first important thing to do is to fill in the information about this store. Your customers and the different services you might use need to know the information about your store. ![Store information](/images/v1/store-information.png) The information stored in this section is available using the following keys: `shop_name` for the store name, `shop_email` for the email and `shop_country_id` for the Country. ## Currency [#currency] Choose the default currency for the store. Only one may be selected. ![Store currency](/images/v1/store-currency.png) For currency configurations we use the [moneyphp/money](https://github.com/moneyphp/money) package. At the moment, the formatter does it automatically depending on the currency. As you may have noticed in the code, there is also a helper that returns the currency you registered `shopper_currency()`. This will return the currency configured in your admin panel: **USD**, **XAF**, **EUR**, etc ## Location [#location] Most stores keep their products in different locations around the world. When setting up this configuration you need to define a location that will be set as the default location for your products. When shipping an order, the products to be delivered/shipped will start from this location and thus the shipping price can be set according to this. ![Store location](/images/v1/customization-map-off.png) You must fill in the address of your location. You can specify GPS coordinates if you want customers to be able to geolocate you on a map with this information. Shopper uses mapbox to display this map. To configure your map you can go to the [mapbox documentation](https://docs.mapbox.com/mapbox-gl-js/api/). ![Store location with mapbox](/images/v1/customization-map.png) The keys registered in the database during this section: `shop_street_address`, `shop_zipcode`, `shop_city`, `shop_phone_number`, `shop_lng` and `shop_lat`. If you modify the Livewire component that takes care of registering those information you can also decide to change the name of its keys. ## Channel [#channel] In today's E-commerce the shop site is no longer the only point of sale. Channels represent a single sales channel, which can be one of the following things: - Website - Mobile application - Cashier in your physical store - Facebook shop, - Instagram shop, - etc or pretty much anything similar you can imagine. By default when you set up your store Shopper creates a sales channel at the same time as your first location with the same location information. ```php (new ChannelRepository())->create([ 'name' => $name = __('Web Store'), 'slug' => $name, 'url' => env('APP_URL'), 'is_default' => true, ]); ``` This sales channel will be automatically assigned to all products that are added to your site. The implementation of a sales channel management will be done later ## Social Links [#social-links] If you want your customers to find you easily on social networks, you can fill in all the links directly by putting the full url. This step is completely optional ![Store social links](/images/v1/customization-social-media.png) The keys registered in the database during this section: `shop_facebook_link`, `shop_instagram_link` and `shop_twitter_link`. ## Update setting [#update-setting] You can update your store information when needed, edit your store images, update the complete address, the legal name of your shop, etc. Shopper at the moment doesn't manage several currencies so you must select with what currency you will sell on your site. To edit your shop information, you must: - From your administration, on the blue sidebar click on the settings icon at the bottom of the page **Settings > General** ![Admin Panel setting](/images/v1/setting.jpg) The component used to update store setting of the store is found in the component configuration file `config/shopper/components.php`, It's the `Shopper\Framework\Http\Livewire\Settings\General` component. ```php use Shopper\Http\Livewire\Components; return [ 'livewire' => [ 'settings.inventories.create' => Components\Settings\Inventories\Create::class, 'settings.inventories.edit' => Components\Settings\Inventories\Edit::class, 'settings.general' => Components\Settings\General::class, 'settings.legal.privacy' => Components\Settings\Legal\Privacy::class, 'settings.legal.refund' => Components\Settings\Legal\Refund::class, ]; ]; ``` ![Admin update setting](/images/v1/store-setting-update.png) In this interface you will update your store. Don't forget that the model used is the model `Shopper\Models\Setting`. With the Shopper configuration you can completely change the architecture of this view and the data stored in the database. # Dashboard (/1.x/dashboard) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. ## Overview [#overview] When you log into the control panel, you will be taken to the dashboard — a customizable screen dispatch with a Livewire component! Shopper is a free open-source e-commerce application based on the [TALL Stack](https://tallstack.dev) and aims to build an e-commerce administration using only [Livewire](https://laravel-livewire.com) components. The navigation at the left contains the available panels for everyday use: ![Shopper Global Set Example](/images/v1/dashboard.png) Clicking on each icon will open the panel or shows a list of available panels. ## Components [#components] The component that displays the dashboard is quite simple, so you can easily replace it to put your own. The component used is `Shopper\Http\Livewire\Pages\Dashboard` and can also be found in the components file `config/shopper/components.php`. ```php namespace Shopper\Http\Livewire\Pages; use Livewire\Component; class Dashboard extends Component { public function render() { return view('shopper::livewire.pages.dashboard') ->layout('shopper::components.layouts.app', [ 'title' => __('shopper::layout.sidebar.dashboard'), ]); } } ``` ## Layout [#layout] Shopper comes with a [Tailwind CSS](https://tailwindcss.com) based design and you can [extend](/1.x/extending/control-panel) the default layout for your components. ``` blade {{-- Your content here --}} ``` All pages that will be on the administration must have this content and extend the default layout of Shopper # Discounts (/1.x/discounts) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. # Control Panel (/1.x/extending/control-panel) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. The control panel may be customized in a number of different ways. You may add new pages, menus, a stylesheet, or maybe you just want to add some arbitrary Javascript. When you need to add features to your Shopper administration, you can first set up some configurations ## Adding CSS and JS assets [#adding-css-and-js-assets] Shopper can load extra stylesheets and Javascript files located in the `public/` directory. You may register assets to be loaded in the Control Panel using the `scripts` and `stylesheets` keys of the resources in the `config/shopper/admin.php` config file. This will accept a array of links. You can load the links locally or using cdn. They will be automatically loaded in the control panel ```php 'resources' => [ 'stylesheets' => [ '/css/admin.css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css', ], 'scripts' => [ 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js', '/js/admin.js', ], ], ``` Depending on how you will use your css and js files, the order is important These commands will make Shopper expect files at `public/css/admin.css` and `public/js/admin.js` respectively for local links. ## Customize Shopper theme [#customize-shopper-theme] Shopper is built using Tallstack presets, but you are not limited to that because the base css file is already built for production. But if you want to customize your dashboard using Tailwind css you must first install Tailwind in your project. You can read the [documentation](https://tailwindcss.com/docs/guides/laravel) Shopper using Tailwind CSS, there are some Tailwind plugins you need to install first: Plugin Forms and Typography, Autoprefixer. You can install them via NPM or Yarn: ```bash yarn add -D tailwindcss @tailwindcss/forms @tailwindcss/typography autoprefixer ``` After installing Tailwind, you need to create a `tailwind.config.js` file at the root of your project and add this content ```js const colors = require('tailwindcss/colors') /** @type {import('tailwindcss').Config} */ module.exports = { darkMode: 'class', presets: [ require('./vendor/shopper/framework/tailwind.config'), ], content: [ './resources/**/*.blade.php', './vendor/shopper/framework/**/*.blade.php', './vendor/filament/**/*.blade.php', './vendor/rappasoft/laravel-livewire-tables/resources/views/**/*.blade.php', './vendor/wire-elements/modal/resources/views/*.blade.php', './vendor/wireui/wireui/resources/**/*.blade.php', './vendor/wireui/wireui/ts/**/*.ts', './vendor/wireui/wireui/src/View/**/*.php' ], theme: { extends: { colors: { primary: colors.blue, secondary: colors.slate, indigo: colors.blue, } } }, plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), ], } ``` New versions of Laravel come with vite by default so if you want to customize the Shopper admin, you need to switch to `Laravel Mix` and in your `webpack.mix.js` file, register Tailwind CSS as a PostCSS plugin: ```js const mix = require('laravel-mix') mix.postCss('resources/css/admin.css', 'public/css', [ require('tailwindcss'), ]) ``` Just load the default Tailwind CSS directives inside your `./resources/css/admin.css` ```css @tailwind base; @tailwind components; @tailwind utilities; ``` Then run `yarn run dev` Keep in mind the `admin.css` file must be load on the `resources` key of your `shopper/admin.php` config file And add Tailwind to the `postcss.config.js` file: ```js module.export = { plugins: { tailwindcss: {}, autoprefixer: {}, }, } ``` ### Branding Logo [#branding-logo] After update (or not) the colors of your administration theme to reflect your brand. You'll probably want to change the logo to display By default, Shopper logo is used next to your application name in the administration panel. You can choose between 2 options The first, and simplest, is to modify the value of the `brand` key in your `shopper/admin.php` configuration file, by entering the link to your logo. ```php /* |-------------------------------------------------------------------------- | Admin Brand Name |-------------------------------------------------------------------------- | | This will be displayed on the login page and in the sidebar's header. | */ 'brand' => 'img/logo.svg', ``` This will load using the Laravel `asset()` helper function. The 2nd option is to create a resources/views/vendor/shopper/components/brand.blade.php file to provide a customized logo: It can be a simple svg or an image tag. ```html Shopper ``` ## Adding control panel routes [#adding-control-panel-routes] If you need to have custom routes for the control panel: 1. Create a routes file. Name it whatever you want, for example: `routes/shopper.php` 2. Then add this to your `shopper/routes.php` file so that all routes are dynamically loaded: ```php 'custom_file' => base_path('routes/shopper.php'), ``` 3. If you want to add middleware to further control access to the routes available in this file you can add in the key `middleware` of the `shopper/routes.php` file ```php 'middleware' => [ 'my-custom-middleware', 'permission:can-access', ], ``` # Controllers (/1.x/extending/controllers) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. Controllers group related Laravel request handling logic into single classes stored in the `app/Http/Controllers/` directory. In this section we will create our own controllers to add functionality to our admin panel. To configure your controllers, you need to look at the `controllers` key in the `shopper/system.php` configuration file. ```php 'controllers' => [ 'namespace' => 'App\\Http\\Controllers\\Shopper', ], ``` This implies that all controllers that will be loaded into the shopper control panel must be in the `app/Http/Controllers/Shopper` folder. But you can change this namespace, you can change it for example to load them into a **CPanel** folder. For this your configuration should look like this ```php 'controllers' => [ 'namespace' => 'App\\Http\\Controllers\\CPanel', ], ``` ## Create Controller [#create-controller] You can create a controller using the following laravel command, which will generate a class in the `App\Http\Controllers\Shopper` namespace. ```bash php artisan make:controller Shopper\\PostController ``` You can now add all your actions and set up the management of your articles ```php namespace App\Http\Controllers\Shopper; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class PostController extends Controller { // } ``` # Navigation (/1.x/extending/navigation) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. The Control Panel navigation is quite customizable. You can add your own sections, pages, and subpages, as well as remove and modify existing ones. The navigation is controlled by the package [maatwebsite/laravel-sidebar](https://github.com/SpartnerNL/Laravel-Sidebar). You need to create a sidebar to add your menus within the main sidebar of Shopper. You may register your sidebar like event in the `register()` method of a service provider. ## Adding Navigation [#adding-navigation] Let's assume we're creating a Sidebar folder under app folder, and want to add a Blog navigation item to the Content section of the navigation. To add this item, we'll create first a `BlogSidebar` class. There is no command to create this class so you have to create it manually and it must extend from `Shopper\Framework\Sidebar\AbstractAdminSidebar` We will have an architecture similar to this one ```text app/ Sidebar/ BlogSidebar.php ``` We assume here that you have already seen how to add routes for our administration explained in this [section](/1.x/extending/control-panel#adding-control-panel-routes). Here we will assume that our `routes/shopper.php` file contains this ```php use Illuminate\Support\Facades\Route; Route::prefix('blog')->group(function () { Route::resource('posts', 'PostController')->only(['index', 'create', 'edit']); }); ``` You cannot use the notation `[PostController::class, 'index']` because this will not load and will generate an error. Everything is loaded directly from the RouteServiceProvider of Shopper Our BlogSidebar will look like this ```php namespace App\Sidebar; use Maatwebsite\Sidebar\Group; use Maatwebsite\Sidebar\Item; use Maatwebsite\Sidebar\Menu; use Shopper\Framework\Sidebar\AbstractAdminSidebar; class BlogSidebar extends AbstractAdminSidebar { /** * Method used to define your sidebar menu groups and items. * * @param Menu $menu * @return Menu */ public function extendWith(Menu $menu): Menu { $menu->group(__('Blog'), function (Group $group) { $group->weight(22); $group->authorize(true); $group->item(__('Posts'), function (Item $item) { $item->weight(2); $item->authorize(true); $item->route('posts.index'); $item->icon(' '); }); }); return $menu; } } ``` Now we will register our sidebar in our **AppServiceProvider** with the `register()` method ```php namespace App\Providers; use App\Sidebar\BlogSidebar; use Darryldecode\Cart\Cart; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Str; use Shopper\Framework\Events\BuildingSidebar; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { if ($this->app->isLocal()) { $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class); } $this->app['events']->listen(BuildingSidebar::class, BlogSidebar::class); $this->app->singleton('wishlist', function ($app) { $storage = $app['session']; $events = $app['events']; $instanceName = 'cart_2'; return new Cart( $storage, $events, $instanceName, session()->getId(), config('shopping_cart') ); }); } /** * Bootstrap any application services. * * @return void */ public function boot() { Str::macro('readDuration', function (...$text) { $totalWords = str_word_count(implode(' ', $text)); $minutesToRead = round($totalWords / 200); return (int) max(1, $minutesToRead); }); } } ``` We will have this in our sidebar ![Blog sidebar](/images/v1/sidebar-screen.png) ## The Menu & Item Class [#the-menu--item-class] Each item you see in the navigation is an instance of the `Maatwebsite\Sidebar\Item` class. Each top-level `Menu` in a section can contain its own group of `Item` children. ### Basic API [#basic-api] The code examples above demonstrate how to add Navigation. Once you have a `Item` object, the following chainable methods are available to you: | Method | Parameters | Description | | :--- | :--- | :--- | | `group()` | `$name` (string) | Define group name. | | `name()` | `$name` (string) | Define item name to overwrite the `group()` name value. | | `weight()` | `$weight` (int) | Define item order name. | | `route()` | `$name` (string) | Define a route automatically available in `routes/shopper.php` | | `url()` | `$url` (string) | Define a URL instead of a route. A string without a leading slash will be relative from the CP. A leading slash will be relative from the root. You may provide an absolute URL. | | `icon()` | `$icon` (string) | Define icon. | | `authorize()` | `$ability` (boolean) | Define authorization. | # Installation (/1.x/installation) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. ## Supported Versions of Laravel [#supported-versions-of-laravel] **Laravel 8 and Laravel 9 are supported.** It feels like this section needs more than one sentence but it really doesn't. That first one said all that needs saying. ## Install Shopper [#install-shopper] Shopper is really easy to install. After creating your new app or in an existing Laravel app \(8+\). There are 2 steps to follow to install Shopper. 1. Run `php artisan config:clear` to make sure your config isn't cached. 2. Install `shopper/framework` with Composer. ``` bash composer require shopper/framework --with-dependencies ``` ## Write Env Variables [#write-env-variables] Next make sure to create a new database and add your database credentials to your .env file, you will also want to add your application URL in the `APP_URL` variable ```bash APP_URL=http://laravelshopper.test DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret ``` ## Automatic Installation [#automatic-installation] After installing Shopper in your project via compose and configuring the database, now we will automatically install in the project. ```bash php artisan shopper:install ``` This will install shopper, publish vendor files, create shopper and storage symlinks if they don't exist in the public folder, run migrations and seeders classes. And we're all good to go! ## Update Existing Files [#update-existing-files] Extend your current User Model \(usually `app/Models/User.php`\) using the `Shopper\Framework\Models\User\User as Authenticatable` alias: ```php // app/Models/User.php use Shopper\Framework\Models\User\User as Authenticatable; class User extends Authenticatable { // ... } ``` ## Create an Admin user [#create-an-admin-user] Now we can create a new superuser and sign into the Dashboard and start creating some content to display on the frontend. Run the following command to create a user with supreme \(at the moment of creation\) rights: ```bash php artisan shopper:admin ``` And you will be prompted for the user email, firstname, lastname and password. You can now login to start create products ![Product creation screenshot](/images/v1/product-screenshot.png) ## New Shopper Directory [#new-shopper-directory] After Shopper is installed, you'll have 1 new directory in your project: - `config/shopper/` ## Publish Vendor Files [#publish-vendor-files] If you want to publish again Shopper's vendor files run these commands: ```bash php artisan shopper:publish ``` To run the project you may use the built-in server: `php artisan serve` After that, run `composer dump-autoload` to finish your installation! If your are using Laravel Valet you can easily access with your project name with `.test` at the end when you navigate on you project. ```bash http://laravelshopper.test/shopper/login ``` # Legal (/1.x/legal) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. This section allows you to set up your pages for your privacy policy, return policy, terms of use and shipping policy to be presented to customers. ## Fields [#fields] The model used is `Shopper\Core\Models\Legal`. | Name | Type | Required | Notes | |--------------|-----------|------------|------------| | `id` | autoinc | | auto | | `title` | string | yes | Unique, title of the legal page | | `slug` | string | yes | Unique, this is dynamically generated based on the title | | `content`| longText | no | nullable, the text of the legal page | | `is_enabled` | boolean | no | Default `false`, define if this legal page is ready to use| ## Components [#components] The components used to manage Legal page are found in the component configuration file `config/shopper/components.php`. Each component corresponds to the page that is defined ```php use Shopper\Http\Livewire\Components; return [ 'livewire' => [ 'settings.legal.privacy' => Components\Settings\Legal\Privacy::class, 'settings.legal.refund' => Components\Settings\Legal\Refund::class, 'settings.legal.shipping' => Components\Settings\Legal\Shipping::class, 'settings.legal.terms' => Components\Settings\Legal\Terms::class, ]; ]; ``` ## Add Legal content [#add-legal-content] In your administration area you must click on the "cog" icon to display the settings page of your store. - From your admin panel, on the blue sidebar click on the cog icon, go to `Settings > Legal`. ![legal setting](/images/v1/settings-legal.png) Once in this page, all the legal pages are displayed as a tab. You can just fill in the content of each page and click on the Enable switch to retrieve the content of your page and display it in your front-end. ![legal pages](/images/v1/legal-screenshot.png) Shopper does not generate the routes for the legal pages, you should set them up yourself. As mentioned in the introduction of this documentation, the **Framework** is just an e-commerce administration ## Retrieve Data [#retrieve-data] Once the information is filled in, we can display it to our users in the views we have created. To do this we will start by creating a controller that will take care of collecting our information and send it to a view ```bash php artisan make:controller LegalController ``` We will add the functions for each of our pages and return the information to present them to our users. Our controller will look like this ```php namespace App\Http\Controllers; use Shopper\Core\Models\Legal; class LegalController extends Controller { public function privacy() { return view('legal.privacy', [ 'legal' => Legal::enabled()->where('slug', 'privacy-policy')->first(), ]); } public function refund() { return view('legal.refund', [ 'legal' => Legal::enabled()->where('slug', 'refund-policy')->first(), ]); } public function terms() { return view('legal.terms', [ 'legal' => Legal::enabled()->where('slug', 'terms-of-use')->first(), ]); } public function shipping() { return view('legal.shipping', [ 'legal' => Legal::enabled()->where('slug', 'shipping-policy')->first(), ]); } } ``` `Legal::enabled()` is a scope to retrieve the page only when it is available. This is a simple way to retrieve the pages but you can do it otherwise all the front-end code depends on you. To learn more about the scopes you can consult the [documentation](https://laravel.com/docs/10.x/eloquent#local-scopes). ### Routes [#routes] Once we have created the controllers we will associate the routes that will allow us to display our contents. We will display our content in the `web.php`. ```php use App\Http\Controllers\LegalController; /* * Legal routes */ Route::get('/privacy', [LegalController::class, 'privacy'])->name('legal.privacy'); Route::get('/terms-of-use', [LegalController::class, 'terms'])->name('legal.terms'); Route::get('/refund-policy', [LegalController::class, 'refund'])->name('legal.refund'); Route::get('/shipping', [LegalController::class, 'shipping'])->name('legal.shipping'); ``` ### Views [#views] You can create views in this way to arrange the content of your legal pages. ```text resources/views/legal/ privacy.blade.php terms.blade.php refund.blade.php shipping.blade.php ``` It's just an idea of how to make your views, not a recommendation. If your front-end is in react, vue or svelte you will not necessarily have the same architecture. So keep in mind that it's just to display your content. Example of a view ```blade @extends('layouts.app') @section('body')

{{ __('Privacy Policy') }}

{{ __('Last update: :date', ['date' => $legal->created_at->format('d, F Y')]) }}
{!! $legal->content !!}
@endsection ``` # Locations (/1.x/locations) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. By default when you install Shopper for the first time you configure and create your shop, and this allows you to create a first location which will have the information you defined. This is the initial location in which all products will be stored. If you have already used [Shopify](https://shopify.com) it is a bit the same model, but a little simpler so that you can modify it because the system is accessible for any type of business. You can set up multiple locations in your store so that you can track inventory and have excel documents of the products ordered in each of your locations. Your locations can be retail stores, warehouses, popups, or any other place where you manage or store inventory. With multiple locations, you have better visibility into your inventory in your business. ![Locations](/images/v1/location-admin.png) A location is a physical place or space where you perform any or all of the following activities: Selling products, shipping or fulfillment orders, and inventory inventory (this may even be your apartment). ## Setup locations [#setup-locations] From the administration area of your store you can't manage more than 4 inventories. This system being still experimental we are working on it to make it simpler to facilitate the management of your store. ### Fields [#fields] The model used is `Shopper\Core\Models\Inventory`. | Name | Type | Required | Notes | |--------------|-----------|------------|------------| | `id` | autoinc | | auto | | `code` | string | yes | Unique, the code is a unique element that allows to index an inventory in a unique way, a bit like a slug | | `description`| text | no | nullable | | `email` | string | yes | Unique, the location email address | | `street_address` | string | yes | The address details (street, nr, building, etc) | | `street_address_plus` | string | no | The second address details (optional) | | `zipcode` | string | yes | National identification code. (optional) | | `city` | string | yes | The city/settlement | | `phone_number` | string | no | Nullable | | `priority` | integer | default (`0`) | no | | `latitude` | decimal | no | Nullable, GPS latitude coordinates | | `longitude` | decimal | no | Nullable, GPS longitude coordinates | | `is_default` | boolean | no | Default `false`, define location as defaut for stock| | `country_id` | string | yes | foreign key for country, each location must be linked to a country | ### Components [#components] The components used to manage locations are found in the component configuration file `config/shopper/components.php`. ```php use Shopper\Core\Http\Livewire; use Shopper\Core\Http\Livewire\Components; return [ 'livewire' => [ 'modals.delete-inventory' => Livewire\Modals\DeleteInventory::class, 'settings.inventories.browse' => Components\Settings\Inventories\Browse::class, 'settings.inventories.create' => Components\Settings\Inventories\Create::class, 'settings.inventories.edit' => Components\Settings\Inventories\Edit::class, ]; ]; ``` You can expand each of its components to customize this section or replace the entire section if your system requires it. You can also change the views too and return your own views. ## Manage locations [#manage-locations] In your administration area you must click on the "cog" icon to display the settings page of your store. - From your admin panel, on the blue sidebar click on the cog icon, go to `Settings > Locations`. ![Setting location](/images/v1/settings-location.png) ### Add location [#add-location] In your administration area you must click on the "cog" icon to display the settings page of your store. 1. Click Add location. 2. Enter a unique name and an address for the location. ![Add location](/images/v1/add-location.png) ### Edit location [#edit-location] To update a location you click on an available location among those you have saved and you will have the update page. ![update location](/images/v1/update-location.png) ### Define a default location [#define-a-default-location] The default location is the one in which all products will be collected with each order. If this location is empty the products will be searched in another and if it is the only one the product will be out of stock on your store. You select a location and during the modification you click on the checkbox **Set as default inventory** ![Set default location](/images/v1/default-location.png) ### Delete location [#delete-location] To delete a location you must click on a location to display it and at the bottom of the page you click on the delete button. ![Delete location](/images/v1/delete-location.png) Once the location removed, all inventories will changed and this could complicate your inventory management. This is why you have a confirmation modal to be sure that this is indeed what you want to proceed. # Media (/1.x/media) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. The Shopper Framework supports assigning images to products, brands, collections and categories. It is an additional layer provided by the framework with the help of the [Spatie Media Library](https://spatie.be/v1/laravel-medialibrary) We recommend organizing your images in a folder offline and keeping a backup in case you need them in the future or mistakenly alter one and wish to revert to the original. You can look at the [documentation](/1.x/configuration#update-configurations) for this purpose ## Configuration [#configuration] For uploading images we are using [FilePond](https://pqina.nl/) and some custom upload component with Livewire. ### Filepond [#filepond] This component is used to update media at the product level and variants for products. ![filepond](/images/v1/filepond.png) Filepond is used in Shopper Framework only to update images, and for that it takes as parameters the images of your model. ```blade ``` `$images` are a collection of media from the Spatie Media Library. So you have to set up the file upload in your Livewire component yourself. An example of file upload with filepond is available on Livewire you can learn more on this [link](https://www.laravel-livewire.com/screencasts/s5-integrating-with-filepond). ### Single upload [#single-upload] Single Upload is a reusable Livewire component created for single upload management with Livewire ![single upload](/images/v1/single-upload.png) The component used is `Shopper\Http\Livewire\Components\Forms\Uploads\Single` To add it to your page you add this component to your view. ```blade ``` Everything is done out of the box. You just add this to your Livewire component you can add a listener ```php namespace App\Http\Livewire; use Livewire\Component; class MyComponent extends Component { public ?string $fileUrl = null; protected $listeners = [ 'shopper:fileUpdated' => 'onFileUpdate' ]; public function onFileUpdate($file) { $this->fileUrl = $file; } public function store() { $model = YourModel::create([...]); if ($this->fileUrl) { $model->addMedia($this->fileUrl) ->toMediaCollection(config('shopper.core.storage.collection_name')); } } } ``` To apply this action on your model you have to preapre your model with the Laravel Media Library [configuration](https://spatie.be/docs/laravel-medialibrary/v10/basic-usage/preparing-your-model) ### Multiple upload [#multiple-upload] The component used is `Shopper\Http\Livewire\Components\Forms\Uploads\Multiple` To add it to your page you add this component to your view. ```blade ``` ![multiple upload](/images/v1/multiple-upload.png) ```php namespace App\Http\Livewire; use Livewire\Component; class MyComponent extends Component { public $files = []; protected $listeners = [ 'shopper:filesUpdated' => 'onFilesUpdated' ]; public function onFilesUpdate($files) { $this->files = $files; } public function store() { $model = YourModel::create([...]); if (collect($this->files)->isNotEmpty()) { collect($this->files)->each( fn ($file) => $model->addMedia($file)->toMediaCollection(config('shopper.core.storage.collection_name')) ); } } } ``` ## Media Variants [#media-variants] The Spatie Media library supports defining various image sizes, so-called [Conversions](https://spatie.be/docs/laravel-medialibrary/v10/converting-images/defining-conversions). The uploaded images will be then converted to the given sizes with the given parameters. For the moment in Shopper for all the Model that's used Media Library the only conversion available is ```php public function registerMediaConversions(?Media $media = null): void { $this->addMediaConversion('thumb200x200') ->fit(Manipulations::FIT_CROP, 200, 200); } ``` But you can extend the different models to add conversions according to your needs. ## Retrieving Images [#retrieving-images] ### Thumbnails [#thumbnails] The presence of thumbnails is a very common scenario, which is why Shopper use them. ```php $product->getUrl('thumb200x200') ``` For more information on what's available, see [Defining conversions](https://spatie.be/docs/laravel-medialibrary/v10/converting-images/defining-conversions#content-using-multiple-conversions) ### Primary [#primary] To get an image with full url on a product, a brand or a collection ```php $product->getFirstMediaUrl(config('shopper.core.storage.disk_name')) ``` # Orders (/1.x/orders) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. # Products (/1.x/products) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. # Requirements (/1.x/requirements) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. Shopper is a modern PHP application, built as a [Laravel](https://laravel.com) package, and has the same server requirements as — you guessed it — Laravel itself. To manipulate images (resize, crop, etc), you will also need the GD Library or ImageMagick. ## Server Requirements [#server-requirements] To run Shopper you'll need a server meeting the following requirements. These are all pretty standard in most modern hosting platforms. ## PHP Version [#php-version] - PHP 8.0+ ## PHP Extension [#php-extension] - BCMath PHP Extension - Ctype PHP Extension - Exif PHP Extension - JSON PHP Extension - Mbstring PHP Extension - OpenSSL PHP Extension - PDO PHP Extension - Tokenizer PHP Extension - XML PHP Extension - GD Library or ImageMagick ## Database Engine [#database-engine] - MySQL 8.0+ - MariaDB 10.2+ ## Recommended Hosts [#recommended-hosts] We recommend using [Digital Ocean][do] to host most Laravel sites. Their servers are fast, inexpensive, and we use them ourselves. _**Full disclosure:** that's an affiliate link but we wouldn't recommend them if it wasn't an excellent option._ ## Development Environments [#development-environments] All of these requirements are satisfied by the [Laravel Homestead][homestead] virtual machine, which makes it a great local Laravel development environment. Virtual machines aren't for everybody though, so here are a couple of other options. ### Laravel Valet (MacOS) [#laravel-valet-macos] [Laravel Valet][valet] is a development environment for Mac minimalists If you are on Linux you must use this [version][valet_linux] of Valet for Linux. No Vagrant, No Apache, No Nginx, No need to manually edit hosts file. It simply maps all the subdirectories in a “web” directory (such as `~/Sites`) to `.test` or `.localhost` domains. You can even share your sites publicly using local tunnels. We use it ourselves and it’s brilliant. ### Laragon (Windows) [#laragon-windows] [Laragon][laragon] and [WAMP][wamp] are both good choice for those of the Windows persuasion. You may also want to checkout [Laravel Sail](https://laravel.com/docs/8.x/sail), which works well with Statamic. [do]: https://m.do.co/c/d6dca1691fb4 [homestead]: https://laravel.com/v1/homestead [valet]: https://laravel.com/v1/valet [valet_linux]: https://cpriego.github.io/valet-linux [wamp]: http://www.wampserver.com/ [laragon]:https://laragon.org/ # Reviews (/1.x/reviews) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. # Roles & Permissions (/1.x/roles-permissions) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. To connect to the dashboard you need to have the role `administrator` this role can be found in the configuration file `config/shopper/core.php`. ```php /* |-------------------------------------------------------------------------- | Configurations for the user |-------------------------------------------------------------------------- | | User configuration to manage user access using spatie/laravel-permission. | */ 'users' => [ 'admin_role' => 'administrator', 'default_role' => 'user', ], ``` After [creating an super admin](/1.x/installation#create-an-admin-user) we get the following result ```bash php artisan shopper:admin Create Admin User for Shopper administration panel Email Address [admin@admin.com]: > arthur@shopperlabs.io First Name [Shopper]: > Last Name [Admin]: > Password: > Confirm Password: > Creating admin account... User created successfully. ``` After logged as an admin, you can add members with permissions on your staff to log in to your store and complete tasks like **adding products** or managing **orders** and use roles to control what sections of your store they can access. Permissions help you manage what your store’s staff can do in your admin. Roles let you delegate, and assign the level of access that your staff needs to do their jobs effectively. Permissions are associated with roles. Depending on the role that a member has, you can assign different types of permissions to it to limit or increase the actions they can do. All this management of roles and permissions is done using the [Laravel Permission](https://github.com/spatie/laravel-permission) package from [Spatie](https://spatie.be). At installation Shopper comes with 3 roles: **Administrator**, **Manager** and **User**, the user role cannot be modified from the administration interface because it is the role that will be assigned to any customer who will create his account on your shop. ## RBAC ACL [#rbac-acl] RBAC (Role Based Access Control) or ACL (Access Control Layer) is an approach to restricting system access for users using roles system, Shopper allow to define the level of access for each user. With roles a user can access menus, pages. It is important to know that one Administrator can have multiple roles assigned. To view the roles and permissions management page, you must go to the `Settings > Staff & Permissions` ![Setting Staff & permissions](/images/v1/settings-staff.png) ### Fields [#fields] The model used for the **Role** is `Shopper\Core\Models\Role` this model extend from the Spatie Role model. | Name | Type | Required | Notes | |-------------|-----------|----------|------------| | `id` | autoinc | | auto | | `name` | string | yes | Role name in lowercase such as an slug (Eg.: author)| | `guard_name`| string | no | This field is automatically filled in by Spatie | | `display_name`| string | no | Nullable, the readable name for the role (Eg.: Blog Author)| | `description`| text | no | Nullable, the role description | | `can_be_removed` | boolean | no | Default `true`, defines if a role can be deleted. Initially no role that comes with Shopper can be deleted from the interface. But the roles that will be added afterwards can be deleted.| And the **Permission** model is `Shopper\Core\Models\Permission` | Name | Type | Required | Notes | |-------------|-----------|----------|------------| | `id` | autoinc | | auto | | `name` | string | yes | Permission name in lowercase such as an slug (Eg.: create_post)| | `guard_name`| string | no | This field is automatically filled in by Spatie | | `group_name`| string | no | Permissions can be grouped into groups to better organize them. The basic permissions that come with Shopper are mostly grouped together. | | `display_name`| string | no | Nullable, the readable name for the permission (Eg.: Create Post)| | `description`| text | no | Nullable, the permission description | | `can_be_removed` | boolean | no | Default `true`, defines if a permission can be deleted. Initially no permission that comes with Shopper can be deleted from the interface. But the permissions that will be added afterwards can be deleted.| The **Permission** model has some groups as shown here ```php namespace Shopper\Framework\Models\User; use Spatie\Permission\Models\Permission as SpatiePermission; class Permission extends SpatiePermission { /** * Get a lists of permissions groups. */ public static function groups(): array { return [ 'system' => __('System'), 'brands' => __('Brands'), 'categories' => __('Categories'), 'collections' => __('Collections'), 'products' => __('Products'), 'customers' => __('Customers'), 'orders' => __('Orders'), 'discounts' => __('Discounts'), ]; } } ``` ### Components [#components] The components used to manage locations are found in the component configuration file `config/shopper/components.php`. ```php use Shopper\Framework\Http\Livewire; use Shopper\Framework\Http\Livewire\Components; return [ 'livewire' => [ 'modals.delete-role' => Livewire\Modals\DeleteRole::class, 'modals.create-permission' => Livewire\Modals\CreatePermission::class, 'modals.create-role' => Livewire\Modals\CreateRole::class, 'settings.management.create-admin-user' => Components\Settings\Management\CreateAdminUser::class, 'settings.management.management' => Components\Settings\Management\Management::class, 'settings.management.permissions' => Components\Settings\Management\Permissions::class, 'settings.management.role' => Components\Settings\Management\Role::class, 'settings.management.users-role' => Components\Settings\Management\UsersRole::class, ]; ]; ``` ## Manage Roles [#manage-roles] A Role is a set of permissions to perform certain operations within the system, which is assigned to a chosen Administrator. As said previously Shopper at installation comes with 3 roles but 2 are accessible in the administration panel. The user role does not appear, modifying it could lead to bugs on your store so it is not listed here. ![roles and admins users](/images/v1/roles-admins.png) It's **strongly** advised to not change the name of roles when they are already assigned to users. If the role verification is done manually you will be forced to change this name in all **middleware**, **helpers**, **blade directives** etc. ### Add role [#add-role] To add a new role, you must click on `Add a new role` button. Required fields are marked with asterisks ![addd new role](/images/v1/add-role.png) The added roles can be used later in your code to assign functionality or access to resources. ### Update role [#update-role] To modify a role you must click on the role you want to modify to access the edit form. And as already mentioned, all Shopper features are livewire components. So you can change everything at any time to fit your store. ![update role](/images/v1/update-role.png) ### Create admin [#create-admin] In addition to creating an administrator from the command line you can also do it from the Shopper interface, you just need to click on **Add Administrator** button. ![add new admin](/images/v1/add-admin.png) Then you fill in the information of your administrator with the role chosen for him ![add new admin form](/images/v1/admin-user-form.png) The actual role registration function looks like the code below. And the whole implementation class is `Shopper\Http\Livewire\Components\Settings\Management\CreateAdminUser` ```php public function store() { $this->validate($this->rules(), $this->messages()); $user = (new UserRepository())->create([ 'email' => $this->email, 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'password' => Hash::make($this->password), 'phone_number' => $this->phone_number, 'gender' => $this->gender, 'email_verified_at' => now()->toDateTimeString(), ]); $role = Role::findById((int) $this->role_id); $user->assignRole([$role->name]); if ($this->send_mail) { $user->notify(new AdminSendCredentials($this->password)); } session()->flash('success', __('Admin :user added successfully.', ['user' => $user->full_name])); $this->redirectRoute('shopper.settings.users'); } ``` ### Create permission [#create-permission] Let’s assume that you would like to add a new permission to ACL. You will need to choose the role because every single permissions are linked to a role. In the way that when a admin are granted of a specific role, he take all role's permissions. ![Role's permissions example](/images/v1/permissions-browse.png) As you may have noticed all permissions are grouped by type, and the available types are mentioned above in this [section](/1.x/roles-permissions#fields). To add a new permission you just need to click on the **Create permission** button. ![Add permission](/images/v1/add-permission.png) After adding your permission it will be automatically associated with the role and therefore all administrators with this role will have this permission. If the permission has no group it will be in a `Custom permissions` section. ![new permission](/images/v1/custom-permissions.png) # Two Factor Authenticator (/1.x/two-factor) This is documentation for Shopper v1, which is no longer maintained. Please refer to the [v2 docs](/2.x/user-guide/getting-started/introduction) for the latest information. Two-step authentication (also known as two-factor authentication or multifactor authentication) provides a more secure login process. When you attempt to sign in, you need to complete two separate steps: 1. Enter the account password. 2. Authenticate through a mobile app security key. These two steps will make much more difficult for an unauthorized person to access your account. Even if they are able to find your password, they will not be able to connect without the second step. Authentication in two secure steps rests on the combination of two factors, which can be something you know (such as your combination of connection and password), something you have (such as a code to Only one use provided by an authentication application or SMS) or something you are (providing biometric authentication, such as a fingerprint). Two-step authentication can be configured for all accounts, but the store owner can not activate it for staff. The staff must put it in place for his own accounts. If you have multiple employees who manage your shop. ## Enabling Two-Factor Authentication [#enabling-two-factor-authentication] To enable two-step authentication, you'll need first to download an authenticator app to your mobile device. The app will be able to scan QR codes and retrieve authentication data for you. Recommended authenticator apps: - [Google Authenticator](https://support.google.com/accounts/answer/1066447) - [Duo Mobile](https://guide.duo.com/third-party-accounts) - [Amazon AWS MFA](https://aws.amazon.com/iam/details/mfa) - [Authenticator](https://www.microsoft.com/store/p/microsoft-authenticator/9nblgggzmcj6) In addition, you should store the listed recovery codes in a secure password manager such as [1Password](https://1password.com). When you install an authenticator app, make sure that you follow its instructions carefully. After your app is successfully downloaded and set up, you can activate the feature in Shopper. From your administrator interface, click on your name with account picture in the upper right corner. Next click on **Personal Account** ![Account dropdown](/images/v1/account-dropdown.png) Scroll to the two factor authenticate section on the screen, click **Enable authentication**. This action will trigger a modal to ask you to confirm your password ![Two factor section Screenshot](/images/v1/two-factor-section.png) Enter your current password in the space provided and click **Enable**. If the user loses access to their mobile device, the login page will allow them to authenticate using one of their recovery codes instead of the temporary token provided by their mobile device's authenticator application. ![Two factor code Screenshot](/images/v1/two-factor-code.png) This feature is inspired by [Laravel Fortify](https://laravel.com/docs/9.x/fortify) which is implemented in [Laravel Jetstream](https://jetstream.laravel.com/2.x/introduction.html) Now when you try to log in, two-factor authentication will require your mobile device. ## Logging in with Two-Factor Authentication [#logging-in-with-two-factor-authentication] You will go to the Shopper administration login page. You will enter your email address and password and click on the **Login** button. On the next page, you need to authenticate using the method you've used to set up two-factor authentication. ![Two factor login Screenshot](/images/v1/auth-two-factor-authentication.png) If you used a two-factor authentication app, open it and retrieve the code you will be given and click on the login button If you have rather copied the recovery codes in an application like 1Password you will have to recover a code, enter it to connect to your store. ## Disable Two-Factor Authentication [#disable-two-factor-authentication] From your administrator interface, click on your name and your account photo in the upper right corner and click on Personnal Account menu. In the Two-factor authentication section, use the Disable button for the authentication method you want to deactivate. This will ask you for a password confirmation, you enter your password and click on confirm to completely deactivate the Two-factor authentication. ![Two factor disable Screenshot](/images/v1/two-factor-disable.png) # Add-ons (/2.x/addons) Addons are the recommended way to package Shopper extensions. An addon is a self-contained unit that registers its routes, Livewire components, sidebar entries, views, and settings items through the `ShopperPanel`. When an addon is disabled, none of its assets are registered. ## Creating an Addon [#creating-an-addon] An addon is a class that implements `Shopper\Contracts\ShopperAddon`. Extend `Shopper\Addon\BaseAddon`: it implements the contract and provides `getName()`, `boot()` and `isEnabled()`, so you only write `getId()` and `register()`. The contract has five methods: | Method | Return | Description | |--------|--------|-------------| | `getId()` | `string` | Unique kebab-case identifier (`my-addon`), also the addon's key in `config/shopper/addons.php` | | `getName()` | `string` | Display name; `BaseAddon` derives it from `getId()` automatically (`loyalty-points` becomes `Loyalty Points`) | | `register(ShopperPanel $panel)` | `void` | Called by `Shopper::addon()` when the addon is enabled, bind routes, components, views, settings | | `boot(ShopperPanel $panel)` | `void` | Called when Shopper boots, after all addons are registered, use for cross-addon dependencies; empty in `BaseAddon` | | `isEnabled()` | `bool` | `BaseAddon` reads `config('shopper.addons.')`, defaulting to `true` | A minimal addon looks like this: ```php namespace App\Addons; use Shopper\Addon\BaseAddon; use Shopper\ShopperPanel; final class AnalyticsAddon extends BaseAddon { public function getId(): string { return 'analytics'; } public function register(ShopperPanel $panel): void { $panel->addonRoutes(fn () => require __DIR__.'/../routes/analytics.php'); $panel->addonLivewireComponents([ 'analytics-dashboard' => \App\Livewire\Analytics\Dashboard::class, 'analytics-report' => \App\Livewire\Analytics\Report::class, ]); $panel->addonViews('analytics', __DIR__.'/../resources/views'); } } ``` ## Registering an Addon [#registering-an-addon] Register the addon in the `register()` method of your application's service provider using the `Shopper` facade: ```php use App\Addons\AnalyticsAddon; use Shopper\Facades\Shopper; public function register(): void { Shopper::addon(new AnalyticsAddon); } ``` Shopper loads the routes, sidebar classes, Livewire components, views and settings items of its addons, then calls their `boot()` method, when its own service provider boots. Laravel boots package service providers before your application's providers, so an addon registered in `AppServiceProvider::boot()` comes too late: its routes, sidebar entries, components, views and settings items are skipped without any error. Calling `Shopper::addon()` in `register()` avoids this. The `AddonManager` checks `isEnabled()` before registering. If the addon is disabled via config, `register()` is never called and nothing is loaded. Registering two enabled addons with the same ID throws a `LogicException`. ## What an Addon Can Register [#what-an-addon-can-register] ### Routes [#routes] Shopper loads addon routes inside its admin route group, so do not add a prefix, a name prefix or middleware yourself. Each route gets the admin panel prefix (`shopper.admin.prefix`, `cpanel` by default) and domain, the `shopper.` name prefix, and the middleware of the admin pages, including the ones listed in `shopper.routes.middleware` (see [Middleware](/2.x/configuration#middleware)). The routes below answer at `/cpanel/analytics` and `/cpanel/analytics/{report}`, and their names are `shopper.analytics.index` and `shopper.analytics.report`: ```php use Illuminate\Support\Facades\Route; $panel->addonRoutes(function () { Route::get('/analytics', AnalyticsDashboard::class)->name('analytics.index'); Route::get('/analytics/{report}', AnalyticsReport::class)->name('analytics.report'); }); ``` Call `addonRoutes()` in `register()`: Shopper loads its routes before it calls the addons' `boot()` method, so routes declared in `boot()` are never loaded. To render a Livewire page inside the admin layout, give the component Shopper's layout, as shown in [Using Livewire Components](/2.x/extending/controllers#using-livewire-components). ### Livewire Components [#livewire-components] Shopper registers each alias with a `shopper-` prefix, like its own components. The component below is rendered with ``: ```php $panel->addonLivewireComponents([ 'analytics-dashboard' => \App\Livewire\Analytics\Dashboard::class, ]); ``` ### Sidebar Navigation [#sidebar-navigation] Pass a class that extends `Shopper\Sidebar\AbstractAdminSidebar` and adds its menu groups in `extendWith()`. Shopper registers it as a listener of the `Shopper\Sidebar\SidebarBuilder` event, as described in the [sidebar extension guide](/2.x/sidebar/shopper-extension). Link its items to the full route names, such as `shopper.analytics.index`: ```php $panel->addonSidebar(\App\Sidebar\AnalyticsSidebar::class); ``` ### Blade Views [#blade-views] Register a view namespace so your Blade views are accessible as `analytics::dashboard`: ```php $panel->addonViews('analytics', __DIR__.'/../resources/views'); ``` ### Settings Items [#settings-items] Add cards to the Settings page. Each key is a class that extends `Shopper\Settings\Setting` (see [Creating a Custom Setting](/2.x/configuration#creating-a-custom-setting)), mapped to a boolean controlling its visibility: ```php $panel->addonSettingItems([ \App\Settings\AnalyticsSetting::class => true, ]); ``` ### Permissions [#permissions] Declare the permissions your addon introduces: ```php $panel->addonPermissions([ 'browse_analytics', 'export_analytics', ]); ``` In 2.x, Shopper only keeps this list, which `Shopper::addonManager()->getPermissions()` returns. It does not create the permissions or give them to any role, so create them yourself, for example in a migration, as shown in [Creating Custom Permissions](/2.x/acl#creating-custom-permissions). ### Styles and Scripts [#styles-and-scripts] Inject additional CSS or JS assets into the admin panel's layout: ```php $panel->addonStyles([asset('css/analytics.css')]); $panel->addonScripts([asset('js/analytics.js')]); ``` A URL that starts with `http://` or `https://` is used as is. Any other path goes through `asset()`, so `'css/analytics.css'` works too. ## Disabling an Addon [#disabling-an-addon] Set the addon's ID to `false` in `config/shopper/addons.php` (published by `php artisan shopper:install`): ```php return [ 'analytics' => false, ]; ``` When set to `false`, `BaseAddon::isEnabled()` returns `false` and the addon's `register()` method is never called. Routes, components, sidebar entries, and assets are not loaded. ## Checking if an Addon is Active [#checking-if-an-addon-is-active] ```php use Shopper\Facades\Shopper; Shopper::hasAddon('analytics'); $addon = Shopper::getAddon('analytics'); $addon->getName(); ``` `hasAddon()` returns `false` for an addon that is disabled or was never registered, and `getAddon()` throws a `LogicException` for it. `Shopper::addonManager()->all()` returns the active addons as a collection keyed by ID. ## Full Example: A Loyalty Points Addon [#full-example-a-loyalty-points-addon] Here is a complete addon that adds a loyalty points feature to the Shopper admin: ```php namespace App\Addons; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Route; use Shopper\Addon\BaseAddon; use Shopper\ShopperPanel; use Shopper\View\CustomerRenderHook; final class LoyaltyAddon extends BaseAddon { public function getId(): string { return 'loyalty'; } public function register(ShopperPanel $panel): void { $panel->addonRoutes(function () { Route::prefix('loyalty')->name('loyalty.')->group(function () { Route::get('/', \App\Livewire\Loyalty\Index::class)->name('index'); Route::get('/tiers', \App\Livewire\Loyalty\Tiers::class)->name('tiers'); }); }); $panel->addonLivewireComponents([ 'loyalty-index' => \App\Livewire\Loyalty\Index::class, 'loyalty-tiers' => \App\Livewire\Loyalty\Tiers::class, 'loyalty-customer-points' => \App\Livewire\Loyalty\CustomerPoints::class, ]); $panel->addonViews('loyalty', __DIR__.'/../resources/views'); $panel->addonSidebar(\App\Sidebar\LoyaltySidebar::class); $panel->addonPermissions([ 'browse_loyalty', 'edit_loyalty', ]); $panel->addonSettingItems([ \App\Settings\LoyaltySetting::class => true, ]); } public function boot(ShopperPanel $panel): void { $panel->renderHook( CustomerRenderHook::SHOW_TABS_END, fn (): string => Blade::render(''), ); } } ``` The routes answer at `/cpanel/loyalty` and `/cpanel/loyalty/tiers` and are named `shopper.loyalty.index` and `shopper.loyalty.tiers`. A render hook returns HTML, so the Livewire tag goes through `Blade::render()`. Register it once in the `register()` method of your service provider: ```php use Shopper\Facades\Shopper; Shopper::addon(new LoyaltyAddon); ``` # Roles & Permissions (/2.x/acl) Shopper uses [spatie/laravel-permission](https://github.com/spatie/laravel-permission) to manage roles and permissions. Every admin user has one or more roles, and each role has a set of permissions that control access to admin panel sections and actions. Since all permissions are registered on Laravel's gate, you can use Laravel's built-in `can()` function and `@can` Blade directive. For a visual walkthrough of managing roles and permissions in the admin panel, see the User Guide pages: [Managing Staff](/2.x/user-guide/administration/users) and [Roles & Permissions](/2.x/user-guide/administration/roles). ## Configuration [#configuration] Roles are configured in `config/shopper/admin.php`. These names are used throughout the system for authorization checks: ```php 'roles' => [ 'admin' => 'administrator', 'manager' => 'manager', 'user' => 'user', ], ``` | Role | Purpose | Admin Access | |------|---------|-------------| | `administrator` | Full access to all admin panel features | Yes | | `manager` | Access limited to the permissions you give the role (none by default) | Yes | | `user` | Customer role. Shopper gives it to customers created in the admin panel; give it to customers who register on your storefront too, because the customers list only shows users with this role | No | A user with any other role can open the admin panel only if they hold the `access_dashboard` permission (see [System Permissions](/2.x/acl#system-permissions)). Do not rename roles after they have been assigned to users. Role names are used in middleware and authorization checks throughout the system. ## Models [#models] ### Role [#role] The model used is `Shopper\Models\Role`, which extends Spatie's Role model with additional fields. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Unique role name used in authorization checks (e.g., `administrator`) | | `guard_name` | string | no | auto | Filled automatically by Spatie | | `display_name` | string | yes | null | Human-readable name | | `description` | text | yes | null | Role description | | `can_be_removed` | boolean | no | true | Whether the role can be deleted | The Role model provides an `isAdmin()` method, which returns `true` when the role name matches `shopper.admin.roles.admin`: ```php use Shopper\Models\Role; $role = Role::query()->where('name', config('shopper.admin.roles.admin'))->first(); $role->isAdmin(); // true ``` ### Permission [#permission] The model used is `Shopper\Models\Permission`, which extends Spatie's Permission model with grouping support. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Permission name (e.g., `browse_products`) | | `guard_name` | string | no | auto | Filled automatically by Spatie | | `group_name` | string | yes | null | Permission group for organization | | `display_name` | string | yes | null | Human-readable name | | `description` | string | yes | null | Permission description | | `can_be_removed` | boolean | no | true | Whether the permission can be deleted | ### Permission Groups [#permission-groups] Each permission belongs to a group through its `group_name` column, and the role page in the admin panel lists permissions by group. `Permission::groups()` returns the built-in groups, used as the options of the group select when you create or generate a permission in the admin panel: ```php use Shopper\Models\Permission; Permission::groups(); ``` This returns an array keyed by group name, with a translated label for each: `system`, `brands`, `categories`, `collections`, `products`, `customers`, `orders`, `discounts`. ### System Permissions [#system-permissions] The `system` group contains the global capabilities that gate everything outside the resource permissions: | Permission | Description | |---|---| | `access_dashboard` | Opens the admin panel for a user who has neither the administrator nor the manager role (checked by `canAccessDashboard()`) | | `access_setting` | Required to open the settings pages (General, Payment methods, Currencies, Carriers, Zones, Taxes, Legal) and for every write action on the Team, Roles and Permissions pages | | `view_users` | Required to view the team pages: the staff list, and a role page with its permissions and members | Locations are not covered by `access_setting`: their pages check the inventory permissions (`browse_inventories`, `add_inventories`, `edit_inventories`, `delete_inventories`). The customers pages check the customer permissions (`browse_customers`, `read_customers`, and so on). Since v2.8, `access_setting` is the only permission that grants write access to PaymentMethods, Currencies, Carriers, Team management, and Role/Permission management. Roles that previously relied on `view_users` to mutate these surfaces must be granted `access_setting` to keep working. ### Team Management Safeguards [#team-management-safeguards] Holding `access_setting` grants write access to the team settings surfaces, but since v2.11.2 it no longer grants unrestricted control over the access control system itself, so you can give it to a staff member who configures shipping or taxes without handing them control of roles and permissions. Non administrator users are subject to three rules: | Rule | Effect | |------|--------| | The administrator role cannot be targeted | A non administrator cannot open, update, delete the administrator role, or assign it to a new team member | | A permission can only be granted if the acting user holds it | A staff member cannot give a role a capability they do not have themselves | | Permission definitions are administrator only | Creating, generating or deleting a permission requires the administrator role | Administrators are unaffected: each rule is skipped when the acting user has the administrator role. Removing a team member is also limited to administrators, and an administrator account cannot be removed from the panel. Permissions and roles flagged with `can_be_removed` set to `false` are also protected on the server, not only hidden in the UI. ### Generating Permissions [#generating-permissions] The `Permission::generate()` method creates five permissions for a given resource (browse, read, edit, add, delete): ```php Permission::generate('brands'); // Creates: browse_brands, read_brands, add_brands, edit_brands, delete_brands Permission::generate('tags', 'products'); // Creates: browse_tags, read_tags, add_tags, edit_tags, delete_tags (in the "products" group) ``` Without a second argument, the group is the resource name. Generated permissions have `can_be_removed` set to `false`, and the method gives them to no role: assign them yourself (see [Creating Custom Permissions](/2.x/acl#creating-custom-permissions)). The **Generate permissions** action on a role page in the admin panel calls the same method and gives the five permissions to that role. ## Working with Roles [#working-with-roles] ### Creating Roles [#creating-roles] To create a new role programmatically: ```php use Shopper\Models\Role; $role = Role::query()->create([ 'name' => 'warehouse-manager', 'display_name' => 'Warehouse Manager', 'description' => 'Manages inventory locations and stock levels.', ]); $role->givePermissionTo([ 'access_dashboard', 'browse_inventories', 'read_inventories', 'edit_inventories', 'browse_products', 'read_products', ]); ``` The `access_dashboard` permission lets users with this role open the admin panel. Without it, only the administrator and manager roles get in. ### Assigning Roles [#assigning-roles] Assign a role to a user: ```php $user->assignRole('warehouse-manager'); $user->assignRole(config('shopper.admin.roles.admin')); ``` ### Checking Roles [#checking-roles] The `InteractsWithShopper` trait on the User model provides role checking methods: ```php $user->isAdmin(); // true if user has the administrator role $user->isManager(); // true if user has the manager role $user->canAccessDashboard(); // true for administrators, managers and users holding access_dashboard $user->hasRole('warehouse-manager'); ``` The trait also adds two query scopes: ```php use App\Models\User; User::query()->administrators()->get(); // users with the administrator or manager role User::query()->customers()->get(); // users with the user role ``` ## Working with Permissions [#working-with-permissions] ### Checking Permissions [#checking-permissions] Use Laravel's standard authorization: ```php $user->hasPermissionTo('browse_products'); $user->can('edit_products'); ``` In Blade templates: ```blade @can('browse_products') Products @endcan ``` In Livewire components, Shopper uses the `authorize()` method: ```php public function mount(): void { $this->authorize('browse_products'); } ``` ### Creating Custom Permissions [#creating-custom-permissions] To add a custom permission and assign it to the administrator and manager roles: ```php use Shopper\Models\Permission; use Shopper\Models\Role; $permission = Permission::query()->create([ 'name' => 'view_analytics', 'group_name' => 'system', 'display_name' => 'View Analytics', 'description' => 'Access the analytics dashboard.', ]); $roles = Role::query() ->whereIn('name', [ config('shopper.admin.roles.admin'), config('shopper.admin.roles.manager'), ]) ->get(); foreach ($roles as $role) { $role->givePermissionTo($permission); } ``` Administrators get no automatic pass on permission checks. The installer gave the administrator role every permission that existed at that time, nothing more, so give each permission you create later to the administrator role too, or `can()` returns `false` for administrators. On the role page in the admin panel, a permission without a `group_name` is listed under a "Custom permission" heading. A permission whose `group_name` is not one of the built-in groups is listed under a heading named after its `group_name`. ### Revoking Permissions [#revoking-permissions] To remove a permission from a role: ```php $role->revokePermissionTo('delete_products'); ``` ## Admin User Creation [#admin-user-creation] You can create an admin user from the command line: ```bash php artisan shopper:user ``` The command asks for the email, first name, last name and password (at least 6 characters), then gives the new user the administrator role. Or programmatically. `forceCreate()` saves the attributes even when they are not in your User model's `$fillable`, as the command does: ```php use App\Models\User; use Illuminate\Support\Facades\Hash; $admin = User::query()->forceCreate([ 'first_name' => 'John', 'last_name' => 'Doe', 'email' => 'admin@example.com', 'password' => Hash::make('password'), 'email_verified_at' => now(), ]); $admin->assignRole(config('shopper.admin.roles.admin')); ``` ## Components [#components] To customize the roles and permissions admin UI: ```bash php artisan shopper:component:publish setting ``` The relevant components in `config/shopper/components/setting.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'team-index' => Livewire\Pages\Settings\Team\Index::class, 'team-roles' => Livewire\Pages\Settings\Team\RolePermission::class, ], 'components' => [ 'settings.team.permissions' => Livewire\Components\Settings\Team\Permissions::class, 'settings.team.users' => Livewire\Components\Settings\Team\UsersRole::class, 'slide-overs.create-team-member' => Livewire\SlideOvers\CreateTeamMember::class, ], ]; ``` # Stripe (/2.x/addons/stripe) The `shopper/stripe` package is a first-party Stripe driver for Shopper's [payment system](/2.x/payments). It uses Stripe PaymentIntents to handle card payments with full support for 3D Secure authentication, manual and automatic capture, partial refunds, and webhook processing. ## Installation [#installation] ```bash composer require shopper/stripe ``` The service provider is auto-discovered. It registers the `stripe` driver with the payment manager and merges the default configuration. ## Configuration [#configuration] Publish the config file: ```bash php artisan vendor:publish --tag=shopper-stripe-config ``` This creates `config/shopper/stripe.php`: ```php return [ 'secret_key' => env('STRIPE_SECRET_KEY'), 'publishable_key' => env('STRIPE_PUBLISHABLE_KEY'), 'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'), 'capture_method' => env('STRIPE_CAPTURE_METHOD', 'manual'), ]; ``` Add your credentials to `.env`: ```bash STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_CAPTURE_METHOD=manual ``` Never commit your Stripe keys to version control. Always use environment variables. ## Capture Method [#capture-method] The `capture_method` setting controls when funds are collected from the customer. | Value | Behavior | Use case | |-------|----------|----------| | `manual` | Authorize first, capture later from the admin panel | Physical goods, verify stock before charging | | `automatic` | Capture immediately when the customer confirms | Digital products, subscriptions, instant fulfillment | Manual capture is the default. When using manual capture, the payment status goes from `Pending` to `Authorized`, then to `Paid`. The merchant captures from the order detail page when ready. Authorization holds typically expire after **7 days** (varies by card network). You must capture within that window or the hold is released and the customer is not charged. ## Payment Method Setup [#payment-method-setup] Create a payment method record linked to the Stripe driver. This makes it selectable at checkout. ```php use Shopper\Core\Models\PaymentMethod; PaymentMethod::query()->create([ 'title' => 'Credit Card', 'slug' => 'credit-card', 'driver' => 'stripe', 'description' => 'Pay securely with your credit or debit card.', 'is_enabled' => true, ]); ``` Assign it to the zones where Stripe should be available: ```php $paymentMethod->zones()->attach([$europeZoneId, $northAmericaZoneId]); ``` ## Payment Flow [#payment-flow] The Stripe driver uses the PaymentIntent API. Here's the complete flow for a checkout with manual capture: ### 1. Initiate at Checkout [#1-initiate-at-checkout] When the customer places an order, initiate the payment. The driver creates a Stripe PaymentIntent and returns a `clientSecret` for the frontend. ```php use Shopper\Payment\Services\PaymentProcessingService; $service = resolve(PaymentProcessingService::class); $result = $service->initiate($order); if ($result->clientSecret) { session()->put('stripe_payment', [ 'client_secret' => $result->clientSecret, 'publishable_key' => $result->data['publishable_key'], ]); return redirect()->route('stripe-payment', $order->number); } ``` ### 2. Confirm on the Frontend [#2-confirm-on-the-frontend] On your payment page, use Stripe.js with the Payment Element to collect card details and confirm the payment: ```html
``` After the customer confirms, Stripe handles 3D Secure if required, then redirects to your `return_url`. ### 3. Handle the Callback [#3-handle-the-callback] On the callback page, verify the payment status: ```php use Shopper\Payment\Services\PaymentProcessingService; $service = resolve(PaymentProcessingService::class); $reference = $service->getLatestReference($order); $result = $service->authorize($order, $reference); if ($result->success) { return redirect()->route('order-confirmed', $order->number); } ``` With manual capture, the order's `payment_status` is now `Authorized`. With automatic capture, it goes straight to `Paid`. ### 4. Capture from the Admin Panel [#4-capture-from-the-admin-panel] When the order is ready to ship, the merchant clicks **Capture payment** on the order detail page. This calls `capturePayment()` on the Stripe driver and collects the funds. The payment status changes from `Authorized` to `Paid`. ## Webhooks [#webhooks] Stripe sends webhook events for asynchronous payment updates. The driver handles these events and converts them into standardized actions. ### Setting Up [#setting-up] 1. In your [Stripe Dashboard](https://dashboard.stripe.com/webhooks), create a webhook endpoint pointing to your application (e.g. `https://yourstore.com/webhooks/stripe`) 2. Copy the signing secret to your `.env`: ```bash STRIPE_WEBHOOK_SECRET=whsec_... ``` 3. Create a webhook controller: ```php namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Shopper\Payment\Facades\Payment; class StripeWebhookController extends Controller { public function __invoke(Request $request): JsonResponse { $driver = Payment::driver('stripe'); $result = $driver->handleWebhook( payload: [ 'raw_body' => $request->getContent(), ], headers: [ 'stripe_signature' => $request->header('Stripe-Signature'), ], ); if ($result->isIgnored()) { return response()->json(['status' => 'ignored']); } // Process the result based on the action // e.g., update order status, send notifications return response()->json(['status' => 'ok']); } } ``` 4. Register the route (excluded from CSRF verification): ```php Route::post('/webhooks/stripe', StripeWebhookController::class); ``` ### Handled Events [#handled-events] | Stripe Event | Action | Description | |-------------|--------|-------------| | `payment_intent.amount_capturable_updated` | `authorized` | Payment authorized, ready to capture | | `payment_intent.succeeded` | `captured` | Payment captured successfully | | `payment_intent.payment_failed` | `failed` | Payment attempt failed | | `payment_intent.canceled` | `canceled` | Payment intent cancelled | | `charge.refunded` | `refunded` | Charge was refunded | All other events are returned as `ignored`. ### Signature Verification [#signature-verification] The driver verifies every webhook using the signing secret. If the signature is invalid, a `StripeException` is thrown. This prevents forged webhook payloads from being processed. ## Refunds [#refunds] The driver supports full and partial refunds through the `PaymentProcessingService`: ```php $service = resolve(PaymentProcessingService::class); $reference = $service->getLatestReference($order); $result = $service->refund($order, $reference, $order->price_amount); ``` For a partial refund, pass a specific amount in cents: ```php $result = $service->refund( order: $order, reference: $reference, amount: 2000, reason: 'Product damaged', ); ``` The order's `payment_status` automatically updates to `PartiallyRefunded` or `Refunded` based on the total refunded amount compared to the order total. ## Cancellation [#cancellation] Cancel an authorized payment before capture to release the hold without processing a refund: ```php $result = $service->cancel($order, $reference); ``` The order's `payment_status` changes to `Voided`. No funds are collected and no refund fees apply. ## Testing [#testing] ### Stripe Test Cards [#stripe-test-cards] Use Stripe's [test card numbers](https://docs.stripe.com/testing#cards) in test mode: | Card Number | Scenario | |-------------|----------| | `4242 4242 4242 4242` | Successful payment | | `4000 0025 0000 3155` | Requires 3D Secure authentication | | `4000 0000 0000 9995` | Declined (insufficient funds) | | `4000 0000 0000 0002` | Declined (generic) | ### Webhook Testing [#webhook-testing] Use the Stripe CLI to forward events to your local environment: ```bash stripe listen --forward-to localhost:8000/webhooks/stripe ``` The CLI prints a webhook signing secret. Use it as `STRIPE_WEBHOOK_SECRET` during development. ### Test Mode [#test-mode] Make sure your `.env` uses `sk_test_` and `pk_test_` keys. Stripe automatically isolates test data from live data. # Attributes (/2.x/attributes) Attributes define product characteristics like Color, Size, or Material. They enable variable products, enhance filtering, and provide detailed product specifications. ## Models [#models] Shopper uses three models to manage attributes: | Model | Purpose | |-------|---------| | `Shopper\Core\Models\Attribute` | The attribute definition (Color, Size, Material) | | `Shopper\Core\Models\AttributeValue` | Possible values for an attribute (Red, Blue, Large) | | `Shopper\Core\Models\AttributeProduct` | Pivot linking attributes to products with a selected value or a custom value | The Attribute model implements `Shopper\Core\Models\Contracts\Attribute` and uses the `HasSlug` trait, which turns the slug you set into a unique slug. Unlike products or brands, the Attribute model is not configurable via `config/shopper/models.php` and has no admin model wrapper. ## Database Schema [#database-schema] Table names start with the prefix set in `config('shopper.core.table_prefix')` (`sh_` by default), for example `sh_attributes`. ### Attribute Table [#attribute-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Attribute name | | `slug` | string | yes | null | URL-friendly identifier (unique), not generated from `name` | | `description` | string | yes | null | Attribute description | | `type` | string | no | - | Field type enum value | | `icon` | string | yes | null | Icon identifier | | `is_enabled` | boolean | no | false | Only enabled attributes can be added to a product in the admin | | `is_searchable` | boolean | no | false | Flag for your storefront search (Shopper does not read it) | | `is_filterable` | boolean | no | false | Flag for your storefront filters (Shopper does not read it) | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### AttributeValue Table [#attributevalue-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `value` | string(50) | no | - | Display value | | `key` | string | no | - | Identifier, unique per attribute (the hex code for a ColorPicker attribute) | | `position` | unsigned smallint | yes | 1 | Display order | | `attribute_id` | bigint | no | - | Foreign key to attribute | ### AttributeProduct Table (Pivot) [#attributeproduct-table-pivot] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `attribute_id` | bigint | no | Foreign key to attribute | | `product_id` | bigint | no | Foreign key to product | | `attribute_value_id` | bigint | yes | Foreign key to attribute value | | `attribute_custom_value` | longtext | yes | Custom value for text-based attributes | ## Field Types [#field-types] Attributes use the `FieldType` enum to determine input behavior: ```php use Shopper\Core\Enum\FieldType; FieldType::Checkbox; // Multiple selectable values FieldType::ColorPicker; // Multiple selectable colors FieldType::DatePicker; // Date input FieldType::RichText; // Rich text editor FieldType::Select; // Single selection dropdown FieldType::Text; // Single-line text input FieldType::Number; // Numeric value ``` | Type | Database Value | Has Predefined Values | Description | |------|---------------|----------------------|-------------| | Checkbox | `checkbox` | Yes | Multiple values can be selected | | ColorPicker | `colorpicker` | Yes | Multiple color values, each with a hex code | | DatePicker | `datepicker` | No | Date input field | | RichText | `richtext` | No | HTML content editor | | Select | `select` | Yes | Single value selection | | Text | `text` | No | Free text input | | Number | `number` | No | Numeric value, entered in a text input | Types without predefined values store the product's value as text in `attribute_custom_value`: HTML for RichText, a `Y-m-d` date for DatePicker. ### Type Checking Methods [#type-checking-methods] Each attribute type has helper methods to determine its behavior: ```php $attribute->hasMultipleValues(); $attribute->hasSingleValue(); $attribute->hasTextValue(); Attribute::fieldsWithValues(); ``` `hasMultipleValues()` returns `true` for Checkbox and ColorPicker. `hasSingleValue()` returns `true` for Select. `hasTextValue()` returns `true` for Text, Number, RichText, and DatePicker. `fieldsWithValues()` returns the types that take predefined values: Checkbox, ColorPicker and Select. The admin shows the Values action only for these types. ## Relationships [#relationships] ### Values [#values] ```php $attribute->values; ``` To add values to an attribute (`key` must be unique within the attribute, `value` holds up to 50 characters): ```php $attribute->values()->create([ 'value' => 'Organic Cotton', 'key' => 'organic-cotton', 'position' => 1, ]); ``` ```php $attribute->values()->createMany([ ['value' => 'Small', 'key' => 'size-s', 'position' => 1], ['value' => 'Medium', 'key' => 'size-m', 'position' => 2], ['value' => 'Large', 'key' => 'size-l', 'position' => 3], ]); ``` ### Products [#products] ```php $attribute->products; ``` Attach an attribute to a product with a predefined value: ```php $attribute->products()->attach($productId, [ 'attribute_value_id' => $valueId, ]); ``` Or with a custom value: ```php $attribute->products()->attach($productId, [ 'attribute_custom_value' => 'Custom specification', ]); ``` ### Variants (AttributeValue) [#variants-attributevalue] AttributeValue can be linked to product variants: ```php $attributeValue->variants; $attributeValue->variants()->attach($variantId); ``` The link is stored in the `attribute_value_product_variant` table (`value_id`, `variant_id`). From the variant side, `values()` returns the attribute values of a `ProductVariant`: ```php $variant->values; ``` ## Slug & Lookup [#slug--lookup] When you set `slug`, the `HasSlug` trait passes it through `Str::slug()` and appends `-1`, `-2` and so on if another attribute already uses it. It does not build the slug from `name`, so pass `slug` when you create an attribute. The trait also provides a `findBySlug()` static method, which throws a `ModelNotFoundException` when no attribute matches: ```php use Shopper\Core\Models\Attribute; $attribute = Attribute::findBySlug('color'); ``` ## Query Scopes [#query-scopes] Filter attributes by their visibility and behavior flags: ```php use Shopper\Core\Models\Attribute; Attribute::query()->enabled()->get(); Attribute::query()->isFilterable()->get(); Attribute::query()->isSearchable()->get(); ``` Scopes can be combined: ```php Attribute::query() ->enabled() ->isFilterable() ->with('values') ->get(); ``` ## Status Management [#status-management] ```php $attribute->updateStatus(true); $attribute->updateStatus(false); ``` `updateStatus()` writes `is_enabled` and defaults to `true`. ## Display Helpers [#display-helpers] ```php $attribute->type_formatted; Attribute::typesFields(); ``` `type_formatted` returns the translated label of the type, like "Checkbox" or "Color picker". `typesFields()` returns every type as a `value => label` array, like `['checkbox' => 'Checkbox', 'colorpicker' => 'Color picker', ...]`. ## Working with AttributeProduct [#working-with-attributeproduct] Each `AttributeProduct` row has `attribute`, `product` and `value` relationships, and a computed `real_value` accessor: ```php use Shopper\Core\Models\AttributeProduct; $attributeProduct = AttributeProduct::query()->find($id); // Get the actual value (custom or from value relationship) $attributeProduct->real_value; // Returns attribute_custom_value if set, otherwise value->value ``` ## Creating Attributes [#creating-attributes] ### Attribute with Predefined Values [#attribute-with-predefined-values] ```php use Shopper\Core\Models\Attribute; use Shopper\Core\Enum\FieldType; // Create a color attribute $color = Attribute::query()->create([ 'name' => 'Color', 'slug' => 'color', 'type' => FieldType::ColorPicker, 'is_enabled' => true, 'is_filterable' => true, ]); // Add color values $color->values()->createMany([ ['value' => 'Red', 'key' => '#dc2626', 'position' => 1], ['value' => 'Blue', 'key' => '#2563eb', 'position' => 2], ['value' => 'Green', 'key' => '#16a34a', 'position' => 3], ]); ``` For a ColorPicker attribute, `key` holds the hex code: the admin edits it with a color picker and draws the swatch from it. `value` is the color name. ### Attribute with Free Text [#attribute-with-free-text] ```php // Create a text attribute (no predefined values needed) $material = Attribute::query()->create([ 'name' => 'Material', 'slug' => 'material', 'type' => FieldType::Text, 'is_enabled' => true, 'is_searchable' => true, ]); ``` ## Assigning Attributes to Products [#assigning-attributes-to-products] On the product side the relationship is `options()`, because `attributes` is already a property of every Eloquent model. A Checkbox or ColorPicker attribute takes one row per selected value, so `$product->options` returns that attribute once per value. In the admin, the Attributes tab appears on standard, variant and virtual products, not on external ones. ```php use Shopper\Models\Product; $product = Product::query()->find($id); // Assign attribute with predefined value (via options relationship) $product->options()->attach($attributeId, [ 'attribute_value_id' => $valueId, ]); // Assign several values of a Checkbox or ColorPicker attribute: one row per value foreach ($valueIds as $valueId) { $product->options()->attach($attributeId, [ 'attribute_value_id' => $valueId, ]); } // Assign attribute with custom value $product->options()->attach($attributeId, [ 'attribute_custom_value' => '100% Cotton', ]); // Get product attributes with values foreach ($product->options as $attribute) { $valueId = $attribute->pivot->attribute_value_id; $customValue = $attribute->pivot->attribute_custom_value; } ``` ## Retrieving Attributes [#retrieving-attributes] ```php use Shopper\Core\Models\Attribute; // Get all enabled attributes with values $attributes = Attribute::query() ->enabled() ->with('values') ->get(); // Get filterable attributes for storefront $filters = Attribute::query() ->enabled() ->isFilterable() ->with(['values' => fn ($q) => $q->orderBy('position')]) ->get(); // Get attribute by slug $size = Attribute::findBySlug('size'); $size->load('values'); ``` ## Observer Behavior [#observer-behavior] The `AttributeObserver` handles cleanup when deleting: ```php // When an attribute is deleted: // 1. All product associations are detached // 2. All attribute values are deleted $attribute->delete(); // Triggers observer cleanup ``` ## Disabling Attribute Feature [#disabling-attribute-feature] ```php // config/shopper/features.php use Shopper\Enum\FeatureState; return [ 'attribute' => FeatureState::Disabled, ]; ``` This removes the Attributes page, its menu entry and the Attributes tab of the product page. The models and their data stay. ## Permissions [#permissions] The admin panel generates five permissions for attribute management: | Permission | Description | |------------|-------------| | `browse_attributes` | View the attributes list | | `read_attributes` | View a single attribute | | `add_attributes` | Create new attributes | | `edit_attributes` | Edit existing attributes | | `delete_attributes` | Delete attributes | ## Components [#components] Attribute components are part of the product configuration. To customize them: ```bash php artisan shopper:component:publish product ``` Attribute-related components in `config/shopper/components/product.php`: ```php use Shopper\Livewire; use Shopper\Livewire\Components; return [ 'pages' => [ // ... 'attribute-index' => Livewire\Pages\Attribute\Browse::class, ], 'components' => [ // ... 'products.form.attributes' => Components\Products\Form\Attributes::class, 'slide-overs.attribute-form' => Livewire\SlideOvers\AttributeForm::class, 'slide-overs.choose-product-attributes' => Livewire\SlideOvers\ChooseProductAttributes::class, 'slide-overs.attribute-values' => Livewire\SlideOvers\AttributeValues::class, ], ]; ``` ## Storefront Example [#storefront-example] ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Shopper\Core\Models\Attribute; use Shopper\Models\Product; class ProductFilterController extends Controller { public function index() { // Get filterable attributes for sidebar $filters = Attribute::query() ->enabled() ->isFilterable() ->with(['values' => fn ($q) => $q->orderBy('position')]) ->get(); return view('products.index', compact('filters')); } public function filter(Request $request) { $query = Product::query()->publish(); foreach ($request->input('attributes', []) as $slug => $values) { $query->whereHas('options', function ($q) use ($slug, $values) { $q->where('slug', $slug) ->whereIn(shopper_table('attribute_product').'.attribute_value_id', $values); }); } return $query->paginate(12); } } ``` ## Use Cases [#use-cases] | Attribute Type | Example | Use Case | |----------------|---------|----------| | Checkbox | Size | Multiple sizes available for clothing | | ColorPicker | Color | Product color options | | Select | Material | Single material selection | | Text | SKU Suffix | Custom text per product | | Number | Weight | Numeric specifications | | DatePicker | Release Date | Product launch date | | RichText | Care Instructions | Detailed HTML content | # Brands (/2.x/brands) Brands represent manufacturers or labels for your products. They help customers identify and filter products from their favorite manufacturers, and they give your storefront structured navigation (e.g., a "Shop by Brand" page or a brand filter in search results). ## Model [#model] The model used is `Shopper\Models\Brand`, which extends `Shopper\Core\Models\Brand`. The core model provides the business logic, relationships, scopes, and slug generation. The admin model adds media collections and conversions through Spatie MediaLibrary. The core model implements `Shopper\Core\Models\Contracts\Brand` and uses the `HasSlug` trait for automatic slug generation with collision handling, and the `HasMediaCollections` trait for config-driven media support. ### Extending the Model [#extending-the-model] To add custom behavior, extend the admin model and update your configuration: ```php namespace App\Models; use Shopper\Models\Brand as ShopperBrand; class Brand extends ShopperBrand { } ``` Update `config/shopper/models.php`: ```php return [ 'brand' => \App\Models\Brand::class, ]; ``` ## Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Brand name | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `website` | string | yes | null | Brand's official website URL | | `description` | longtext | yes | null | Brand description (supports rich text) | | `position` | smallint (unsigned) | no | 0 | Display order position (set by drag and drop in the admin brands table) | | `is_enabled` | boolean | no | false | Brand visibility status | | `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 | ## Slug Generation [#slug-generation] The `HasSlug` trait generates unique slugs automatically. When you set the `slug` attribute, the trait runs it through `Str::slug()` and appends an incrementing suffix (`-1`, `-2`, etc.) if a collision is detected. The trait does not build the slug from the name. The admin brand form fills it from the name for you, but when you create a brand in code, pass a `slug` yourself, otherwise the column stays `null`. The trait also provides a `findBySlug()` static method. It throws a `ModelNotFoundException` (a 404 response in a controller) when no brand matches, and it does not check `is_enabled`: ```php use Shopper\Models\Brand; $brand = Brand::findBySlug('nike'); ``` ## Relationships [#relationships] ### Products [#products] A brand has many [products](/2.x/products). This is a standard `HasMany` relationship using the configured product model, through the `brand_id` column of the products table. Deleting a brand keeps its products and sets their `brand_id` to `null`. ```php $brand->products; $brand->products()->count(); ``` To get only published products for a brand (for storefront display): ```php $brand->products()->publish()->get(); ``` With eager loading: ```php $brands = Brand::query()->with('products')->get(); ``` ## Query Scopes [#query-scopes] ### Enabled Brands [#enabled-brands] The `enabled` scope filters brands where `is_enabled` is `true`. Use it for all storefront queries to exclude draft or hidden brands. ```php use Shopper\Models\Brand; Brand::query()->enabled()->orderBy('position')->get(); ``` ## Status Management [#status-management] The `updateStatus()` method provides a convenient way to toggle brand visibility: ```php $brand->updateStatus(true); // enable $brand->updateStatus(false); // disable ``` You can also update the field directly: ```php $brand->update(['is_enabled' => true]); ``` The brand select of the admin product forms only lists enabled brands. ## Media [#media] Brands support two media collections through [Spatie MediaLibrary](https://spatie.be/docs/laravel-medialibrary), using the same config-driven collection names as [products](/2.x/products#media). | Collection | Config key | Behavior | Description | |------------|-----------|----------|-------------| | Default gallery | `shopper.media.storage.collection_name` | Multiple files | Brand images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | Single file | Brand logo | The collections default to `uploads` and `thumbnail`, use the `shopper.media.storage.disk_name` disk and accept the mime types listed in `shopper.media.accepts_mime_types`. The admin brand form uploads the logo to the thumbnail collection, up to `shopper.media.max_size.thumbnail` kilobytes. To add a brand logo: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $brand->addMedia($file)->toMediaCollection($collection); ``` To retrieve the logo URL with a specific conversion: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $url = $brand->getFirstMediaUrl($collection, 'medium'); ``` Conversion names come from `shopper.media.conversions`: `large` and `medium` by default (see [image conversions](/2.x/media#image-conversions)). When the brand has no logo, `getFirstMediaUrl()` returns the Shopper placeholder image, not an empty string. Check `$brand->hasMedia($collection)` first if your storefront should show the brand name instead. From a URL: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $brand->addMediaFromUrl('https://example.com/nike-logo.png') ->toMediaCollection($collection); ``` ## Creating Brands [#creating-brands] To create a brand with a logo and SEO metadata: ```php use Shopper\Models\Brand; $brand = Brand::query()->create([ 'name' => 'Nike', 'slug' => 'nike', 'website' => 'https://nike.com', 'description' => 'Just Do It', 'is_enabled' => true, 'position' => 1, 'seo_title' => 'Nike - Official Products', 'seo_description' => 'Shop official Nike products including shoes, clothing, and accessories.', ]); $collection = config('shopper.media.storage.thumbnail_collection'); $brand->addMedia($logoFile)->toMediaCollection($collection); ``` ## Retrieving Brands [#retrieving-brands] To get all enabled brands ordered by position: ```php Brand::query()->enabled()->orderBy('position')->get(); ``` To get brands that have at least one published product, with their published product counts: ```php $brands = Brand::query() ->enabled() ->whereHas('products', fn ($query) => $query->publish()) ->withCount(['products' => fn ($query) => $query->publish()]) ->get(); ``` To find a brand by slug: ```php $brand = Brand::findBySlug('nike'); ``` For navigation or filter dropdowns where you only need name and slug: ```php $brands = Brand::query() ->enabled() ->select(['id', 'name', 'slug']) ->orderBy('name') ->get(); ``` ## Metadata [#metadata] The `metadata` JSON column lets you store additional custom data that doesn't warrant its own database column. The model casts it to an array. The admin brand form edits `metadata` as a list of key-value pairs with text values. If your team also edits brands in the admin, keep the values flat strings: ```php $brand->update([ 'metadata' => [ 'country_of_origin' => 'USA', 'founded_year' => '1964', 'instagram' => '@nike', ], ]); $country = $brand->metadata['country_of_origin'] ?? null; ``` ## Configuration [#configuration] ### Disabling Brands [#disabling-brands] If you don't need brands in your store, disable the feature in `config/shopper/features.php`: ```php use Shopper\Enum\FeatureState; return [ 'brand' => FeatureState::Disabled, ]; ``` When disabled, the brand menu item is hidden from the sidebar, brand-related routes are not registered, brand selection is removed from product forms, and the brand column is hidden from the products table. ### Permissions [#permissions] The admin panel generates five permissions for brand management: | Permission | Description | |------------|-------------| | `browse_brands` | View the brands list and its sidebar item | | `read_brands` | View a single brand (the admin has no brand detail page and does not check it) | | `add_brands` | Create new brands | | `edit_brands` | Edit existing brands, reorder them, and enable or disable them in bulk | | `delete_brands` | Delete brands, one at a time or in bulk | ## Components [#components] To customize the admin UI for brand management: ```bash php artisan shopper:component:publish brand ``` This creates `config/shopper/components/brand.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'brand-index' => Livewire\Pages\Brand\Index::class, ], 'components' => [ 'slide-overs.brand-form' => Livewire\SlideOvers\BrandForm::class, ], ]; ``` The `BrandForm` slide-over handles both creating and editing a brand. To add content above or below the brands table without publishing components, use the `CatalogRenderHook::BRANDS_TABLE_BEFORE` and `CatalogRenderHook::BRANDS_TABLE_AFTER` [render hooks](/2.x/render-hooks#catalog-hooks). ## Storefront Example [#storefront-example] This example shows a brand listing page and a brand detail page with its published products. The detail page queries with the `enabled` scope so a disabled brand returns a 404. ```php namespace App\Http\Controllers; use Shopper\Models\Brand; class BrandController extends Controller { public function index() { $brands = Brand::query() ->enabled() ->withCount(['products' => fn ($query) => $query->publish()]) ->orderBy('position') ->get(); return view('brands.index', compact('brands')); } public function show(string $slug) { $brand = Brand::query() ->enabled() ->where('slug', $slug) ->firstOrFail(); $products = $brand->products() ->publish() ->paginate(12); return view('brands.show', compact('brand', 'products')); } } ``` ### View Composer [#view-composer] For brands that appear in multiple views (header, footer, filters), use a View Composer to avoid repeating the query: ```php namespace App\View\Composers; use Illuminate\View\View; use Shopper\Models\Brand; class BrandsComposer { public function compose(View $view): void { $view->with('brands', Brand::query() ->enabled() ->orderBy('position') ->take(12) ->get() ); } } ``` Register it in your `AppServiceProvider`: ```php use App\View\Composers\BrandsComposer; use Illuminate\Support\Facades\View; public function boot(): void { View::composer(['partials.brands', 'filters.brands'], BrandsComposer::class); } ``` # Carriers (/2.x/carriers) Carriers represent shipping providers and their delivery options. Shopper uses a two-level structure with carriers (the shipping company) and carrier options (specific delivery methods with prices per zone). Shopper provides a flexible shipping system that supports both manual rate configuration and real-time API integration with major carriers like UPS, FedEx, and USPS. ## Models [#models] Shopper uses two models to manage shipping: | Model | Purpose | |-------|---------| | `Shopper\Core\Models\Carrier` | The shipping provider (UPS, FedEx, local delivery) | | `Shopper\Core\Models\CarrierOption` | Specific delivery methods with pricing per zone | The Carrier model implements `Shopper\Core\Models\Contracts\Carrier` and uses the `HasSlug` and `HasZones` traits. It is not configurable via `config/shopper/models.php`. ## Database Schema [#database-schema] ### Carrier Table [#carrier-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Carrier name | | `slug` | string | yes | null | URL-friendly identifier (unique). The value you pass is slugified and suffixed (`-1`, `-2`) when taken; nothing is generated when you omit it. The admin form fills it from the name | | `driver` | string | yes | null | Shipping driver code (`manual`, `ups`, `fedex`, `usps` or a custom driver). `null` is treated as `manual`; the admin form stores `manual` | | `link_url` | string | yes | null | Carrier website URL | | `description` | string | yes | null | Carrier description | | `shipping_amount` | integer | yes | null | Amount in cents. Shopper does not read this column: rates come from the driver or from carrier options | | `is_enabled` | boolean | no | false | Carrier visibility | | `metadata` | json | yes | null | Additional custom data | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### CarrierOption Table [#carrieroption-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Option name, unique per zone (unique index on `name` and `zone_id`) | | `description` | string(255) | yes | null | Option description | | `price` | integer | no | - | Shipping price (cents) | | `is_enabled` | boolean | no | false | Option visibility | | `carrier_id` | bigint | no | - | FK to carrier | | `zone_id` | bigint | no | - | FK to zone | | `metadata` | json | yes | null | Additional custom data | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Shipping Drivers [#shipping-drivers] Shopper uses a driver-based architecture for shipping, similar to [Laravel's Mail](https://laravel.com/docs/mail) or [Queue systems](https://laravel.com/docs/queues). This allows you to connect carriers directly to shipping provider APIs for real-time rate calculation, or use manual rates stored in your database. ### Available Drivers [#available-drivers] | Driver | Code | Description | |--------|------|-------------| | Manual | `manual` | Rates come from `CarrierOption` records in your database | | UPS | `ups` | Real-time rates from UPS API | | FedEx | `fedex` | Real-time rates from FedEx API | | USPS | `usps` | Real-time rates from USPS API | ### Driver Configuration [#driver-configuration] All driver credentials are stored in your `.env` file. Publish the shipping configuration file to customize drivers: ```bash php artisan vendor:publish --tag=shopper-config ``` The `shopper-config` tag publishes every Shopper config file; files already in `config/shopper` are kept unless you add `--force` (Laravel's `vendor:publish` behavior). This creates `config/shopper/shipping.php`: ```php return [ 'drivers' => [ 'ups' => [ 'enabled' => env('SHIPPING_UPS_ENABLED', false), 'sandbox' => env('SHIPPING_SANDBOX', false), 'credentials' => [ 'client_id' => env('UPS_CLIENT_ID'), 'client_secret' => env('UPS_CLIENT_SECRET'), 'user_id' => env('UPS_USER_ID'), 'account_number' => env('UPS_ACCOUNT_NUMBER'), ], ], 'fedex' => [ 'enabled' => env('SHIPPING_FEDEX_ENABLED', false), 'sandbox' => env('SHIPPING_SANDBOX', false), 'credentials' => [ 'client_id' => env('FEDEX_CLIENT_ID'), 'client_secret' => env('FEDEX_CLIENT_SECRET'), 'account_number' => env('FEDEX_ACCOUNT_NUMBER'), ], ], 'usps' => [ 'enabled' => env('SHIPPING_USPS_ENABLED', false), 'sandbox' => env('SHIPPING_SANDBOX', false), 'credentials' => [ 'client_id' => env('USPS_CLIENT_ID'), 'client_secret' => env('USPS_CLIENT_SECRET'), ], ], ], 'units' => env('SHIPPING_UNITS', 'metric'), ]; ``` The published file also contains `canada_post` and `purolator` entries. No built-in driver reads them: to use those carriers, register a [custom driver](/2.x/carriers#custom-shipping-drivers) under the same code. Shopper does not apply the `units` value to packages for you: read it with `config('shopper.shipping.units')` when you build your `Package` objects. Add the credentials to your `.env` file: ```dotenv SHIPPING_UPS_ENABLED=true SHIPPING_SANDBOX=true UPS_CLIENT_ID=your-client-id UPS_CLIENT_SECRET=your-client-secret UPS_USER_ID=your-user-id UPS_ACCOUNT_NUMBER=your-account-number ``` A driver is ready when its credentials are filled: UPS needs all four values above, FedEx needs `client_id`, `client_secret` and `account_number`, USPS needs `client_id` and `client_secret`. The `enabled` flag only decides whether the driver appears in `Shipping::configuredDrivers()`. Rate calculation and the admin carrier form check the credentials, not this flag. ### Using the Shipping Facade [#using-the-shipping-facade] The `Shipping` facade provides access to the shipping manager and all registered drivers: ```php use Shopper\Shipping\Facades\Shipping; $driver = Shipping::driver('ups'); $allDrivers = Shipping::availableDrivers(); $configured = Shipping::configuredDrivers(); $isReady = Shipping::isConfigured('fedex'); ``` - `driver()` returns a `ShippingDriver` instance. Called without a name, it returns the `manual` driver. An unknown name throws an `InvalidArgumentException`. - `availableDrivers()` returns the driver codes: `manual`, `ups`, `fedex`, `usps` and every custom driver you registered. - `configuredDrivers()` returns a collection of driver instances keyed by code: `manual` plus the drivers whose `enabled` flag is `true`. - `isConfigured()` returns `true` when the driver's credentials are filled, and `false` for an unknown driver. ### Carrier Driver Integration [#carrier-driver-integration] The Carrier model has no driver methods of its own: the `CarrierRateService` resolves the driver from the carrier's `driver` column, and `logo()` asks that driver for its logo URL: ```php use Shopper\Core\Models\Carrier; use Shopper\Shipping\Services\CarrierRateService; $carrier = Carrier::query()->where('driver', 'ups')->first(); $service = app(CarrierRateService::class); $driver = $service->resolveDriver($carrier); $isConfigured = $service->isDriverConfigured($carrier); $logo = $carrier->logo(); ``` `resolveDriver()` returns `null` when the carrier's driver is empty or `manual`. When a carrier has a driver whose credentials are set, Shopper uses that driver to fetch real-time rates from the carrier's API. When no driver is assigned, the driver is `manual`, or its credentials are missing, rates come from the CarrierOption records in your database. ## Calculating Shipping Rates [#calculating-shipping-rates] The `CarrierRateService` provides a unified way to get shipping rates, regardless of whether the carrier uses an API driver or manual configuration. ```php use Shopper\Shipping\Services\CarrierRateService; use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; $service = app(CarrierRateService::class); $from = new Address( firstName: 'Store', lastName: 'Warehouse', street: '123 Warehouse St', city: 'Los Angeles', postalCode: '90001', state: 'CA', country: 'US', ); $to = new Address( firstName: 'John', lastName: 'Doe', street: '456 Customer Ave', city: 'New York', postalCode: '10001', state: 'NY', country: 'US', ); $packages = [ new Package( length: 30, width: 20, height: 15, weight: 2.5, unit: 'metric', ), ]; ``` The `country` of an `Address` is the two-letter ISO code (`US`, `CA`, `FR`), which the drivers send to the carrier API. A `Package` takes `unit: 'metric'` (centimeters and kilograms, the default) or `unit: 'imperial'` (inches and pounds). The built-in drivers convert packages to the units their API expects. ### Getting Rates for a Carrier [#getting-rates-for-a-carrier] ```php $rates = $service->getRatesForCarrier( carrier: $carrier, from: $from, to: $to, packages: $packages, zone: $zone, ); ``` For carriers with an API driver whose credentials are set, rates are fetched from the carrier's API. For manual carriers, rates come from the enabled CarrierOption records of the specified zone. The `zone` argument is optional: without it, every enabled option of the carrier is returned, priced in the store's default currency. When the carrier API fails, the driver throws a `Shopper\Shipping\Exceptions\ShippingException`. ### Getting Rates for a Zone [#getting-rates-for-a-zone] To get all available shipping rates for a zone across its enabled carriers: ```php $rates = $service->getRatesForZone( zone: $zone, from: $from, to: $to, packages: $packages, ); ``` Only carriers attached to the zone are included (see [zone carriers](/2.x/zones#carriers)). `getRatesForZone()` does not catch a `ShippingException`: when one carrier API fails, the call throws and returns no rate at all. To keep the other carriers' rates, call `getRatesForCarrier()` for each carrier yourself: ```php use Shopper\Core\Models\Carrier; use Shopper\Shipping\Exceptions\ShippingException; $rates = $zone->carriers()->enabled()->get()->flatMap(function (Carrier $carrier) use ($service, $from, $to, $packages, $zone) { try { return $service->getRatesForCarrier($carrier, $from, $to, $packages, $zone); } catch (ShippingException $exception) { report($exception); return collect(); } }); ``` ### ShippingRate DTO [#shippingrate-dto] Both methods return a collection of `ShippingRate` objects: ```php foreach ($rates as $rate) { $rate->serviceCode; $rate->serviceName; $rate->amount; $rate->currency; $rate->carrierCode; $rate->estimatedDays; $rate->estimatedDelivery; $rate->formattedAmount(); $rate->toArray(); } ``` `amount` is in cents and `formattedAmount()` formats it with `shopper_money_format()`. For a manual rate, `serviceCode` is the CarrierOption id, `serviceName` its name, `currency` the zone's currency code, `carrierCode` the carrier slug (its name when the slug is empty), and `estimatedDays` and `estimatedDelivery` are `null`. ## Custom Shipping Drivers [#custom-shipping-drivers] Shopper's shipping system is designed for extensibility. You can create custom drivers for any shipping provider not included by default, such as DHL, Canada Post, Colissimo, or regional carriers. ### Creating a Driver [#creating-a-driver] A shipping driver must implement the `ShippingDriver` contract. The easiest approach is to extend the abstract `Driver` class, which provides sensible defaults for optional methods. Create your driver class: ```php namespace App\Shipping\Drivers; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Http; use Shopper\Shipping\Drivers\Driver; use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; use Shopper\Shipping\DataTransferObjects\ShippingRate; use Shopper\Shipping\Exceptions\ShippingException; final class DhlDriver extends Driver { public function __construct( private readonly string $apiKey, private readonly string $accountNumber, private readonly bool $sandbox = false, ) {} public function code(): string { return 'dhl'; } public function name(): string { return 'DHL Express'; } public function logo(): ?string { return asset('images/carriers/dhl.svg'); } public function isConfigured(): bool { return filled($this->apiKey) && filled($this->accountNumber); } public function supportsLabels(): bool { return false; } public function supportsTracking(): bool { return false; } public function calculateRates(Address $from, Address $to, array $packages): Collection { if (! $this->isConfigured()) { throw ShippingException::notConfigured('dhl'); } $packages = $this->normalizePackages($packages); $response = Http::withHeaders([ 'DHL-API-Key' => $this->apiKey, ])->post($this->getApiUrl().'/rates', [ 'accountNumber' => $this->accountNumber, 'originAddress' => $this->formatAddress($from), 'destinationAddress' => $this->formatAddress($to), 'packages' => $this->formatPackages($packages), ]); if ($response->failed()) { throw ShippingException::apiError('dhl', $response->body()); } return collect($response->json('products'))->map(fn (array $product) => new ShippingRate( serviceCode: $product['productCode'], serviceName: $product['productName'], amount: is_no_division_currency($product['priceCurrency']) ? (int) $product['totalPrice'] : (int) round($product['totalPrice'] * 100), currency: $product['priceCurrency'], carrierCode: 'dhl', estimatedDays: $product['deliveryCapabilities']['estimatedDeliveryDays'] ?? null, )); } private function getApiUrl(): string { return $this->sandbox ? 'https://express.api.dhl.com/mydhlapi/test' : 'https://express.api.dhl.com/mydhlapi'; } private function formatAddress(Address $address): array { return [ 'postalCode' => $address->postalCode, 'cityName' => $address->city, 'countryCode' => $address->country, ]; } private function formatPackages(array $packages): array { return array_map(fn (Package $p) => [ 'weight' => $p->weight, 'dimensions' => [ 'length' => $p->length, 'width' => $p->width, 'height' => $p->height, ], ], $packages); } } ``` ### The Driver Contract [#the-driver-contract] The `ShippingDriver` contract defines the following methods: | Method | Return | Description | |--------|--------|-------------| | `code()` | `string` | Unique identifier for the driver | | `name()` | `string` | Human-readable name displayed in the admin | | `logo()` | `?string` | URL to the carrier's logo | | `isConfigured()` | `bool` | Whether required credentials are set | | `supportsRealTimeRates()` | `bool` | Whether the driver can fetch rates from an API | | `supportsLabels()` | `bool` | Whether the driver can generate shipping labels | | `supportsTracking()` | `bool` | Whether the driver can track shipments | | `calculateRates()` | `Collection` | Get shipping rates for the given addresses and packages | | `createShipment()` | `Shipment` | Create a shipment and get the label | | `track()` | `TrackingInfo` | Get tracking information for a shipment | The abstract `Driver` class provides default implementations for `logo()` (returns `null`), `supportsRealTimeRates()`, `supportsLabels()`, and `supportsTracking()` (all return `true`), and throws `ShippingException::notSupported()` for `createShipment()` and `track()`. Override these methods as needed for your driver: a driver that keeps the default `createShipment()` and `track()` should return `false` from `supportsLabels()` and `supportsTracking()`. None of the built-in drivers creates labels or tracks shipments: their `createShipment()` and `track()` throw `ShippingException::notSupported()`. The `amount` of a `ShippingRate` is an integer in cents. Convert the decimal price of a carrier API with `round()` and skip the multiplication for zero-decimal currencies (`is_no_division_currency()`), as the built-in drivers do. See [zero-decimal currencies](/2.x/pricing#zero-decimal-currencies). ### Registering the Driver [#registering-the-driver] Register your custom driver in a service provider using the `extend` method on the Shipping facade. Add the provider to `bootstrap/providers.php`, or put the `extend` call in the `boot()` method of your `AppServiceProvider`: ```php namespace App\Providers; use App\Shipping\Drivers\DhlDriver; use Illuminate\Support\ServiceProvider; use Shopper\Shipping\Facades\Shipping; class ShippingServiceProvider extends ServiceProvider { public function boot(): void { Shipping::extend('dhl', function (): DhlDriver { $config = config('shopper.shipping.drivers.dhl', []); return new DhlDriver( apiKey: $config['credentials']['api_key'] ?? '', accountNumber: $config['credentials']['account_number'] ?? '', sandbox: $config['sandbox'] ?? false, ); }); } } ``` The closure receives the driver name as a parameter and must return an instance of `ShippingDriver`. Drivers are resolved lazily, meaning the closure is only called when the driver is first accessed. ### Adding Configuration [#adding-configuration] Add your driver configuration to `config/shopper/shipping.php`: ```php 'drivers' => [ // ... existing drivers 'dhl' => [ 'enabled' => env('SHIPPING_DHL_ENABLED', false), 'sandbox' => env('SHIPPING_SANDBOX', false), 'credentials' => [ 'api_key' => env('DHL_API_KEY'), 'account_number' => env('DHL_ACCOUNT_NUMBER'), ], ], ], ``` Once registered, your driver appears automatically in the carrier form dropdown and can be assigned to carriers like any built-in driver. ### Driver Capabilities [#driver-capabilities] The abstract `Driver` class provides a `normalizePackages()` helper method that converts between metric and imperial units. This is useful since different carriers expect different unit systems: ```php public function calculateRates(Address $from, Address $to, array $packages): Collection { $packages = $this->normalizePackages($packages, 'imperial'); // ... } ``` Pass `'metric'` for carriers expecting centimeters and kilograms, or `'imperial'` for those expecting inches and pounds. ## Relationships [#relationships] ### Carrier Options [#carrier-options] ```php $carrier->options; $carrier->options()->enabled()->get(); $carrier->options()->create([ 'name' => 'Express Delivery', 'price' => 1500, 'zone_id' => $zoneId, 'is_enabled' => true, ]); ``` ### Zones [#zones] The `HasZones` trait links a carrier to zones through the `zone_has_relations` pivot table. `CarrierRateService::getRatesForZone()` only uses carriers attached to the zone, and the admin shipping option form only lists them (see [zone carriers](/2.x/zones#carriers)): ```php $carrier->zones; $carrier->zones()->attach($zoneId); ``` ### Zone (CarrierOption) [#zone-carrieroption] ```php $option->zone; CarrierOption::query() ->where('zone_id', $zoneId) ->enabled() ->get(); ``` ### Carrier (CarrierOption) [#carrier-carrieroption] ```php $option->carrier; $option->isEnabled(); ``` ## Query Scopes [#query-scopes] ```php use Shopper\Core\Models\Carrier; use Shopper\Core\Models\CarrierOption; Carrier::query()->enabled()->get(); CarrierOption::query()->enabled()->get(); ``` ## Price Handling [#price-handling] CarrierOption prices are stored in cents: ```php $option = CarrierOption::query()->create([ 'name' => 'Standard Shipping', 'price' => 1000, 'zone_id' => $zoneId, 'carrier_id' => $carrierId, ]); shopper_money_format($option->price, $zone->currency->code); ``` `1000` is 10.00 in a currency with cents. For a zero-decimal currency such as XAF or JPY, the price is stored in whole units and `shopper_money_format()` does not divide it (see [zero-decimal currencies](/2.x/pricing#zero-decimal-currencies)). ## Creating Carriers [#creating-carriers] ### Manual Carrier [#manual-carrier] For carriers where you define rates manually in the database: ```php use Shopper\Core\Models\Carrier; $carrier = Carrier::query()->create([ 'name' => 'Local Delivery', 'slug' => 'local-delivery', 'description' => 'Same-day delivery within city limits', 'is_enabled' => true, ]); $carrier->zones()->attach($localZoneId); $carrier->options()->createMany([ [ 'name' => 'Standard', 'price' => 500, 'zone_id' => $localZoneId, 'is_enabled' => true, ], [ 'name' => 'Express (2 hours)', 'price' => 1500, 'zone_id' => $localZoneId, 'is_enabled' => true, ], ]); ``` ### API-Connected Carrier [#api-connected-carrier] For carriers using a shipping driver to fetch real-time rates: ```php $carrier = Carrier::query()->create([ 'name' => 'UPS', 'slug' => 'ups', 'driver' => 'ups', 'link_url' => 'https://ups.com', 'is_enabled' => true, ]); $carrier->zones()->attach($nationalZoneId); ``` With an API driver whose credentials are set, you don't need to create CarrierOption records. Rates are fetched directly from the carrier's API when needed. Until the credentials are set, the carrier falls back to its CarrierOption records. ### Free Shipping Option [#free-shipping-option] ```php $freeShipping = Carrier::query()->create([ 'name' => 'Free Shipping', 'slug' => 'free-shipping', 'description' => 'Free standard shipping', 'is_enabled' => true, ]); $freeShipping->zones()->attach($domesticZoneId); $freeShipping->options()->create([ 'name' => 'Free Standard Delivery', 'price' => 0, 'zone_id' => $domesticZoneId, 'is_enabled' => true, 'metadata' => [ 'min_order_amount' => 5000, 'estimated_days' => '5-7', ], ]); ``` Shopper stores `metadata` as is and never reads these keys: your checkout must hide the option when the cart total is below `min_order_amount` (in cents) and display `estimated_days` itself. ## Retrieving Carriers [#retrieving-carriers] ```php use Shopper\Core\Models\Carrier; use Shopper\Core\Models\CarrierOption; $carriers = Carrier::query() ->enabled() ->with(['options' => fn ($q) => $q->enabled()]) ->get(); $carrier = Carrier::query() ->where('slug', 'fedex') ->first(); $carrier = Carrier::findBySlug('fedex'); $options = CarrierOption::query() ->where('zone_id', $zoneId) ->enabled() ->with('carrier') ->orderBy('price') ->get(); $cheapest = CarrierOption::query() ->where('zone_id', $zoneId) ->enabled() ->orderBy('price') ->first(); ``` `findBySlug()` comes from the `HasSlug` trait and throws a `ModelNotFoundException` when no carrier has that slug. ## Working with Orders [#working-with-orders] ```php use Shopper\Core\Enum\ShipmentStatus; use Shopper\Core\Models\Order; use Shopper\Core\Models\OrderShipping; $order->shippingOption; $order->shippings; OrderShipping::query()->create([ 'order_id' => $order->id, 'carrier_id' => $carrierId, 'status' => ShipmentStatus::Pending, 'tracking_number' => 'TRACK123456', 'tracking_url' => 'https://fedex.com/track/TRACK123456', ]); ``` `shippingOption` is the CarrierOption the customer picked (`shipping_option_id` on the order), and `shippings` are the order's shipments. Create a shipment with the `Pending` status: `shipped_at` is set when you record the carrier pickup (see [Creating Shipments](/2.x/fulfillment#creating-shipments)). ## Storefront Example [#storefront-example] ### Checkout Shipping Selection [#checkout-shipping-selection] The origin address for shipping calculations should come from your store's inventory (warehouse). Shopper uses the `Inventory` model to represent physical locations where products are stored and shipped from. ```php namespace App\Http\Controllers; use Shopper\Cart\Facades\Cart; use Shopper\Cart\Models\Cart as CartModel; use Shopper\Cart\Models\CartAddress; use Shopper\Cart\Models\CartLine; use Shopper\Core\Enum\Dimension\Weight; use Shopper\Core\Models\Inventory; use Shopper\Core\Models\Zone; use Shopper\Shipping\Services\CarrierRateService; use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; class CheckoutController extends Controller { public function __construct( private readonly CarrierRateService $rateService, ) {} public function showShipping(?int $inventoryId = null) { $cart = Cart::current() ?? abort(404); $address = $cart->shippingAddress() ?? abort(404); $inventory = $this->getShippingInventory($inventoryId); $zone = $this->getCustomerZone($cart, $address); $from = $this->getInventoryAddress($inventory); $to = $this->getCustomerAddress($address); $packages = $this->getCartPackages($cart); $shippingOptions = $this->rateService->getRatesForZone( zone: $zone, from: $from, to: $to, packages: $packages, ); return view('checkout.shipping', compact('shippingOptions')); } private function getShippingInventory(?int $inventoryId = null): Inventory { if ($inventoryId) { return Inventory::query()->findOrFail($inventoryId); } return Inventory::query()->default()->firstOrFail(); } private function getInventoryAddress(Inventory $inventory): Address { return new Address( firstName: $inventory->name, lastName: '', street: $inventory->street_address, street2: $inventory->street_address_plus, city: $inventory->city, postalCode: $inventory->postal_code, state: $inventory->state ?? '', country: $inventory->country->cca2, phone: $inventory->phone_number, email: $inventory->email, ); } private function getCustomerAddress(CartAddress $address): Address { return new Address( firstName: $address->first_name ?? '', lastName: $address->last_name, street: $address->address_1, city: $address->city, postalCode: $address->postal_code, state: $address->state ?? '', country: $address->country->cca2, company: $address->company, street2: $address->address_2, phone: $address->phone, ); } private function getCartPackages(CartModel $cart): array { $weight = $cart->lines()->with('purchasable')->get()->sum( fn (CartLine $line): float => $this->weightInKilograms($line) * $line->quantity ); return [ new Package( length: 40, width: 30, height: 20, weight: $weight, ), ]; } private function weightInKilograms(CartLine $line): float { $value = (float) $line->purchasable->weight_value; return match ($line->purchasable->weight_unit) { Weight::G => $value / 1000, Weight::LBS => $value * 0.453592, default => $value, }; } private function getCustomerZone(CartModel $cart, CartAddress $address): Zone { return $cart->zone ?? Zone::query() ->enabled() ->whereHas('countries', fn ($query) => $query->whereKey($address->country_id)) ->firstOrFail(); } } ``` Products and variants have their own dimensions (`width_value`, `height_value`, `depth_value`), but adding them up does not give the size of a box. This example ships everything in one 40 x 30 x 20 cm box and sums the weights (`weight_value` converted from `weight_unit`). Replace the box with your own packing rules. If your store has multiple warehouses, you can pass the inventory ID to ship from a specific location. This is useful for selecting the nearest warehouse to the customer or the one with available stock: ```php return redirect()->route('checkout.shipping', ['inventoryId' => $nearestInventory->id]); ``` ## Use Cases [#use-cases] | Carrier | Options | |---------|---------| | USPS | Priority Mail, Ground Advantage, Media Mail | | FedEx | Ground, Express, Overnight | | UPS | Ground, 2-Day, Next Day Air | | DHL | Express, Economy, Freight | | Local | Same-Day, Pick-up | | Scenario | Implementation | |----------|----------------| | Flat rate shipping | Manual carrier with single option at fixed price | | Free shipping threshold | Store `min_order_amount` in the option's metadata and check it in your checkout | | Zone-based pricing | Create options per zone for manual carriers | | Real-time rates | Assign a shipping driver to the carrier and set the driver's credentials | | Hybrid approach | Manual carriers for local, API drivers for national/international | # Cart (/2.x/cart) The `shopper/cart` package handles everything between "Add to cart" and "Place order". It manages cart lines, validates stock, applies discounts, calculates taxes, and converts completed carts into orders. All through a clean, testable API. Every monetary value is stored in **cents** as an unsigned integer. A product priced at $25.00 is stored as `2500`. ## How It Works [#how-it-works] The cart system has five main pieces: 1. **CartManager** handles cart operations: add, update, remove, apply coupons, calculate totals 2. **CartSessionManager** persists the current cart in the session for storefront use 3. **Pipeline system** calculates totals through a configurable chain of pipes (subtotals, then discounts, then taxes, then the total) 4. **DiscountValidator** enforces coupon rules: eligibility, usage limits, zones, minimum amounts 5. **CreateOrderFromCartAction** converts a cart into an order within a database transaction ## Cart Manager [#cart-manager] The `CartManager` is the primary API for all cart operations. It is registered as a singleton and injected with the `CartPipelineRunner`. ```php use Shopper\Cart\CartManager; $manager = resolve(CartManager::class); ``` ### Adding Items [#adding-items] Pass any model that implements `Priceable`, typically a `Product` or `ProductVariant`. The manager looks up the unit price from the purchasable's price list using the cart's currency. If the purchasable has no price in that currency, the line is created with a `unit_price_amount` of `0`. A quantity below `1` throws an `InvalidArgumentException`. ```php $line = $manager->add($cart, $product); $line = $manager->add($cart, $product, quantity: 3); $line = $manager->add($cart, $variant, metadata: [ 'gift_wrap' => true, 'message' => 'Happy birthday!', ]); ``` Adding the same purchasable twice increments the existing line's quantity instead of creating a duplicate. The line keeps the unit price and metadata it was created with. ```php $manager->add($cart, $product, quantity: 2); // quantity: 2 $manager->add($cart, $product, quantity: 3); // quantity: 5 ``` ### Stock Validation [#stock-validation] Every `add()` call, and every `update()` call that sets a quantity, checks available stock. If the purchasable implements `Stockable`, returns `true` from `tracksInventory()` and has `allow_backorder` set to false, an `InsufficientStockException` is thrown when the requested quantity exceeds available inventory. On `add()`, the requested quantity is the line's new total: the quantity already in the cart plus the quantity you add. Virtual and external products do not track inventory, so they are never checked. ```php use Shopper\Cart\Exceptions\InsufficientStockException; try { $manager->add($cart, $product, quantity: 100); } catch (InsufficientStockException $e) { $e->purchasable; // The product or variant $e->available; // Current stock level $e->requested; // Quantity that was requested } ``` Products with `allow_backorder` set to `true` bypass stock checks entirely. ### Updating a Line [#updating-a-line] ```php $updated = $manager->update($cart, $lineId, [ 'quantity' => 5, ]); $updated = $manager->update($cart, $lineId, [ 'metadata' => ['gift_wrap' => false], ]); ``` Only the `quantity` and `metadata` keys are written, any other key is ignored. The new `quantity` replaces the current one and goes through the same minimum and stock checks as `add()`. A `$lineId` that does not belong to the cart throws a `ModelNotFoundException`, in `update()` and in `remove()`. ### Removing Lines [#removing-lines] ```php $manager->remove($cart, $lineId); $manager->clear($cart); ``` ### Applying Coupons [#applying-coupons] The `applyCoupon()` method validates that the discount code exists in the database before setting it on the cart. It does not check whether the discount is active or the cart is eligible: those rules run during the pipeline, along with the discount calculation (see [Discount Validation](/2.x/cart#discount-validation)). ```php use Shopper\Cart\Exceptions\InvalidDiscountException; try { $manager->applyCoupon($cart, 'SUMMER20'); } catch (InvalidDiscountException $e) { // Discount code not found } $manager->removeCoupon($cart); ``` Removing a coupon also deletes all line adjustments that were created by the discount pipeline. ### Adding Addresses [#adding-addresses] ```php use Shopper\Core\Enum\AddressType; $manager->addAddress($cart, AddressType::Shipping, [ 'first_name' => 'John', 'last_name' => 'Doe', 'address_1' => '123 Main St', 'city' => 'New York', 'postal_code' => '10001', 'country_id' => $countryId, ]); $manager->addAddress($cart, AddressType::Billing, $billingData); ``` If an address of the same type already exists, it is updated instead of duplicated. ### Calculating Totals [#calculating-totals] ```php use Shopper\Cart\Pipelines\CartPipelineContext; $context = $manager->calculate($cart); $context->subtotal; // Sum of line subtotals (before discounts/tax) $context->discountTotal; // Total discount amount $context->taxTotal; // Total tax amount $context->total; // Final total $context->taxInclusive; // Whether tax is included in prices $context->lineSubtotals; // Subtotal of each line, keyed by line ID $context->cart; // The cart that was calculated ``` `calculate()` writes to the database: the discount and tax pipes delete and recreate the cart's `CartLineAdjustment` and `CartLineTaxLine` rows. ### Completed Cart Guard [#completed-cart-guard] The line and coupon operations (`add`, `update`, `remove`, `clear`, `applyCoupon`, `removeCoupon`) throw `CartCompletedException` if the cart has already been completed. This prevents modifications after an order has been placed. `addAddress()` does not run this check. ```php use Shopper\Cart\Exceptions\CartCompletedException; $cart->update(['completed_at' => now()]); $manager->add($cart, $product); // throws CartCompletedException ``` ## Session Management [#session-management] The `CartSessionManager` handles cart persistence in the HTTP session. Use it in your storefront to retrieve or create the current customer's cart. ### Using the Facade [#using-the-facade] ```php use Shopper\Cart\Facades\Cart; $cart = Cart::current(); $cart = Cart::create(); $cart = Cart::create(['channel_id' => $channelId, 'zone_id' => $zoneId]); Cart::use($existingCart); Cart::associate($user); Cart::forget(); ``` ### Behavior [#behavior] - `current()` never returns a completed cart or a cart that was deleted. In those cases, and when the session holds no cart, it returns `null`, or a new cart when `shopper.cart.session.auto_create` is `true` - `create()` stores the new cart's ID in the session and sets the `currency_code` from `shopper_currency()` unless you pass one - `use()` stores an existing cart's ID in the session - `associate()` sets the `customer_id` on the current cart and does nothing when there is no current cart. Call this after login - `forget()` removes the cart ID from the session without deleting the cart itself ## Models [#models] ### Cart [#cart] ```php Shopper\Cart\Models\Cart ``` The cart tables are `sh_carts`, `sh_cart_lines`, `sh_cart_addresses`, `sh_cart_line_adjustments` and `sh_cart_line_tax_lines` (`sh_` is the default [table prefix](/2.x/configuration#database-table-prefix)). | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | | Primary key | | `customer_id` | bigint | Yes | FK to `users` | | `channel_id` | bigint | Yes | FK to `sh_channels` | | `zone_id` | bigint | Yes | FK to `sh_zones` | | `currency_code` | string | | ISO currency code (e.g. `USD`) | | `coupon_code` | string | Yes | Applied discount code | | `completed_at` | timestamp | Yes | Set when cart is converted to order | | `metadata` | jsonb | Yes | Custom data | | `created_at` | timestamp | | | | `updated_at` | timestamp | | | #### Relationships [#relationships] ```php $cart->lines; // HasMany $cart->addresses; // HasMany $cart->customer; // BelongsTo, the model in config('auth.providers.users.model') $cart->channel; // BelongsTo $cart->zone; // BelongsTo ``` #### Methods [#methods] ```php $cart->isCompleted(); // bool, checks if completed_at is set $cart->shippingAddress(); // ?CartAddress, address with type Shipping $cart->billingAddress(); // ?CartAddress, address with type Billing ``` ### CartLine [#cartline] ```php Shopper\Cart\Models\CartLine ``` | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | | Primary key | | `cart_id` | bigint | | FK to cart | | `purchasable_type` | string | | Morph type (`Product`, `ProductVariant`, etc.) | | `purchasable_id` | bigint | | Morph ID | | `quantity` | unsigned int | | Item quantity | | `unit_price_amount` | unsigned int | | Price per unit in cents | | `metadata` | jsonb | Yes | Custom data | #### Relationships [#relationships-1] ```php $line->cart; // BelongsTo $line->purchasable; // MorphTo, Product, ProductVariant, etc. $line->adjustments; // HasMany $line->taxLines; // HasMany ``` ### CartAddress [#cartaddress] ```php Shopper\Cart\Models\CartAddress ``` | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | | Primary key | | `cart_id` | bigint | | FK to cart | | `type` | string | | `shipping` or `billing` (AddressType enum) | | `country_id` | bigint | Yes | FK to `sh_countries` | | `first_name` | string | Yes | | | `last_name` | string | | | | `company` | string | Yes | | | `address_1` | string | | Street address | | `address_2` | string | Yes | Apartment, suite, etc. | | `city` | string | | | | `state` | string | Yes | | | `postal_code` | string | | | | `phone` | string | Yes | | The `full_name` accessor combines `first_name` and `last_name`. The `cart` and `country` relations are `BelongsTo`. ### CartLineAdjustment [#cartlineadjustment] ```php Shopper\Cart\Models\CartLineAdjustment ``` | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | | Primary key | | `cart_line_id` | bigint | | FK to cart line | | `discount_id` | bigint | Yes | FK to discount | | `amount` | unsigned int | | Discount amount in cents | | `code` | string | Yes | Coupon code | The `cartLine` and `discount` relations are `BelongsTo`. ### CartLineTaxLine [#cartlinetaxline] ```php Shopper\Cart\Models\CartLineTaxLine ``` | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | | Primary key | | `cart_line_id` | bigint | | FK to cart line | | `tax_rate_id` | bigint | Yes | FK to tax rate | | `code` | string | | Tax code | | `name` | string | | Tax name (e.g. "VAT") | | `rate` | decimal(8,4) | | Tax rate (e.g. `20.0000` for 20%) | | `amount` | unsigned int | | Tax amount in cents | The `cartLine` and `taxRate` relations are `BelongsTo`. ## Calculation Pipeline [#calculation-pipeline] Cart totals are calculated through a pipeline of configurable steps. Each pipe receives a `CartPipelineContext`, performs its calculation, and passes it to the next pipe. ### Default Pipeline [#default-pipeline] ```php use Shopper\Cart\Pipelines\CalculateLines; use Shopper\Cart\Pipelines\ApplyDiscounts; use Shopper\Cart\Pipelines\CalculateTax; use Shopper\Cart\Pipelines\Calculate; // config/shopper/cart.php 'pipelines' => [ 'cart' => [ CalculateLines::class, ApplyDiscounts::class, CalculateTax::class, Calculate::class, ], ], ``` ### Pipeline Steps [#pipeline-steps] **1. CalculateLines**. Computes the subtotal for each line (`unit_price_amount * quantity`), stores it in `$context->lineSubtotals` and sums them into `$context->subtotal`. **2. ApplyDiscounts**. If the cart has a `coupon_code`, loads the active discount with that code, validates it through `DiscountValidator` and calculates the discount amount. For percentage discounts, each applicable line gets `round(lineSubtotal * value / 100)`. For fixed amount discounts, the amount is capped at the subtotal of the applicable lines and distributed proportionally across them, the last line taking the rounding remainder. Replaces the cart's `CartLineAdjustment` records. **3. CalculateTax**. Resolves the shipping address country (and its `state` as the province code) and calculates tax for each line using the core `TaxCalculator`. The taxable amount per line is `(lineSubtotal - discountAmount)`, and a line with nothing left to tax is skipped. Replaces the `CartLineTaxLine` records of each taxed line and sets `$context->taxInclusive` from the [tax zone](/2.x/taxes#tax-zones)'s `is_tax_inclusive`. Without a shipping address country, this step does nothing and `taxTotal` stays `0`. **4. Calculate**. Computes the final total. If tax is inclusive: `total = subtotal - discountTotal`. If tax is exclusive: `total = subtotal - discountTotal + taxTotal`. The minimum total is always `0`. ### Custom Pipeline [#custom-pipeline] You can replace or extend the pipeline in `config/shopper/cart.php`. Add a custom pipe to handle shipping costs, loyalty points, or any other calculation: ```php 'pipelines' => [ 'cart' => [ CalculateLines::class, ApplyDiscounts::class, CalculateTax::class, Calculate::class, App\Cart\Pipes\ApplyShippingCost::class, ], ], ``` `Calculate` overwrites `$context->total`, so a pipe that changes the total goes after it. Each pipe is resolved from the container, so its constructor can receive dependencies. Like Shopper's own pipes, it implements `handle(CartPipelineContext $context, Closure $next)` (an `__invoke()` method with the same signature also works): ```php namespace App\Cart\Pipes; use Closure; use Shopper\Cart\Pipelines\CartPipelineContext; final class ApplyShippingCost { public function handle(CartPipelineContext $context, Closure $next): mixed { if ($context->subtotal < 5000) { $context->total += 990; } return $next($context); } } ``` This pipe adds a $9.90 shipping fee to orders under $50.00. The total it returns is what `CreateOrderFromCartAction` stores as the order's `price_amount`. ## Discount Validation [#discount-validation] When a coupon is applied during the pipeline, the `DiscountValidator` runs a series of checks before the discount is calculated. A failed check does not throw: the pipeline skips the discount, `discountTotal` stays `0` and the code stays on the cart. Each check returns a translatable message from the `shopper-cart::messages` file. To tell the customer why a code does not apply, run the validator yourself: ```php use Shopper\Cart\CartManager; use Shopper\Cart\Discounts\DiscountValidator; use Shopper\Core\Models\Discount; $context = resolve(CartManager::class)->calculate($cart); $discount = Discount::query()->where('code', $cart->coupon_code)->firstOrFail(); $result = resolve(DiscountValidator::class)->validate($discount, $context); if (! $result->valid) { return back()->with('error', $result->failureReason); } ``` ### Validation Rules [#validation-rules] | Rule | Condition | Error Key | |------|-----------|-----------| | Active | `discount->is_active` must be true | `discount.not_active` | | Value | `discount->value` must be greater than `0` | `discount.invalid_value` | | Percentage | A percentage discount's `value` must not exceed `100` | `discount.invalid_percentage` | | Started | `discount->start_at` must not be in the future | `discount.not_started` | | Not expired | `discount->end_at` must be null or in the future | `discount.expired` | | Usage limit | Total uses must be under the global limit | `discount.usage_limit_reached` | | Per-user limit | If `usage_limit_per_user` is true, the customer must have no earlier order with this discount | `discount.already_used` | | Eligibility | If `eligibility` is `customers`, the cart customer must be one of the selected customers | `discount.customer_not_eligible` | | Requires login | If `eligibility` is `customers` or `usage_limit_per_user` is true, the cart must have a `customer_id` | `discount.requires_login` | | Zone | If the discount has a `zone_id`, it must match `cart->zone_id` | `discount.not_available_in_zone` | | Minimum amount | If `min_required` is `price`, the cart subtotal before discount must reach `min_required_value` (in cents) | `discount.min_amount_not_reached` | | Minimum quantity | If `min_required` is `quantity`, the total quantity of all lines must reach `min_required_value` | `discount.min_quantity_not_reached` | ### Discount Application Modes [#discount-application-modes] Discounts support two application scopes via `discount->apply_to`: - **Order** (`DiscountApplyTo::Order`). Applies to all cart lines - **Specific products** (`DiscountApplyTo::Products`). Applies only to lines whose product is selected on the discount. A variant line matches when its parent product is selected And two discount types: - **Percentage**. Each applicable line gets `round(lineSubtotal * value / 100)` - **Fixed amount**. The fixed amount (in cents, capped at the subtotal of the applicable lines) is distributed proportionally across applicable lines based on their share of that subtotal ## Order Conversion [#order-conversion] The `CreateOrderFromCartAction` converts a cart into an order and marks the cart as completed. This is the bridge between the storefront cart and the order management system. ```php use Shopper\Cart\Actions\CreateOrderFromCartAction; $action = resolve(CreateOrderFromCartAction::class); $order = $action->execute($cart); ``` ### What Happens [#what-happens] The entire operation runs inside a database transaction with a `FOR UPDATE` lock on the cart: 1. **Reserves the discount**. If a coupon is applied, locks the discount row with `lockForUpdate`, validates the per-user limit against `orders.discount_id`, and increments `total_use` atomically only if the global `usage_limit` has not been reached 2. **Calculates totals**. Runs the full pipeline to get final amounts 3. **Creates order addresses**. Copies cart shipping/billing addresses to `OrderAddress` records 4. **Creates the order**. With `price_amount`, `tax_amount`, `currency_code`, all foreign keys, and the discount snapshot (`discount_id`, `discount_code`, `discount_type`, `discount_value_at_apply`, `discount_currency_code`) 5. **Creates order items and reserves stock**. One order item per cart line, including the discount amount from adjustments. For every line whose purchasable tracks inventory, stock is reserved through the `StockReserver` contract under a `lockForUpdate` row lock on the stockable. If the reservable quantity is less than the line quantity, `InsufficientStockException` is thrown and the whole transaction rolls back 6. **Creates order tax lines**. Via `CreateOrderTaxLinesAction`, which calculates the tax of each order item again from the shipping address country, stores it as `OrderTaxLine` records and updates the `tax_amount` of the items and the order 7. **Marks cart as completed**. Sets `completed_at` to prevent further modifications 8. **Dispatches `CartCompleted` event**. With the cart and the created order, inside the transaction If the cart has already been completed, `CartCompletedException` is thrown before any work begins. The `FOR UPDATE` lock prevents race conditions from concurrent checkout attempts. ### Discount Limit Exceptions [#discount-limit-exceptions] Two failure paths around discount limits can short-circuit the transaction. `DiscountLimitReachedException::global($code)` is thrown when the global `usage_limit` was exhausted between cart validation and order commit. `DiscountLimitReachedException::perUser($code)` is thrown when the customer has already redeemed a discount with `usage_limit_per_user` set, or when a guest cart (no `customer_id`) uses such a discount. In both cases the transaction rolls back and no order is created. ```php use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Exceptions\DiscountLimitReachedException; try { $order = resolve(CreateOrderFromCartAction::class)->execute($cart); } catch (DiscountLimitReachedException $e) { return back()->with('error', 'This discount can no longer be used.'); } ``` For the full enforcement model, see [Usage Limit Enforcement](/2.x/discounts#usage-limit-enforcement) on the Discounts page. ### Stock Reservation [#stock-reservation] Stock is reserved during checkout, inside the same transaction that creates the order, rather than asynchronously after the order commits. This closes the oversell window where two concurrent checkouts could each read the same last unit and both succeed. Reservation is delegated to the `Shopper\Core\Contracts\StockReserver` contract: ```php namespace Shopper\Core\Contracts; use Illuminate\Database\Eloquent\Model; use Shopper\Core\Models\Contracts\Stockable; interface StockReserver { public function reserve(Stockable $product, int $quantity, ?Model $reference = null, ?int $userId = null): int; } ``` The default implementation, `Shopper\Core\Stock\LockingStockReserver`, takes a `lockForUpdate` row lock on the stockable, decreases the stock of the locations chosen by the `StockAllocator` contract (one `decreaseStock()` movement per location, with the order as reference), and returns the reserved quantity. When the locations together hold less than the requested quantity, it decreases nothing and returns what they hold. A product with `allow_backorder` enabled takes the whole quantity from its first location. See [How Locations Connect to Stock](/2.x/locations#how-locations-connect-to-stock) for how the locations are chosen. The action throws `InsufficientStockException` when that amount is short of the requested quantity. Only purchasables that return `true` from `tracksInventory()` are reserved, so virtual and external products are skipped. To plug in a custom strategy, such as reserving against an external warehouse system, bind your own implementation in a service provider: ```php use Shopper\Core\Contracts\StockReserver; $this->app->bind(StockReserver::class, WarehouseStockReserver::class); ``` ## Events [#events] | Event | Dispatched When | Properties | |-------|-----------------|------------| | `CartCompleted` | Cart is converted to an order | `Cart $cart`, `Order $order` (contracts from `Shopper\Core\Models\Contracts`) | | `CouponApplied` | Coupon code is set on a cart | `Cart $cart`, `string $code` | | `CouponRemoved` | Coupon code is cleared from a cart | `Cart $cart` | ```php use Shopper\Cart\Events\CartCompleted; use Shopper\Cart\Events\CouponApplied; use Shopper\Cart\Events\CouponRemoved; ``` ## Configuration [#configuration] `php artisan shopper:install` publishes `config/shopper/cart.php` with the other Shopper configuration files. To publish the files that are missing, run: ```bash php artisan vendor:publish --tag=shopper-config ``` ```php // config/shopper/cart.php return [ 'pipelines' => [ 'cart' => [ CalculateLines::class, ApplyDiscounts::class, CalculateTax::class, Calculate::class, ], ], 'session' => [ 'key' => 'shopper_cart', // Session key for storing cart ID 'auto_create' => false, // Auto-create cart when current() is called ], 'abandoned_after_minutes' => 60, // Minutes of inactivity before a cart counts as abandoned 'prune_after_days' => 30, // Days before abandoned carts are pruned 'models' => [ 'cart' => Cart::class, // Swappable via model contracts 'cart_line' => CartLine::class, ], ]; ``` ### Model Swapping [#model-swapping] The `Cart` and `CartLine` models implement core contracts (`Shopper\Core\Models\Contracts\Cart`, `Shopper\Core\Models\Contracts\CartLine`) and use the `HasModelContract` trait. You can replace them with your own models: ```php // config/shopper/cart.php 'models' => [ 'cart' => App\Models\Cart::class, 'cart_line' => App\Models\CartLine::class, ], ``` Your custom models must extend `Shopper\Cart\Models\Cart` and `Shopper\Cart\Models\CartLine`, otherwise Shopper throws an `InvalidModelConfigurationException`: ```php namespace App\Models; use Shopper\Cart\Models\Cart as ShopperCart; class Cart extends ShopperCart { } ``` ## Abandoned Carts [#abandoned-carts] A cart is considered "abandoned" when it is not completed, has items, and has not been updated for a configurable period. Shopper provides both an admin interface and programmatic tools to manage abandoned carts. ### Admin Panel [#admin-panel] The admin panel includes an Abandoned Carts page under the Orders section, open to users with the `browse_orders` permission. It lists all carts that are not completed, have at least one line item, and have not been updated for at least `abandoned_after_minutes`. Administrators can view cart contents, the customer (if authenticated), the addresses, and the associated channel. ### Configuration [#configuration-1] Two config keys in `config/shopper/cart.php` control abandoned cart behavior: ```php 'abandoned_after_minutes' => 60, // Cart is "abandoned" after 60 minutes of inactivity 'prune_after_days' => 30, // Carts not completed are deleted after 30 days without update ``` ### Querying Abandoned Carts [#querying-abandoned-carts] To find abandoned carts programmatically, for example to send recovery emails: ```php use Shopper\Cart\Models\Cart; $abandonedCarts = Cart::query() ->whereNull('completed_at') ->whereHas('lines') ->whereNotNull('customer_id') ->where('updated_at', '<', now()->subMinutes( config('shopper.cart.abandoned_after_minutes', 60) )) ->with(['customer', 'lines.purchasable']) ->get(); ``` ### Pruning [#pruning] Old carts are deleted by the `shopper:prune-carts` command: ```bash php artisan shopper:prune-carts php artisan shopper:prune-carts --days=7 ``` By default, carts that haven't been updated in the last 30 days (configurable via `prune_after_days`) are deleted, with or without lines, and their lines go with them. `--days` overrides the setting for one run. Only carts where `completed_at` is `null` are pruned. Completed carts are kept as historical records tied to their orders. Shopper does not schedule the command. Schedule it in your `routes/console.php`: ```php use Illuminate\Support\Facades\Schedule; Schedule::command('shopper:prune-carts')->daily(); ``` ## Storefront Implementation [#storefront-implementation] This section shows how to build a complete cart experience in your storefront. The examples are based on the patterns used in the [Shopper demo store](https://demo.laravelshopper.dev). They use `App\Models\Product` and `App\Models\ProductVariant`, the store's own models that extend Shopper's (see [Extending the Model](/2.x/products#extending-the-model)). ### Cart Session Helper [#cart-session-helper] A common pattern is to create a `cartSession()` helper that handles cart creation with the correct zone and channel. This avoids repeating the creation logic across your controllers and components: ```php // app/helpers.php use Shopper\Cart\CartSessionManager; use Shopper\Cart\Models\Cart; use Shopper\Core\Models\Channel; function cartSession(): Cart { $session = resolve(CartSessionManager::class); $cart = $session->current(); if (! $cart) { $defaultChannel = Channel::query()->scopes('default')->first(); $cart = $session->create([ 'currency_code' => shopper_currency(), 'channel_id' => $defaultChannel?->id, 'zone_id' => session('zone_id'), 'customer_id' => auth()->id(), ]); } return $cart; } ``` Register the helper in your `composer.json`: ```json { "autoload": { "files": ["app/helpers.php"] } } ``` ### Associating Cart on Login [#associating-cart-on-login] When a guest adds items to their cart and then logs in, the cart should be associated with their account. Register a listener for the `Login` event in your `AppServiceProvider`: ```php use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Event; use Shopper\Cart\CartSessionManager; public function boot(): void { Event::listen(Login::class, function (Login $event): void { resolve(CartSessionManager::class)->associate($event->user); }); } ``` ### Add to Cart Action [#add-to-cart-action] Create a dedicated action class that handles adding both products and variants to the cart: ```php namespace App\Actions\Cart; use App\Models\Product; use App\Models\ProductVariant; use Shopper\Cart\CartManager; use Shopper\Cart\Models\CartLine; final readonly class AddToCart { public function __construct( private CartManager $cartManager, ) {} public function handle(Product $product, ?ProductVariant $variant = null): CartLine { $purchasable = $variant ?? $product; return $this->cartManager->add(cartSession(), $purchasable); } } ``` ### Livewire Cart Component [#livewire-cart-component] Here is a complete Livewire component for displaying and managing the cart as a slide-over panel: ```php namespace App\Livewire; use App\Models\ProductVariant; use Illuminate\Contracts\View\View; use Illuminate\Support\Collection; use Livewire\Attributes\On; use Livewire\Component; use Shopper\Cart\CartManager; use Shopper\Cart\CartSessionManager; use Shopper\Cart\Models\CartLine; final class ShoppingCart extends Component { public int|float $subtotal = 0; /** @var Collection */ public Collection $items; public function mount(): void { $this->loadCart(); } #[On('cartUpdated')] public function loadCart(): void { $cart = resolve(CartSessionManager::class)->current(); if (! $cart) { $this->items = collect(); $this->subtotal = 0; return; } $cart->load('lines.purchasable'); $cart->lines->loadMorph('purchasable', [ ProductVariant::class => ['product'], ]); $this->items = $cart->lines; $context = resolve(CartManager::class)->calculate($cart); $this->subtotal = $context->subtotal; } public function removeFromCart(int $lineId): void { resolve(CartManager::class)->remove(cartSession(), $lineId); $this->loadCart(); $this->dispatch('cartUpdated'); } public function render(): View { return view('livewire.shopping-cart'); } } ``` The corresponding Blade view displays each cart line with its product details and a remove button: ```blade
@if ($items->isEmpty())

Your cart is empty.

@else
    @foreach ($items as $line)
  • @if ($line->purchasable instanceof \App\Models\ProductVariant) {{ $line->purchasable->product->name }} - {{ $line->purchasable->name }} @else {{ $line->purchasable->name }} @endif

    Qty: {{ $line->quantity }} · {{ shopper_money_format($line->unit_price_amount, cartSession()->currency_code) }}

  • @endforeach

Subtotal: {{ shopper_money_format($subtotal, cartSession()->currency_code) }}

@endif
``` ### Cart Header Button [#cart-header-button] A small component that displays the cart item count in the navigation. It listens for the `cartUpdated` event to refresh automatically: ```php namespace App\Livewire; use Illuminate\Contracts\View\View; use Livewire\Attributes\On; use Livewire\Component; use Shopper\Cart\CartSessionManager; final class ShoppingCartButton extends Component { public int $count = 0; public function mount(): void { $this->updateCount(); } #[On('cartUpdated')] public function updateCount(): void { $cart = resolve(CartSessionManager::class)->current(); $this->count = $cart ? $cart->lines->sum('quantity') : 0; } public function render(): View { return view('livewire.shopping-cart-button'); } } ``` ### Displaying Cart Totals [#displaying-cart-totals] Use the `CartManager::calculate()` method to get the full breakdown. The returned `CartPipelineContext` contains all computed values: ```php use Shopper\Cart\CartManager; $context = resolve(CartManager::class)->calculate($cart); ``` ```blade

Subtotal: {{ shopper_money_format($context->subtotal, $cart->currency_code) }}

@if ($context->discountTotal > 0)

Discount: -{{ shopper_money_format($context->discountTotal, $cart->currency_code) }}

@endif @if ($context->taxTotal > 0)

Tax: {{ shopper_money_format($context->taxTotal, $cart->currency_code) }}

@endif

Total: {{ shopper_money_format($context->total, $cart->currency_code) }}

``` ### Applying a Coupon [#applying-a-coupon] Apply a discount code to the cart, then validate it. `applyCoupon()` only checks that the code exists. The other rules run when `calculate()` runs the pipeline, which skips an invalid discount without an error, so run the [`DiscountValidator`](/2.x/cart#discount-validation) to tell the customer why a code does not apply: ```php use Shopper\Cart\CartManager; use Shopper\Cart\Discounts\DiscountValidator; use Shopper\Cart\Exceptions\InvalidDiscountException; use Shopper\Core\Models\Discount; $manager = resolve(CartManager::class); try { $manager->applyCoupon($cart, $couponCode); } catch (InvalidDiscountException $e) { return back()->with('error', $e->getMessage()); } $context = $manager->calculate($cart); $discount = Discount::query()->where('code', $couponCode)->firstOrFail(); $result = resolve(DiscountValidator::class)->validate($discount, $context); if (! $result->valid) { $manager->removeCoupon($cart); return back()->with('error', $result->failureReason); } ``` ### Setting Checkout Addresses [#setting-checkout-addresses] Add shipping and billing addresses to the cart before converting to an order: ```php use Shopper\Cart\CartManager; use Shopper\Core\Enum\AddressType; $manager = resolve(CartManager::class); $manager->addAddress($cart, AddressType::Shipping, [ 'first_name' => $request->first_name, 'last_name' => $request->last_name, 'address_1' => $request->address, 'city' => $request->city, 'postal_code' => $request->postal_code, 'country_id' => $request->country_id, ]); $manager->addAddress($cart, AddressType::Billing, $billingData); ``` ### Converting to Order [#converting-to-order] When the customer completes checkout, convert the cart into an order. The action runs inside a database transaction, calculates final totals, creates order records, and marks the cart as completed. If a discount limit is hit at commit time, catch `DiscountLimitReachedException` and surface a friendly message: ```php use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Exceptions\DiscountLimitReachedException; use Shopper\Cart\Facades\Cart; try { $order = resolve(CreateOrderFromCartAction::class)->execute(Cart::current()); } catch (DiscountLimitReachedException $e) { return back()->with('error', 'This discount can no longer be used.'); } Cart::forget(); ``` After converting the cart to an order, call `Cart::forget()` to clear the session. The cart is marked as completed and cannot be modified, but the session should be cleaned up so `Cart::current()` returns `null`. See the [Payments](/2.x/payments) page for processing the order payment. # Categories (/2.x/categories) Categories provide a hierarchical organization structure for your products. Shopper uses nested categories with parent-child relationships, allowing unlimited depth. You can model complex product taxonomies like Electronics > Computers > Laptops without artificial limits. ## Model [#model] The model used is `Shopper\Models\Category`, which extends `Shopper\Core\Models\Category`. It implements the `Shopper\Core\Models\Contracts\Category` contract and `Spatie\MediaLibrary\HasMedia` for media support. The core model provides the business logic (relationships, scopes, slug handling, hierarchical structure via [laravel-adjacency-list](https://github.com/staudenmeir/laravel-adjacency-list)) and declares its two media collections in `getMediaCollections()`. The admin model registers those collections with Spatie MediaLibrary and adds the image conversions through the `HasMedia` and `RegistersMediaCollections` traits. This separation means the core model has no dependency on Spatie MediaLibrary. Media support is added at the admin layer. ### Extending the Model [#extending-the-model] To add custom behavior, extend the admin model and update your configuration: ```php namespace App\Models; use Shopper\Models\Category as ShopperCategory; class Category extends ShopperCategory { } ``` Update `config/shopper/models.php`: ```php return [ 'category' => \App\Models\Category::class, ]; ``` ## Database Schema [#database-schema] Categories are stored in the `sh_categories` table (`sh_` is the default [table prefix](/2.x/configuration#database-table-prefix)). | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Category name | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `description` | longtext | yes | null | Category description | | `position` | smallint (unsigned) | no | 0 | Display order among siblings (set by the admin reorder panel) | | `is_enabled` | boolean | no | false | Category visibility status | | `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 | | `parent_id` | bigint (unsigned) | yes | null | Foreign key to the parent category. Set to `null` when the parent is deleted, so its children become root categories | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The `HasSlug` trait runs any slug you set through `Str::slug()` and appends `-1`, `-2`, etc. if the slug is already taken. It does not build the slug from the `name`. The admin category form fills the slug from the name for you, and the `CategoryObserver` sets it for subcategories (see [Custom Paths & Slug Behavior](#custom-paths--slug-behavior)). When you create a root category in code, pass a `slug` yourself, otherwise the column stays `null`. ## Hierarchical Structure [#hierarchical-structure] Categories support unlimited nesting levels, so you can organize products into deeply nested taxonomies: ``` Electronics (parent_id: null) ├── Computers (parent_id: 1) │ ├── Laptops (parent_id: 2) │ └── Desktops (parent_id: 2) ├── Phones (parent_id: 1) │ ├── Smartphones (parent_id: 5) │ └── Accessories (parent_id: 5) └── Audio (parent_id: 1) ``` ## Media [#media] Categories support two media collections through [Spatie MediaLibrary](https://spatie.be/docs/laravel-medialibrary), using the same config-driven collection names as [products](/2.x/products#media). | Collection | Config key | Behavior | Description | |------------|-----------|----------|-------------| | Default gallery | `shopper.media.storage.collection_name` | Multiple files | Category images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | Single file | Primary image for listings and navigation | Both collections accept the MIME types listed in `shopper.media.accepts_mime_types`: JPEG, PNG, WebP and AVIF by default (configurable in `config/shopper/media.php`). The admin category form uploads a single image to the thumbnail collection, limited to `shopper.media.max_size.thumbnail` kilobytes (1024 by default). The admin does not upload to the default gallery collection: fill it from your own code. The collection names are defined in `config/shopper/media.php` under the `storage` key (`uploads` and `thumbnail` by default). The `getFirstMediaUrl` method returns the URL for the first media in a collection. If no media has been uploaded, a fallback URL is returned instead. You can also request a specific conversion size like `medium` (500x500) or `large` (800x800), defined under `shopper.media.conversions`. To display a category's thumbnail on your storefront: ```php use Shopper\Models\Category; $category = Category::query()->find($id); $collection = config('shopper.media.storage.thumbnail_collection'); $thumbnailUrl = $category->getFirstMediaUrl($collection); $mediumUrl = $category->getFirstMediaUrl($collection, 'medium'); ``` To add a thumbnail to a category programmatically: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $category->addMedia($pathToImage) ->toMediaCollection($collection); ``` ## Relationships [#relationships] ### Parent Category [#parent-category] Every category can optionally belong to a parent category. Use this to build breadcrumbs or display the parent context. Ancestors carry a negative `depth` (`-1` for the parent, `-2` for the grandparent), so ordering by `depth` lists the root category first: ```php $category->parent; if ($category->parent) { $breadcrumb = $category->ancestors()->orderBy('depth')->get(); } ``` ### Child Categories [#child-categories] Using the `laravel-adjacency-list` package, categories expose a full set of hierarchical relationships: The `children` relationship returns direct children only. Use `descendants` for all recursive children (children of children, etc.) and `ancestors` for all recursive parents up to the root. ```php $category->children; $category->descendants; $category->ancestors; $category->descendantsAndSelf; ``` ### Descendant Categories [#descendant-categories] To work with every category below a given one, at any depth, use the `descendants` relationship. It is an Eloquent relation like `children`: you can eager load it, count it, or add constraints before running the query. Use `descendantsAndSelf` to include the category itself. ```php $total = $category->descendants()->count(); $enabledDescendants = $category->descendants()->enabled()->get(); $categories = Category::query() ->whereNull('parent_id') ->with('descendants') ->get(); ``` ### Products [#products] Categories have a polymorphic many-to-many relationship with products through the `product_has_relations` table: ```php $category->products; $category->products()->count(); $category->products()->publish()->get(); ``` ## Available Tree Methods [#available-tree-methods] The `laravel-adjacency-list` package provides these methods for traversing the hierarchy: | Method | Description | |--------|-------------| | `ancestors()` | The model's recursive parents | | `ancestorsAndSelf()` | The model's recursive parents and itself | | `bloodline()` | The model's ancestors, descendants and itself | | `children()` | The model's direct children | | `childrenAndSelf()` | The model's direct children and itself | | `descendants()` | The model's recursive children | | `descendantsAndSelf()` | The model's recursive children and itself | | `parent()` | The model's direct parent | | `parentAndSelf()` | The model's direct parent and itself | | `rootAncestor()` | The model's topmost parent | | `siblings()` | The parent's other children | | `siblingsAndSelf()` | All the parent's children | ```php $ancestors = Category::query()->find($id)->ancestors; $categories = Category::with('descendants')->get(); $total = Category::query()->find($id)->descendants()->count(); Category::query()->find($id)->descendants()->update(['is_enabled' => false]); ``` ## Query Scopes [#query-scopes] ### Enabled Categories [#enabled-categories] Filter categories that are visible to customers: ```php Category::query()->enabled()->get(); ``` ### Root Categories [#root-categories] Get only top-level categories (those without a parent): ```php Category::query()->whereNull('parent_id')->get(); ``` Using the tree structure to get the full hierarchy: ```php Category::tree()->get(); ``` ## Custom Paths & Slug Behavior [#custom-paths--slug-behavior] The model declares a `slug_path` custom path for nested URLs. The `laravel-adjacency-list` package fills it on categories loaded through a recursive query (`tree()`, `descendants`, `ancestors` and the other tree relations) by joining the slugs with `/`, starting at the first level of that query. A category loaded with `find()` or `findBySlug()` has no `slug_path`. With `Category::tree()`, the path starts at the root. For a category "Laptops" under "Computers" under "Electronics", `slug_path` is `electronics/electronics-computers/electronics-computers-laptops`, because each subcategory slug already starts with its parent's slug (see the note below): ```php public function getCustomPaths(): array { return [ [ 'name' => 'slug_path', 'column' => 'slug', 'separator' => '/', ], ]; } ``` When a category has a parent, the `CategoryObserver` sets its slug to the parent's slug followed by the category name, on creation and on every update made through the model. For example, creating a "Laptops" category under a parent with slug `electronics-computers` produces the slug `electronics-computers-laptops`, and a slug you pass for a subcategory is replaced. This keeps same-named subcategories under different parents apart (`electronics-phones-accessories`, `electronics-audio-accessories`). If a slug is still taken, the `HasSlug` trait appends `-1`, `-2`, etc. ## Methods & Helpers [#methods--helpers] ### Find by Slug [#find-by-slug] The `findBySlug` static method looks up a category by its slug and throws a `ModelNotFoundException` if not found. It does not check `is_enabled`: ```php use Shopper\Models\Category; $category = Category::findBySlug('electronics'); ``` ### Label with Path [#label-with-path] The `getLabelOptionName()` method returns the full hierarchical path as a formatted string, useful for select dropdowns and admin interfaces: For a category "Laptops" nested under "Computers" under "Electronics", the method returns `Electronics / Computers / Laptops`. It walks up the `parent` relation, which runs one query per level unless the parents are already loaded. ```php $category->getLabelOptionName(); ``` ### Status Management [#status-management] Toggle a category's visibility with `updateStatus()`: Pass `true` (the default) to enable a category or `false` to disable it. ```php $category->updateStatus(true); $category->updateStatus(false); ``` ## Creating Categories [#creating-categories] Create a root category by omitting the `parent_id`. Pass the `slug` yourself, because the model does not build it from the name: ```php $electronics = Category::query()->create([ 'name' => 'Electronics', 'slug' => 'electronics', 'is_enabled' => true, 'position' => 1, ]); ``` Create a subcategory by setting `parent_id`. The `CategoryObserver` sets its slug from the parent's slug and the name, `electronics-computers` here: ```php $computers = Category::query()->create([ 'name' => 'Computers', 'parent_id' => $electronics->id, 'is_enabled' => true, ]); ``` ## Retrieving Categories [#retrieving-categories] Root categories with their children: ```php $categories = Category::query() ->whereNull('parent_id') ->enabled() ->with('children') ->orderBy('position') ->get(); ``` Full category tree: ```php $tree = Category::query() ->enabled() ->tree() ->get() ->toTree(); ``` A category with all its descendants: ```php $category = Category::query() ->where('slug', 'electronics') ->with('descendants') ->first(); $breadcrumb = $category->ancestors()->orderBy('depth')->get(); ``` For navigation menus with nested enabled children: ```php $navCategories = Category::query() ->whereNull('parent_id') ->enabled() ->with(['children' => fn ($q) => $q->enabled()]) ->orderBy('position') ->get(); ``` ## Working with Products [#working-with-products] Products in this category only: ```php $category = Category::query()->find($id); $products = $category->products; ``` Products in category and all descendants: ```php $categoryIds = $category->descendants->pluck('id')->push($category->id); $products = Product::query() ->publish() ->whereHas('categories', fn ($q) => $q->whereIn('id', $categoryIds)) ->get(); ``` ## Metadata [#metadata] The `metadata` JSON column lets you store arbitrary key-value data on a category without modifying the schema. This is useful for storing custom attributes like banner colors, display preferences, or integration identifiers: ```php $category = Category::query()->create([ 'name' => 'Summer Sale', 'slug' => 'summer-sale', 'is_enabled' => true, 'metadata' => [ 'banner_color' => '#FF6B35', 'featured_on_homepage' => true, 'external_id' => 'cat_abc123', ], ]); $color = $category->metadata['banner_color']; ``` ## Disabling Category Feature [#disabling-category-feature] If your store doesn't use categories, you can disable the feature entirely. This removes the category menu and pages from the admin panel, and the category field from the product forms: In your `config/shopper/features.php` file, set the category feature to disabled: ```php use Shopper\Enum\FeatureState; return [ 'category' => FeatureState::Disabled, ]; ``` ### Permissions [#permissions] The permissions seeder creates five permissions for category management: | Permission | Description | |------------|-------------| | `browse_categories` | View the categories list and the Categories menu entry | | `read_categories` | View a single category. Not checked by the admin category screens | | `add_categories` | Create new categories | | `edit_categories` | Edit existing categories, change their status and reorder them | | `delete_categories` | Delete categories | ## Components [#components] You can publish the Livewire components to customize the admin UI for categories: ```bash php artisan shopper:component:publish category ``` Creates `config/shopper/components/category.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'category-index' => Livewire\Pages\Category\Index::class, ], 'components' => [ 'slide-overs.category-form' => Livewire\SlideOvers\CategoryForm::class, 'slide-overs.re-order-categories' => Livewire\SlideOvers\ReOrderCategories::class, ], ]; ``` ## Storefront Example [#storefront-example] Here is a complete controller for displaying categories and their products on your storefront. The `show` method collects products from the category and all its descendants, so browsing "Electronics" also returns products from "Computers", "Laptops", etc. ```php namespace App\Http\Controllers; use Shopper\Models\Category; use Shopper\Models\Product; class CategoryController extends Controller { public function index() { $categories = Category::query() ->whereNull('parent_id') ->enabled() ->with(['children' => fn ($q) => $q->enabled()]) ->withCount('products') ->orderBy('position') ->get(); return view('categories.index', compact('categories')); } public function show(string $slug) { $category = Category::findBySlug($slug); abort_unless($category->is_enabled, 404); $category->load(['ancestors' => fn ($query) => $query->orderBy('depth')]); $categoryIds = $category->descendants ->pluck('id') ->push($category->id); $products = Product::query() ->publish() ->whereHas('categories', fn ($q) => $q->whereIn('id', $categoryIds)) ->paginate(12); return view('categories.show', compact('category', 'products')); } } ``` # Channels (/2.x/channels) Channels represent different sales platforms where your products can be sold. Examples include your main website, mobile app, marketplace integrations, or physical stores. ## Model [#model] The model used is `Shopper\Core\Models\Channel`. It implements `Shopper\Core\Models\Contracts\Channel` and uses the `HasSlug` trait: the `slug` you set is converted with `Str::slug()` and gets a `-1`, `-2` suffix when it is already taken. The slug is not generated from the name, so pass one when you create a channel. The model is configurable via `config/shopper/models.php`. ### Extending the Model [#extending-the-model] To add custom behavior, extend the model and update your configuration: ```php namespace App\Models; use Shopper\Core\Models\Channel as BaseChannel; class Channel extends BaseChannel { } ``` Update `config/shopper/models.php`: ```php return [ 'channel' => \App\Models\Channel::class, ]; ``` ## Database Schema [#database-schema] Channels are stored in the `sh_channels` table (`sh_` is the default [table prefix](/2.x/configuration#database-table-prefix)). | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Channel name | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `description` | text | yes | null | Channel description | | `timezone` | string | yes | null | Channel timezone, stored for your own code (Shopper does not read it) | | `url` | string | yes | null | Channel URL | | `is_default` | boolean | no | false | Default channel flag | | `is_enabled` | boolean | no | false | Whether the channel is active. Only enabled channels are listed in the admin product form | | `metadata` | jsonb | yes | null | Additional custom data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Relationships [#relationships] ### Products [#products] Channels have a many-to-many polymorphic relationship with products: ```php // Get all products for a channel $channel->products; // Collection of Product models // Add products to channel $channel->products()->attach([$productId1, $productId2]); // Remove products from channel $channel->products()->detach($productId); // Sync products $channel->products()->sync($productIds); ``` ### Orders and Carts [#orders-and-carts] Orders and carts store the channel they were placed on in a nullable `channel_id` column and expose a `channel()` relation. Deleting a channel sets this column to `null`. The `Channel` model has no inverse relation, so query orders by the column: ```php use Shopper\Core\Models\Order; $order->channel; // Channel model or null $mobileOrders = Order::query() ->where('channel_id', $mobileChannel->id) ->count(); ``` ## Query Scopes [#query-scopes] ```php use Shopper\Core\Models\Channel; // Get only the default channel Channel::query()->default()->first(); // Get only enabled channels Channel::query()->enabled()->get(); // Combine scopes Channel::query() ->enabled() ->where('timezone', 'UTC') ->get(); ``` ## Observer Behavior [#observer-behavior] The `Shopper\Core\Observers\ChannelObserver` ensures only one channel can be default: ```php // When creating/updating a channel with is_default = true: // 1. Any existing default channel is set to is_default = false // 2. The new/updated channel becomes the default $channel = Channel::query()->create([ 'name' => 'Mobile App', 'is_default' => true, // Previous default is automatically unset ]); ``` The previous default is updated with `updateQuietly()`, so no model events fire for it. The observer does not keep a default in place: setting `is_default` to `false` on the current default leaves the store without one. ## Default Channel [#default-channel] When you accept the database step of `php artisan shopper:install`, the `ChannelSeeder` creates one channel named Web Store, with the slug `web-store`, the `url` from `config('app.url')`, enabled and marked as default. You can retrieve the default channel using the `default` scope. It returns `null` when no channel is marked as default: ```php use Shopper\Core\Models\Channel; use Shopper\Models\Product; // Get the default channel $channel = Channel::query()->default()->first(); // Use in controllers public function index() { $channel = Channel::query()->default()->first(); $products = Product::query() ->forChannel($channel->id) ->publish() ->get(); } ``` ## Creating Channels [#creating-channels] The 2.x admin panel has no page to manage channels: create them in code, for example in a seeder. `is_enabled` defaults to `false`, so pass `'is_enabled' => true` for a channel you want to pick in the admin product form. ### Default Website Channel [#default-website-channel] Creating a channel with `'is_default' => true` removes the flag from the current default, such as the seeded Web Store channel. ```php use Shopper\Core\Models\Channel; $channel = Channel::query()->create([ 'name' => 'Website', 'slug' => 'website', 'description' => 'Main e-commerce website', 'url' => config('app.url'), 'timezone' => config('app.timezone'), 'is_default' => true, 'is_enabled' => true, ]); ``` ### Additional Channels [#additional-channels] ```php // Mobile app channel $mobileChannel = Channel::query()->create([ 'name' => 'Mobile App', 'slug' => 'mobile-app', 'description' => 'iOS and Android mobile application', 'timezone' => 'UTC', 'is_enabled' => true, ]); // Marketplace channel $marketplaceChannel = Channel::query()->create([ 'name' => 'Amazon', 'slug' => 'amazon', 'description' => 'Amazon marketplace integration', 'url' => 'https://amazon.com/store/your-store', 'is_enabled' => true, 'metadata' => [ 'marketplace_id' => 'ATVPDKIKX0DER', 'seller_id' => 'A1234567890', ], ]); ``` ## Retrieving Channels [#retrieving-channels] ```php use Shopper\Core\Models\Channel; // Get all enabled channels $channels = Channel::query()->enabled()->get(); // Get default channel $default = Channel::query()->default()->first(); // Get channel by slug $channel = Channel::query() ->where('slug', 'website') ->first(); // Get channel by slug, throws ModelNotFoundException when none matches $channel = Channel::findBySlug('website'); // Get channel with products $channel = Channel::query() ->with('products') ->where('slug', 'mobile-app') ->first(); // Get channels with product counts $channels = Channel::query() ->enabled() ->withCount('products') ->get(); ``` ## Assigning Products to Channels [#assigning-products-to-channels] ```php use Shopper\Models\Product; $product = Product::query()->find($id); // Assign to channels (via product) $product->channels()->attach([$channelId1, $channelId2]); // Get products for a specific channel $products = Product::query() ->forChannel($channelId) ->publish() ->get(); // Get products assigned to at least one of these channels $products = Product::query() ->forChannel([$channelId1, $channelId2]) ->publish() ->get(); ``` ## Storefront Example [#storefront-example] ```php namespace App\Http\Controllers; use Shopper\Core\Models\Channel; use Shopper\Models\Product; class ProductController extends Controller { public function index() { // Get products for default channel $channel = Channel::query()->default()->first(); $products = Product::query() ->forChannel($channel->id) ->publish() ->with(['brand', 'categories']) ->paginate(12); return view('products.index', compact('products')); } } ``` ### Multi-Channel API [#multi-channel-api] ```php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Shopper\Core\Models\Channel; use Shopper\Models\Product; class ProductController extends Controller { public function index(Request $request) { $channelSlug = $request->header('X-Channel', 'website'); $channel = Channel::query() ->where('slug', $channelSlug) ->enabled() ->firstOrFail(); $products = Product::query() ->forChannel($channel->id) ->publish() ->paginate(20); return response()->json($products); } } ``` ## Use Cases [#use-cases] | Channel | Example Use | |---------|------------| | Website | Main e-commerce storefront | | Mobile App | iOS/Android application | | Marketplace | Amazon, eBay, Etsy integration | | POS | Physical store point of sale | | Wholesale | B2B customer portal | | Social | Facebook/Instagram shop | ## Best Practices [#best-practices] 1. **Default Channel**: Always have one default channel for fallback 2. **Product Assignment**: Assign products to relevant channels during creation 3. **Timezone**: Shopper stores `timezone` but does not read it: use it in your own code (for example to show order dates in the channel's timezone) 4. **Metadata**: Use metadata for channel-specific configuration (marketplace or seller IDs). Keep secrets such as API keys in `.env`, not in a database column ```php // Example: Channel-specific settings $channel = Channel::query()->find($id); $marketplaceId = $channel->metadata['marketplace_id'] ?? null; $sellerId = $channel->metadata['seller_id'] ?? null; ``` # Collections (/2.x/collections) Collections are curated groups of products for marketing and merchandising. Unlike categories, collections can be manually curated or automatically populated based on rules. ## Model [#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 [#extending-the-model] To add custom behavior, extend the admin model and update your configuration: ```php namespace App\Models; use Shopper\Models\Collection as ShopperCollection; class Collection extends ShopperCollection { } ``` Update `config/shopper/models.php`: ```php return [ 'collection' => \App\Models\Collection::class, ]; ``` ## Database Schema [#database-schema] ### Collection Table [#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 [#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 [#collection-types] ```php use Shopper\Core\Enum\CollectionType; CollectionType::Manual // Products are manually selected CollectionType::Auto // Products are added based on rules ``` ### Type Checking [#type-checking] ```php $collection->isManual(); // true for manual collections $collection->isAutomatic(); // true for automatic collections ``` ## Relationships [#relationships] ### Products [#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](#collection-rules)) and `products` holds the last synced matches. ```php $collection->products; ``` For manual collections, manage products with the standard Eloquent relationship methods: ```php $collection->products()->attach([$productId1, $productId2]); $collection->products()->detach($productId); $collection->products()->sync($productIds); ``` ### Zones [#zones] Collections can be scoped to specific geographic zones. This is useful when a promotion or product group only applies to certain markets. ```php $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: ```php use Shopper\Core\Models\Zone; $zone = Zone::query()->find($id); $zone->collections; ``` ### Rules (Automatic Collections) [#rules-automatic-collections] Automatic collections use rules to determine which products belong to them. Each rule defines a condition that products must match. ```php $collection->rules; ``` Add a rule that matches products whose title contains "summer": ```php use Shopper\Core\Enum\Operator; use Shopper\Core\Enum\Rule; $collection->rules()->create([ 'rule' => Rule::ProductTitle, 'operator' => Operator::Contains, 'value' => 'summer', ]); ``` ## Slug & Lookup [#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: ```php use Shopper\Models\Collection; $collection = Collection::findBySlug('summer-essentials'); ``` ## Query Scopes [#query-scopes] Filter collections by type: ```php Collection::query()->manual()->get(); Collection::query()->automatic()->get(); ``` The `published` scope filters collections that have a `published_at` date in the past or present: ```php Collection::query()->published()->get(); ``` ## Collection Rules [#collection-rules] ### Rule Types [#rule-types] ```php 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](/2.x/pricing#zero-decimal-currencies), 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 [#operators] ```php 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_contains ``` Each 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`. ```php use Shopper\Core\Enum\Rule; $operators = Rule::ProductPrice->allowedOperators(); ``` ### Match Conditions [#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`. ```php $collection->match_conditions = 'all'; $collection->match_conditions = 'any'; ``` ## Display Helpers [#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: ```php $collection->firstRule(); ``` ## Creating Collections [#creating-collections] ### Manual Collection [#manual-collection] ```php 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-collection] Automatic collections populate themselves based on rules. Here's a "Sale Items" collection that matches products under $50 with "sale" in the title: ```php 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](#sync-action) after creating them. ### Best Sellers Collection [#best-sellers-collection] A collection that automatically includes products with more than 10 units sold in paid orders: ```php $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 [#top-rated-collection] A collection of products whose average approved rating is above 3: ```php $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 [#retrieving-collections] All published collections: ```php $collections = Collection::query()->published()->get(); ``` A collection with its products. `productsQuery()` only returns [published products](/2.x/products#published-products), so you do not filter them again: ```php $collection = Collection::findBySlug('summer-essentials'); $products = $collection->productsQuery()->get(); ``` Filter by type: ```php $manualCollections = Collection::query()->manual()->get(); $autoCollections = Collection::query() ->automatic() ->with('rules') ->get(); ``` ## Retrieving Products [#retrieving-products] Shopper provides built-in methods to retrieve products from collections, handling both manual and automatic collections transparently. ### Basic Usage [#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. ```php $collection = Collection::query()->find($id); $products = $collection->getProducts(); ``` For pagination or additional filtering, use `productsQuery()` which returns an Eloquent builder: ```php $products = $collection->productsQuery()->paginate(12); $products = $collection->productsQuery() ->where('featured', true) ->orderBy('name') ->get(); ``` ### How It Works [#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_conditions` is `all`, all rules must be satisfied (AND logic) - **Match Any**: any other value, at least one rule must be satisfied (OR logic) ```php $collection = Collection::query() ->where('slug', 'sale-items') ->with('rules') ->first(); $products = $collection->getProducts(); ``` ### Rule Evaluation [#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. ```php use Shopper\Core\Queries\CollectionProductsQuery; $query = new CollectionProductsQuery(); $products = $query->get($collection); ``` For further customization, use the query builder: ```php $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: ```php $isMatching = $query->matches($collection, $product); ``` ## Automatic Synchronization [#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 [#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](#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 [#manual-sync-command] You can manually sync automatic collections using the artisan command: ```bash # Sync all automatic collections php artisan shopper:collections:sync # Sync a specific collection php artisan shopper:collections:sync --collection=1 ``` To keep automatic collections current, schedule the command in `routes/console.php`: ```php use Illuminate\Support\Facades\Schedule; Schedule::command('shopper:collections:sync')->hourly(); ``` ### Sync Action [#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`: ```php use Shopper\Core\Actions\SyncCollectionProductsAction; use Shopper\Models\Collection; $collection = Collection::query()->find($id); $action = new SyncCollectionProductsAction(); $syncedCount = $action->execute($collection); ``` ### Background Jobs [#background-jobs] Sync operations run in queued jobs to avoid blocking requests: - `Shopper\Core\Jobs\SyncCollectionProductsJob` - Syncs a single collection - `Shopper\Core\Jobs\SyncProductWithCollectionsJob` - Syncs a product with all automatic collections You can dispatch them yourself: ```php use Shopper\Core\Jobs\SyncCollectionProductsJob; SyncCollectionProductsJob::dispatch($collection); ``` Configure your queue worker to process these jobs: ```bash php artisan queue:work ``` ## Media [#media] Collections support two media collections through [Spatie MediaLibrary](https://spatie.be/docs/laravel-medialibrary), using the same config-driven collection names as [products](/2.x/products#media). | 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: ```php $mediaCollection = config('shopper.media.storage.thumbnail_collection'); $collection->addMedia($file)->toMediaCollection($mediaCollection); ``` To retrieve the cover URL: ```php $mediaCollection = config('shopper.media.storage.thumbnail_collection'); $url = $collection->getFirstMediaUrl($mediaCollection, 'medium'); ``` ## Configuration [#configuration] ### Disabling Collections [#disabling-collections] ```php // 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 [#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 [#components] To customize the admin UI for collection management: ```bash php artisan shopper:component:publish collection ``` Creates `config/shopper/components/collection.php`: ```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 [#storefront-example] ```php 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 [#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 | # Configuration (/2.x/configuration) Shopper publishes its configuration files to `config/shopper/` during installation. These files control the admin panel behavior, model resolution, feature flags, media handling, and more. Component configuration files are published separately on demand. ## Configuration Files [#configuration-files] The following files are published by `php artisan shopper:install`: | File | Package | Purpose | |------|---------|---------| | `addons.php` | admin | Disables an installed add-on by its ID | | `admin.php` | admin | Admin panel prefix, domain, roles, branding, locales | | `auth.php` | admin | Authentication guard, 2FA toggle, password reset | | `core.php` | core | Database table prefix, barcode type | | `features.php` | admin | Feature flags for each admin module | | `media.php` | admin | Media storage, MIME types, max sizes, image conversions | | `models.php` | admin | Model class resolution for every Shopper entity | | `orders.php` | core | Order number generator format | | `routes.php` | admin | Additional middleware and custom route files | | `settings.php` | admin | Settings page registry | The installer also publishes `cart.php`, `payment.php` and `shipping.php`, because `shopper/cart`, `shopper/payment` and `shopper/shipping` are installed with the admin panel. The Stripe driver publishes its own file on demand with `php artisan vendor:publish --tag=shopper-stripe-config`. ## Admin Panel [#admin-panel] By default, the admin panel is accessible at `/cpanel`. You can change this prefix in `config/shopper/admin.php` or by adding the `SHOPPER_PREFIX` variable to your `.env` file: ```php title="config/shopper/admin.php" 'prefix' => env('SHOPPER_PREFIX', 'cpanel'), ``` If you change the prefix, run `php artisan shopper:link` to recreate the asset symlink with the new name. To bind the admin panel to a specific domain, set the `SHOPPER_DOMAIN` environment variable. This uses Laravel's `Route::domain()` under the hood: ```php title="config/shopper/admin.php" 'domain' => env('SHOPPER_DOMAIN'), ``` You can also customize the admin panel branding (logo, favicon, and Filament primary color): ```php title="config/shopper/admin.php" 'brand' => null, 'favicon' => null, 'primary_color' => \Filament\Support\Colors\Color::Blue, ``` `brand` and `favicon` take a path from your `public` directory, such as `'/images/logo.svg'`. When `brand` is `null`, the Shopper logo is shown. To render the logo from your own HTML or Blade view instead, see [Branding Logo](/2.x/extending/control-panel#branding-logo). The `primary_color` key accepts any [Filament color](https://filamentphp.com/docs/support/colors) constant. Shopper's styles, including a custom theme built from its `theme.css`, read their `primary` colors from this value, so you change it here and nowhere else. The `roles` key in the same file names the admin, manager and user roles. It is covered on the [ACL](/2.x/acl#configuration) page. ### Avatar Colors [#avatar-colors] Default colors for auto-generated user avatars (UI Avatars). Values are hexadecimal without the `#` prefix: ```php title="config/shopper/admin.php" 'avatar' => [ 'color' => '1d4ed8', 'bg_color' => 'dbeafe', ], ``` ### Locales [#locales] Available languages in the admin panel. Each entry maps a locale code to a display label and a flag code (ISO 3166-1 alpha-2, lowercase) used for the flag SVG: ```php title="config/shopper/admin.php" 'locales' => [ 'en' => ['label' => 'English', 'flag' => 'gb'], 'fr' => ['label' => 'Français', 'flag' => 'fr'], ], ``` ### Custom Pages [#custom-pages] The `php artisan make:shopper-page` command creates a Livewire page for the admin panel: a class that extends `Shopper\Livewire\Pages\AbstractPageComponent`, which renders it inside the admin panel layout, and its Blade view. These keys set where it writes them: ```php title="config/shopper/admin.php" 'pages' => [ 'namespace' => 'App\\Livewire\\Shopper', 'view_path' => resource_path('views/livewire/shopper'), ], ``` The command does not register a route: add one in your [custom route file](/2.x/configuration#custom-routes). ### Icon Picker Cache [#icon-picker-cache] The icon picker on the attribute form caches its list of icons. Turn the cache off with `cache`, or change how long it lasts with `duration`, which takes any interval Carbon understands: ```php title="config/shopper/admin.php" 'icon-picker' => [ 'cache' => true, 'duration' => '7 days', ], ``` ## Database Table Prefix [#database-table-prefix] All Shopper tables are prefixed with `sh_` by default so they do not conflict with your application's existing tables. ```php title="config/shopper/core.php" 'table_prefix' => 'sh_', ``` The prefix applies to the tables Shopper creates. The columns Shopper adds to your `users` table and the roles and permissions tables of spatie/laravel-permission, named in `config/permission.php`, keep their own names. Set the table prefix before the Shopper migrations run. Changing it afterwards requires a custom migration that renames every Shopper table. The file only exists once the installer has published it, so change the prefix in this order: 1. Run `php artisan shopper:install` and answer no when it asks to run the migrations and seeders. 2. Change `table_prefix` in `config/shopper/core.php`. 3. Run the migrations and the two seeders the installer would have run: ```bash php artisan migrate php artisan db:seed --class="Shopper\Core\Database\Seeders\ShopperSeeder" php artisan db:seed --class="Shopper\Database\Seeders\AuthTableSeeder" ``` ## Feature Flags [#feature-flags] The `features.php` config controls which sections of the admin panel are active. Set a feature to `FeatureState::Disabled` to remove its pages and sidebar link from the admin panel, along with its field on the product form for brands, categories, collections, suppliers and tags. Suppliers are disabled by default: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'attribute' => FeatureState::Enabled, 'brand' => FeatureState::Enabled, 'category' => FeatureState::Enabled, 'collection' => FeatureState::Enabled, 'discount' => FeatureState::Enabled, 'review' => FeatureState::Enabled, 'supplier' => FeatureState::Disabled, 'tag' => FeatureState::Enabled, ]; ``` For example, if your store does not use product reviews, set `'review' => FeatureState::Disabled` and the reviews page and its sidebar link disappear from the admin panel. To check a flag in your own code, such as a storefront view, call `Shopper\Feature::enabled()` with the feature key: ```blade @if (\Shopper\Feature::enabled('review')) @endif ``` ## Models [#models] Shopper resolves model classes through `config/shopper/models.php`. To use your own model for any entity, replace the class in this file. The entire system (admin panel, relationships, route bindings) uses the configured class automatically. Models that have media support (images, thumbnails) use the `Shopper\Models` namespace from the admin package. Models without media use the `Shopper\Core\Models` namespace from the core package. When swapping a model, extend the class listed in the config comment for that entry. ```php title="config/shopper/models.php" use Shopper\Models; return [ 'address' => Shopper\Core\Models\Address::class, 'brand' => Models\Brand::class, 'category' => Models\Category::class, 'collection' => Models\Collection::class, 'product' => Models\Product::class, 'variant' => Models\ProductVariant::class, 'channel' => Shopper\Core\Models\Channel::class, 'inventory' => Shopper\Core\Models\Inventory::class, 'order' => Shopper\Core\Models\Order::class, 'supplier' => Shopper\Core\Models\Supplier::class, 'tax_zone' => Shopper\Core\Models\TaxZone::class, 'tax_rate' => Shopper\Core\Models\TaxRate::class, ]; ``` See the [Introduction](/2.x/getting-started) page for more details on model swapping and extensibility. ## Authentication [#authentication] The `auth.php` config controls the authentication guard, two-factor authentication, and password reset flow for the admin panel: ```php title="config/shopper/auth.php" return [ 'guard' => 'web', '2fa_enabled' => env('SHOPPER_ENABLED_TWO_FACTOR', false), 'password_reset' => true, ]; ``` `guard` is the name of a guard defined in your `config/auth.php`. The admin panel logs users in and checks them with this guard. Set `SHOPPER_ENABLED_TWO_FACTOR=true` in your `.env` file to make two-factor authentication available to admin users. Your user model must also implement `Shopper\Contracts\HasStoreAuthentication` and `Shopper\Contracts\HasStoreAuthenticationRecovery`, with the traits listed in [Interfaces and Traits](/2.x/two-factor#interfaces-and-traits). Each user then turns it on from their profile; it is not forced on anyone. See the [Two-Factor Authentication](/2.x/two-factor) page for setup details. ## Middleware [#middleware] Shopper lets you add extra middleware to the admin routes that require a logged-in user: the admin pages, the routes of your custom route file and the routes of add-ons. The login and password reset pages, `/cpanel/initialize` and `/cpanel/forbidden` do not get them. This is useful for logging, rate limiting, or custom access control: ```php title="config/shopper/routes.php" 'middleware' => [], ``` The admin pages are Livewire components. On the requests a component sends after the page has loaded, Livewire only runs the middleware in its persistent list. If your middleware restricts access, also register it with `Livewire::addPersistentMiddleware()` in the `boot()` method of a service provider. ## Custom Routes [#custom-routes] By default, your `web.php` routes are not loaded inside the admin panel, and `custom_file` is `null`. To add custom routes that share Shopper's authentication middleware, point it to a dedicated route file: ```php title="config/shopper/routes.php" 'custom_file' => base_path('routes/shopper.php'), ``` Shopper loads this file inside its own route group: each route gets the admin panel prefix and domain, the `shopper.` name prefix and the admin panel's middleware, including the `middleware` key above. The route below answers at `/cpanel/settings/loyalty` and its name is `shopper.settings.loyalty`: ```php title="routes/shopper.php" use App\Livewire\Shopper\LoyaltySettings; use Illuminate\Support\Facades\Route; Route::get('settings/loyalty', LoyaltySettings::class)->name('settings.loyalty'); ``` ## Components [#components] Shopper's admin UI is built from Livewire components that you can override individually. Each feature has a component configuration file listing its pages and components. To publish a feature's component config, run the publish command with the feature name: ```bash php artisan shopper:component:publish category ``` This creates `config/shopper/components/category.php` where you can point any component to your own class. Available features: | Feature | Config file | |---------|------------| | `account` | `components/account.php` | | `brand` | `components/brand.php` | | `category` | `components/category.php` | | `collection` | `components/collection.php` | | `customer` | `components/customer.php` | | `dashboard` | `components/dashboard.php` | | `discount` | `components/discount.php` | | `order` | `components/order.php` | | `product` | `components/product.php` | | `review` | `components/review.php` | | `setting` | `components/setting.php` | To publish every component config at once, pass `--all`. Without an argument or `--all`, the command asks which feature to publish. Add `--force` to overwrite files you already published. ## Settings [#settings] Shopper uses a class-based approach for settings pages. Each setting is a class that implements the `Shopper\Contracts\SettingItem` interface. The `settings.php` config registers which settings are enabled: ```php title="config/shopper/settings.php" use Shopper\Settings\Items; return [ 'items' => [ Items\GeneralSetting::class => true, Items\StaffSetting::class => true, Items\LocationSetting::class => true, Items\PaymentSetting::class => true, Items\CarrierSetting::class => true, Items\LegalSetting::class => true, Items\ZoneSetting::class => true, Items\TaxSetting::class => true, Items\CurrencySetting::class => true, ], ]; ``` To hide a setting from the settings page and from the settings navigation, set its value to `false`. ### Creating a Custom Setting [#creating-a-custom-setting] To add your own card to the settings page, extend the `Shopper\Settings\Setting` base class. `name()`, `description()` and `icon()` are required. `url()`, `permission()` and `order()` are optional and default to `null`, `null` and `0`: ```php namespace App\Settings; use Shopper\Settings\Setting; final class LoyaltySetting extends Setting { public function name(): string { return 'Loyalty program'; } public function description(): string { return 'Set how many points customers earn on each order.'; } public function icon(): string { return 'heroicon-o-gift'; } public function url(): string { return route('shopper.settings.loyalty'); } public function order(): int { return 10; } public function permission(): ?string { return 'manage_loyalty'; } } ``` `url()` returns the address of your settings page, declared in your [custom route file](/2.x/configuration#custom-routes). A setting without a URL shows a "Soon" badge. `order()` sorts the cards; the built-in settings use 1 to 9. `permission()` shows the card only to users who have that permission, so create it first (see [Creating Custom Permissions](/2.x/acl#creating-custom-permissions)) and check it in your page component as well, for example with `$this->authorize('manage_loyalty')` in `mount()`. Then add it to the `items` array of `config/shopper/settings.php`, after the built-in settings: ```php title="config/shopper/settings.php" 'items' => [ App\Settings\LoyaltySetting::class => true, ], ``` ### Programmatic Registration [#programmatic-registration] You can also register settings at runtime through the `SettingManager`, for example in the `boot()` method of a service provider: ```php use Shopper\Settings\SettingManager; app(SettingManager::class)->add(App\Settings\LoyaltySetting::class); ``` `add()` takes an optional second argument, `false` to register the setting disabled. `enable()` and `disable()` switch a setting that is already registered, including the built-in ones: ```php use Shopper\Settings\Items\LegalSetting; use Shopper\Settings\SettingManager; app(SettingManager::class)->disable(LegalSetting::class); ``` Disabling a setting item removes its card and its navigation tab, so your team can no longer open it from the admin panel. Make sure your team does not need access to those settings before disabling them. ## Order Number Format [#order-number-format] The `orders.php` config controls how order numbers are generated. You can customize the prefix, separator, date format, and sequence padding: ```php title="config/shopper/orders.php" 'generator' => [ 'prefix' => 'ORD', 'separator' => '-', 'date_format' => 'Ymd', 'start_sequence_from' => 1, 'pad_length' => 6, 'pad_string' => '0', ], ``` The sequence is `start_sequence_from` plus the ID of the last order, padded on the left with `pad_string` up to `pad_length` characters. The parts are joined with `separator`, and a part set to `null` is left out. Shopper generates the number when it creates an order from a cart. If you create orders in your own code, call the `generate_number()` helper to fill the `number` column. Examples of generated numbers depending on configuration: | Configuration | Result | |---------------|--------| | Default | `ORD-20260328-000001` | | `'prefix' => null` | `20260328-000001` | | `'date_format' => null` | `ORD-000001` | | `'prefix' => null, 'date_format' => null` | `000001` | # Contribution Guide (/2.x/contributing) Contributions are accepted via Pull Requests on [GitHub](https://github.com/shopperlabs/shopper). ## Bug Reports [#bug-reports] To encourage active collaboration, Shopper strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test. ## Pull Requests [#pull-requests] - **Add tests** - A pull request that changes behaviour comes with tests that cover it. - **Document any change in behaviour** - Make sure the `readme.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - Shopper follows [SemVer v2.0.0](https://semver.org/): minor and patch releases never contain breaking changes. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. **Happy coding**! ## Security Vulnerabilities [#security-vulnerabilities] If you discover a security vulnerability within Shopper, report it privately through [GitHub](https://github.com/shopperlabs/shopper/security/advisories/new) or by email at [arthur@shopperlabs.co](mailto:arthur@shopperlabs.co). Do not open a public issue. All security vulnerabilities will be promptly addressed. ## Coding Style [#coding-style] Shopper follows the Laravel coding style, checked by [Laravel Pint](https://laravel.com/docs/pint) with the rules in `pint.json`, and the [PSR-4](https://www.php-fig.org/psr/psr-4/) autoloading standard. Run `composer lint` to format your changes before you push them. ## Code of Conduct [#code-of-conduct] As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of the level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. # Currencies (/2.x/currencies) Currencies define the monetary units used across your store. Each [zone](/2.x/zones) is associated with a currency, and each [price](/2.x/pricing) record is linked to a currency. Shopper supports multi-currency pricing out of the box, with over 150 currencies seeded during installation. ## Model [#model] The model used is `Shopper\Core\Models\Currency`. It implements `Shopper\Core\Models\Contracts\Currency`. The model has a global `enabled` scope that automatically filters out disabled currencies (see [Pricing](/2.x/pricing#currency-model) for details). ### Database Schema [#database-schema] Currencies are stored in the `currencies` table with the [table prefix](/2.x/configuration#database-table-prefix) set in `config('shopper.core.table_prefix')`, so `sh_currencies` by default. The table has no timestamps. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Currency name (e.g., "US Dollar") | | `code` | string(10) | no | - | ISO 4217 code (e.g., "USD"), unique | | `symbol` | string(25) | no | - | Currency symbol (e.g., "$") | | `format` | string(50) | no | - | Display format pattern (e.g., "$1,0.00"). `shopper_money_format()` does not read it | | `exchange_rate` | decimal(10,2) | yes | null | Exchange rate relative to the store's default currency. Stored for reference only: Shopper never converts prices with it | | `is_enabled` | boolean | no | true | Whether the currency is enabled | ## How Currencies are Created [#how-currencies-are-created] Currencies are defined in the `database/data/currencies.json` file of the `shopper/core` package. When you run `php artisan shopper:install` and answer yes to "Run database migrations and seeders?", the `Shopper\Core\Database\Seeders\CurrenciesTableSeeder` seeder reads this file and inserts its 158 currencies, all enabled. If you skipped that step, run the Shopper seeder yourself. It also seeds the countries, legal pages, default channel, carrier and payment method: ```bash php artisan db:seed --class="Shopper\Core\Database\Seeders\ShopperSeeder" ``` Shopper ships with over 150 currencies out of the box, so you rarely need to add more. If you do need a custom currency, such as the Sierra Leonean leone (`SLE`) that the file does not have, create a migration that inserts it through the `Currency` model, which writes to the prefixed table: ```php create([ 'name' => 'Sierra Leonean Leone', 'code' => 'SLE', 'symbol' => 'Le', 'format' => 'Le1,0.00', ]); } }; ``` ## How to Set Up Store Currencies [#how-setup-store-currencies] After installing Shopper, you need to [set up your store](/2.x/setup-store). During this step you choose the currencies you want for your store and the one used by default, which must be one of them. Once you've done this, you can change these currencies in the Store currency section of your general settings, `Settings > General`. Both steps only list enabled currencies. The `Settings > Currencies` page lists every currency in the table, disabled ones included. There you enable or disable currencies, one at a time with the status toggle or several at once with the bulk actions, and edit their exchange rate. Names, codes and symbols cannot be edited from this page. It requires the `access_setting` permission. Only disable currencies your store does not use. The `enabled` scope hides a disabled currency, so `$zone->currency` and `$price->currency` return `null`, the `currency_code` attribute of a zone or a price throws an error, and if it is the default currency, `shopper_currency()` returns `USD` once its one-hour cache expires. Do not delete a currency either: deleting it also deletes every zone and every price that uses it. ## Zero-Decimal Currencies [#zero-decimal-currencies] Some currencies have no subdivision (no "cents"). For example, the Japanese Yen (JPY) and the Central African CFA Franc (XAF) are stored as whole numbers, so 1000 JPY is stored as `1000`, not `100000`. Shopper handles this automatically. The `is_no_division_currency()` helper checks if a currency code (in uppercase) is zero-decimal, and `zero_decimal_currencies()` returns the full list: ```php is_no_division_currency('XAF'); // true is_no_division_currency('USD'); // false zero_decimal_currencies(); // ['BIF', 'CLP', 'DJF', 'GNF', 'HTG', 'JPY', 'KMF', 'KRW', // 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XAG', 'XAU', // 'XDR', 'XOF', 'XPF'] ``` The `shopper_money_format()` helper and the `MoneyInput` form component both use this to determine whether to divide/multiply by 100. See the [Pricing documentation](/2.x/pricing) for details. ## Relation to Other Entities [#relation-to-other-entities] [Carts](/2.x/cart) and [orders](/2.x/orders) do not reference a currency row: they store the ISO code in a `currency_code` column. A new cart uses `shopper_currency()` unless you pass a `currency_code`. ### Store [#store] A store has a default currency and can have many currencies. These currencies are then used in other relations: the admin only offers the store currencies when you associate a zone with a currency or set the prices of a product or a variant. These 2 values are stored through the `Shopper\Core\Models\Setting` model, in the rows whose `key` column is `default_currency_id` and `currencies`. The `shopper_setting('default_currency_id')` helper returns the ID of the default currency, and `shopper_setting('currencies')` returns an array with the IDs of the currencies set up for your store. The `shopper_currency()` helper returns the code of the default currency, or `USD` when none is set (see [Default Currency](/2.x/pricing#default-currency)): ```php use Shopper\Core\Models\Currency; $storeCurrencies = Currency::query() ->whereIn('id', shopper_setting('currencies') ?? []) ->get(); $defaultCurrencyCode = shopper_currency(); // "EUR" ``` ### Zone [#zone] Each Zone is associated with a currency. A currency can be used in more than one zone, but a zone can have only one currency. The relation is available on a Zone through the `currency` relation and will return a `Shopper\Core\Models\Currency` object. You can also access the currency code through the attribute `currency_code` on the zone. From the currency side, `$currency->zone` returns only one of its zones: see [Zone Relationship](/2.x/pricing#zone-relationship) to get all of them. ### Price [#price] The Price entity is used to represent a price associated with an entity, for example for products or variants. Each price is associated with a currency. The relation is available on a Price through the `currency` relation and will return a `Shopper\Core\Models\Currency` object. You can also access the currency code through the attribute `currency_code` on the price. # Customers (/2.x/customers) Customers are users who have the customer role (`user` by default, set in `shopper.admin.roles.user`) and can place orders in your store. Shopper extends your Laravel User model with e-commerce specific fields and relationships. ## User Model Integration [#user-model-integration] Shopper doesn't create a separate Customer model. Instead, it extends your existing `App\Models\User` model (the model set in `auth.providers.users.model`) with the `InteractsWithShopper` trait and `ShopperUser` contract. ```php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; class User extends Authenticatable implements ShopperUser { use InteractsWithShopper; use Notifiable; protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'gender', 'phone_number', 'birth_date', 'avatar_type', 'avatar_location', 'opt_in', 'email_verified_at', 'last_login_ip', ]; } ``` The admin customer form, the anonymize action and the admin profile page write users with Eloquent's `create()` and `update()`, and Laravel ignores every attribute that is not fillable. Declare the columns above as fillable. The Shopper migration renames the `name` column of the Laravel skeleton to `last_name`, so `name` leaves the list. Keep the skeleton's `Notifiable` trait: the admin uses it to email their credentials to a new customer. The `InteractsWithShopper` trait provides: - `HasRoles` (Spatie Permission) for role-based access control - `HasDiscounts` for customer-specific discount eligibility, through the `discounts()` relation - `HasProfilePhoto` for avatar management, through the `picture` attribute It also casts `birth_date`, `email_verified_at` and `last_login_at` to Carbon dates, `gender` to `GenderType` and `opt_in` to a boolean. ## Database Schema [#database-schema] ### User Table Modifications [#user-table-modifications] Shopper's migrations modify the standard Laravel `users` table: they rename `name` to `last_name`, make `password` nullable and add the other columns below. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `first_name` | string | yes | null | First name | | `last_name` | string | no | - | Last name (the `name` column of the Laravel skeleton, renamed) | | `email` | string | no | - | Email address (unique) | | `password` | string | yes | null | Password (nullable for social auth) | | `store_two_factor_secret` | text | yes | null | Encrypted two-factor secret, see [Two-Factor Authentication](/2.x/two-factor) | | `store_two_factor_recovery_codes` | text | yes | null | Encrypted two-factor recovery codes | | `email_verified_at` | timestamp | yes | null | Email verification date | | `gender` | string | yes | null | Gender enum value | | `phone_number` | string | yes | null | Phone number | | `birth_date` | date | yes | null | Birth date | | `avatar_type` | string | no | avatar_ui | `avatar_ui` (generated from the name) or `storage` (uploaded file) | | `avatar_location` | string | yes | null | Avatar file path | | `timezone` | string | yes | null | User timezone | | `opt_in` | boolean | no | false | Marketing email consent | | `last_login_at` | timestamp | yes | null | Last login timestamp | | `last_login_ip` | string | yes | null | Last login IP address | ### Address Table [#address-table] Addresses are stored in the `sh_user_addresses` table (`sh_` is the default [table prefix](/2.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `first_name` | string | no | - | First name | | `last_name` | string | no | - | Last name | | `company_name` | string | yes | null | Company name | | `street_address` | string | no | - | Street address | | `street_address_plus` | string | yes | null | Additional address line | | `postal_code` | string | no | - | Postal/ZIP code | | `city` | string | no | - | City | | `state` | string | yes | null | State/province/region | | `phone_number` | string | yes | null | Phone number | | `shipping_default` | boolean | no | false | Default shipping address | | `billing_default` | boolean | no | false | Default billing address | | `type` | string | yes | null | Address type enum | | `metadata` | jsonb | yes | null | Extra JSON data (the model has no cast for it: add an `array` cast in a custom Address model) | | `country_id` | bigint | yes | null | FK to countries (set to null when the country is deleted) | | `user_id` | bigint | no | - | FK to users (the address is deleted with the user) | ## Gender Type [#gender-type] The `GenderType` enum defines available gender options: ```php use Shopper\Core\Enum\GenderType; GenderType::Male // male GenderType::Female // female GenderType::Male->getLabel(); // "Male", translated ``` ## Address Type [#address-type] The `AddressType` enum defines address categories: ```php use Shopper\Core\Enum\AddressType; AddressType::Billing // billing AddressType::Shipping // shipping AddressType::Billing->getLabel(); // "Billing Address", translated ``` ## Relationships [#relationships] ### Orders [#orders] `orders()` returns the orders whose `customer_id` is the user's ID, using the model set in `shopper.models.order`. ```php // Get all customer orders $customer->orders; // Collection of Order models // Get recent orders $customer->orders() ->latest() ->take(5) ->get(); ``` ### Addresses [#addresses] ```php // Get all customer addresses $customer->addresses; // Collection of Address models // Get default shipping address $customer->addresses() ->where('shipping_default', true) ->first(); // Get default billing address $customer->addresses() ->where('billing_default', true) ->first(); ``` ## Query Scopes [#query-scopes] ```php use App\Models\User; // Get only customers (users with the shopper.admin.roles.user role) User::query()->customers()->get(); // Get administrators (shopper.admin.roles.admin or shopper.admin.roles.manager role) User::query()->administrators()->get(); ``` ## Role Checking [#role-checking] ```php // Check if user has the shopper.admin.roles.admin role $user->isAdmin(); // Check if user has the shopper.admin.roles.manager role $user->isManager(); // Check if user can open the admin panel: admin, manager, or the access_dashboard permission $user->canAccessDashboard(); // Check if email is verified $user->isVerified(); ``` ## Computed Attributes [#computed-attributes] ```php // Get full name (the last name alone when first_name is empty) $customer->full_name; // "John Doe" // Get the birth date text shown in the admin ("Not defined" when empty) $customer->birth_date_formatted; // Format the birth date yourself: it is cast to a Carbon instance $customer->birth_date?->isoFormat('LL'); // "January 15, 1990" // Get role display names as a comma-separated string ("N/A" without roles) $customer->roles_label; // "User, VIP" // Get profile picture URL $customer->picture; // Avatar URL (ui-avatars or uploaded) ``` ## Address Model [#address-model] The model used is `Shopper\Core\Models\Address`. It implements `Shopper\Core\Models\Contracts\Address` and is configurable via `config/shopper/models.php`. ### Extending the Address Model [#extending-the-address-model] ```php namespace App\Models; use Shopper\Core\Models\Address as BaseAddress; class Address extends BaseAddress { // Add your customizations here } ``` Your class must extend `Shopper\Core\Models\Address`: Shopper throws a `Shopper\Core\Exceptions\InvalidModelConfigurationException` otherwise. Set the `address` key in `config/shopper/models.php` and keep the other keys: ```php return [ 'address' => \App\Models\Address::class, ]; ``` ### Address Relationships [#address-relationships] Each address belongs to a user and optionally to a country: ```php $address->user; // The customer who owns this address $address->country; // The Country model (nullable) ``` ### Address Methods [#address-methods] The Address model provides helpers for checking default status: ```php $address->isShippingDefault(); // true if this is the default shipping address $address->isBillingDefault(); // true if this is the default billing address $address->full_name; // "John Doe" (computed from first_name + last_name) ``` ## Creating Customers [#creating-customers] ### Basic Customer [#basic-customer] ```php use App\Models\User; use Shopper\Core\Enum\GenderType; use Illuminate\Support\Facades\Hash; $customer = User::query()->create([ 'first_name' => 'John', 'last_name' => 'Doe', 'email' => 'john@example.com', 'password' => Hash::make('password'), 'gender' => GenderType::Male, 'email_verified_at' => now(), ]); // Assign customer role $customer->assignRole(config('shopper.admin.roles.user')); ``` These calls need the fillable columns listed in [User Model Integration](#user-model-integration). ### Customer with Address [#customer-with-address] ```php use App\Models\User; use Shopper\Core\Enum\AddressType; use Shopper\Core\Enum\GenderType; use Shopper\Core\Models\Country; $customer = User::query()->create([ 'first_name' => 'Jane', 'last_name' => 'Doe', 'email' => 'jane@example.com', 'gender' => GenderType::Female, 'phone_number' => '+1234567890', 'opt_in' => true, ]); $customer->assignRole(config('shopper.admin.roles.user')); // Add shipping address $customer->addresses()->create([ 'first_name' => 'Jane', 'last_name' => 'Doe', 'street_address' => '123 Main Street', 'city' => 'New York', 'state' => 'NY', 'postal_code' => '10001', 'country_id' => Country::query()->where('cca2', 'US')->value('id'), 'type' => AddressType::Shipping, 'shipping_default' => true, ]); ``` ## Retrieving Customers [#retrieving-customers] ```php use App\Models\User; // Get all customers $customers = User::query() ->customers() ->latest() ->get(); // Search customers $customers = User::query() ->customers() ->where(function ($query) use ($search) { $query->where('first_name', 'like', "%{$search}%") ->orWhere('last_name', 'like', "%{$search}%") ->orWhere('email', 'like', "%{$search}%"); }) ->get(); // Get customer with addresses and orders $customer = User::query() ->with(['addresses', 'orders']) ->findOrFail($id); // Get customers who opted in for marketing $marketingList = User::query() ->customers() ->where('opt_in', true) ->get(); // Get verified customers only $verified = User::query() ->customers() ->whereNotNull('email_verified_at') ->get(); ``` ## Managing Addresses [#managing-addresses] ```php use Shopper\Core\Enum\AddressType; use Shopper\Core\Models\Address; // Create address for customer $address = Address::query()->create([ 'user_id' => $customer->id, 'first_name' => 'John', 'last_name' => 'Doe', 'street_address' => '456 Oak Avenue', 'city' => 'Los Angeles', 'postal_code' => '90001', 'country_id' => $countryId, 'type' => AddressType::Billing, 'billing_default' => true, ]); // Make another address the default shipping address: // the observer removes the flag from the previous default $newDefault = Address::query()->find($addressId); $newDefault->update(['shipping_default' => true]); ``` ## Observer Behavior [#observer-behavior] When a user is deleted, the `InteractsWithShopper` trait automatically: - Detaches all roles - Deletes all addresses ```php // When deleting a user: $customer->delete(); // Roles are detached and addresses are deleted automatically ``` Orders are kept: the database sets their `customer_id` to null. `Shopper\Core\Observers\AddressObserver` runs when an address is created or updated. When the address has `shipping_default` set, the observer removes the flag from the customer's previous default shipping address, and it does the same for `billing_default`. The flags are exclusive per customer whatever the address `type`. ## Role Configuration [#role-configuration] Roles are defined in `config/shopper/admin.php`: ```php return [ 'roles' => [ 'admin' => 'administrator', 'manager' => 'manager', 'user' => 'user', ], ]; ``` The Shopper seeder creates the three roles with these names, so set them before you seed. ## Permissions [#permissions] The admin panel generates five permissions for customer management: | Permission | Description | |------------|-------------| | `browse_customers` | View the customers list | | `read_customers` | View a single customer profile | | `add_customers` | Create new customers | | `edit_customers` | Generated for your own screens: the 2.x customer page is read-only and does not check it | | `delete_customers` | Anonymize a customer (the admin has no delete action) | Anonymizing replaces the first and last names with "Deleted" and "Customer" (translated) and the email with an `@anonymized.local` address, clears the phone number, avatar, birth date and last login IP, turns `opt_in` off and deletes the customer's addresses. Orders are kept. ## Components [#components] To customize the admin UI for customer management: ```bash php artisan shopper:component:publish customer ``` Creates `config/shopper/components/customer.php`: ```php use Shopper\Livewire; use Shopper\Livewire\Components; return [ 'pages' => [ 'customer-index' => Livewire\Pages\Customers\Index::class, 'customer-create' => Livewire\Pages\Customers\Create::class, 'customer-show' => Livewire\Pages\Customers\Show::class, ], 'components' => [ 'customers.addresses' => Components\Customers\Addresses::class, 'customers.orders' => Components\Customers\Orders::class, 'customers.profile' => Components\Customers\Profile::class, ], ]; ``` ## Storefront Example [#storefront-example] ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Validation\Rule; use Shopper\Core\Enum\AddressType; use Shopper\Core\Models\Country; class AccountController extends Controller { public function show() { $customer = auth()->user(); return view('account.show', [ 'customer' => $customer, 'orders' => $customer->orders()->latest()->paginate(10), 'addresses' => $customer->addresses, ]); } public function updateProfile(Request $request) { $validated = $request->validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'phone_number' => 'nullable|string|max:20', 'birth_date' => 'nullable|date', 'opt_in' => 'boolean', ]); auth()->user()->update($validated); return back()->with('success', 'Profile updated successfully'); } public function storeAddress(Request $request) { $validated = $request->validate([ 'first_name' => 'required|string', 'last_name' => 'required|string', 'street_address' => 'required|string', 'city' => 'required|string', 'postal_code' => 'required|string', 'country_id' => ['required', Rule::exists(Country::class, 'id')], 'type' => 'required|in:billing,shipping', ]); auth()->user()->addresses()->create([ ...$validated, 'type' => AddressType::from($validated['type']), ]); return back()->with('success', 'Address added successfully'); } } ``` ## Use Cases [#use-cases] | Scope | Description | |-------|-------------| | `customers()` | Users with 'user' role | | `administrators()` | Users with 'admin' or 'manager' role | | Method | Description | |--------|-------------| | `isAdmin()` | Check if user has admin role | | `isManager()` | Check if user has manager role | | `canAccessDashboard()` | Check if user is an admin, a manager, or has the `access_dashboard` permission | | `isVerified()` | Check if email is verified | # Dashboard (/2.x/dashboard) The dashboard is the first screen after login. It shows store health at a glance: revenue trends, key metrics, recent orders and top products. Until the store is configured, an onboarding guide takes the place of these widgets. ## Components [#components] The dashboard is composed of five Livewire components, each with a focused responsibility. The four data widgets cache their data independently (see [Caching](#caching)). The revenue chart, the top selling products and the recent orders require the `browse_orders` permission: the dashboard does not render them for a user without it. ### RevenueChart [#revenuechart] Displays monthly revenue as a bar chart for the last 12 months, the current month included. Each bar is the sum of `price_amount` on paid orders in the selected currency, converted from cents for display (zero-decimal currencies such as XAF or JPY are shown as stored). Data is grouped by month in a single aggregated query and cached with flexible TTL (fresh for 5 minutes, stale up to 30 minutes). The component extends `ApexChartWidget` from the `leandrocfe/filament-apex-charts` package. The chart supports a currency filter. It starts on the store default currency, and a dropdown lists the currencies enabled in your store settings to switch between them. The Y-axis and tooltip are formatted using `Intl.NumberFormat` with the application locale, followed by the currency symbol. The revenue query supports MySQL, PostgreSQL, and SQLite with database-specific date expressions. ### StatCards [#statcards] Shows four summary cards comparing the current month to the previous month: | Card | Metric | Scope | |------|--------|-------| | Revenue | Sum of `price_amount` on paid orders created this month | Store default currency | | Products | Total product count, monthly new products for trend | All types | | Orders | Total count of paid orders, monthly count for trend | All currencies | | Customers | Total count of users with the customer role (the `customers` scope, role name from `config('shopper.admin.roles.user')`, `user` by default), monthly new customers for trend | All | Each card shows the percentage change versus the previous month, with a green or red trend indicator (gray at 0% when nothing changed, 100% when the previous month had nothing). Cards link to their respective admin sections. A card is shown only to users who can browse its section: `browse_orders` for Revenue and Orders, `browse_products` for Products, `browse_customers` for Customers. ### RecentOrders [#recentorders] A table of the 7 most recent orders, whatever their payment status, excluding orders with Cancelled or Archived status. Each row shows the order number, first product with thumbnail (plus the count of other items), total amount, order status badge, and links to the order detail page. ### TopSellingProducts [#topsellingproducts] Ranks the top 6 products by total quantity sold across all paid orders, with no date range. Variant sales are aggregated back to the parent product. Each row shows the product thumbnail, name, total units sold, and the average rating and count of its approved reviews. ### SetupGuide [#setupguide] An interactive checklist that guides new stores through the essential configuration steps. It takes the place of the dashboard widgets until it is completed or dismissed, and detects each step's completion by querying the database. A step is listed only for users who have its permission: | Step | Completed when | Permission | |------|---------------|------------| | Add your first product | At least one product exists | `add_products` | | Create a collection | At least one collection exists | `add_collections` | | Set up shipping zones | At least one enabled shipping zone exists | `access_setting` | | Set up payment methods | At least one enabled payment method exists | `access_setting` | | Configure taxes | At least one tax zone exists | `access_setting` | When all steps are complete, the guide saves a `setup_guide_done` setting and dispatches a `setup-guide-completed` event to hide itself. This check runs when the dashboard loads, for a user with the `access_setting` permission. The guide does not reappear on subsequent visits. A user with `access_setting` can also dismiss it early with the dismiss button. ## Caching [#caching] The four data widgets cache their data independently with Laravel's `Cache::flexible()`. During the fresh TTL the cached value is served as is. Between the fresh and the stale TTL, the cached value is still served and Laravel recomputes it after the response is sent. Past the stale TTL, the next request recomputes it. The setup guide is not cached. The cache keys and TTLs are: | Component | Cache key | Fresh TTL | Stale TTL | |-----------|-----------|-----------|-----------| | RevenueChart | `dashboard:revenue:{currency}` | 5 min | 30 min | | StatCards | `dashboard:stat-cards:{locale}` | 5 min | 30 min | | RecentOrders | `dashboard.orders:recent-ids` | 1 min | 5 min | | TopSellingProducts | `dashboard.products:top-selling` | 5 min | 30 min | RecentOrders caches only the order IDs: the orders themselves are loaded fresh on each render. To clear the dashboard cache manually (for example after a data import), flush the keys: ```php use Illuminate\Support\Facades\Cache; Cache::forget('dashboard:revenue:'.shopper_currency()); Cache::forget('dashboard:stat-cards:'.app()->getLocale()); Cache::forget('dashboard.orders:recent-ids'); Cache::forget('dashboard.products:top-selling'); ``` The revenue chart keeps one entry per currency shown in its filter, and the stat cards one entry per admin locale: forget the key of each currency and locale your team uses. ## Access Requirements [#access-requirements] The dashboard middleware (`Shopper\Http\Middleware\Dashboard`) checks two conditions before rendering the page. The user must have the administrator or manager role (role names from `config('shopper.admin.roles.admin')` and `config('shopper.admin.roles.manager')`), or the `access_dashboard` permission. The store must have the `email` and `street_address` settings configured (these are set during the initial store setup). The middleware runs on every authenticated page of the admin panel, not only the dashboard: your custom routes (`config('shopper.routes.custom_file')`) and add-on routes included. Only the initialization and forbidden pages skip it. If the user lacks permission, Shopper redirects to its forbidden page. If the settings are missing, it redirects to the store initialization page. ## Customizing the Dashboard [#customizing-the-dashboard] ### Replacing the Entire Page [#replacing-the-entire-page] The dashboard page is registered in the components configuration. Publish the dashboard component config to swap it with your own implementation: ```bash php artisan shopper:component:publish dashboard ``` This creates `config/shopper/components/dashboard.php`: ```php use Shopper\Livewire\Components; use Shopper\Livewire\Pages; return [ 'pages' => [ 'dashboard' => Pages\Dashboard::class, ], 'components' => [ 'locale-switcher' => Components\LocaleSwitcher::class, ], ]; ``` Replace the page class with your own component: ```php 'pages' => [ 'dashboard' => App\Livewire\Pages\Dashboard::class, ], ``` Your component only needs to render a view with the app layout. The simplest override: ```php namespace App\Livewire\Pages; use Illuminate\Contracts\View\View; use Livewire\Component; final class Dashboard extends Component { public function render(): View { return view('dashboard.index') ->layout('shopper::components.layouts.app', [ 'title' => 'Dashboard', ]); } } ``` You can also extend `Shopper\Livewire\Pages\AbstractPageComponent`, which already sets this layout, and only pass the title with `->title()`. ### Overriding Individual Components [#overriding-individual-components] To replace a single widget (for example, swap the revenue chart for a custom report), map its Livewire alias to your own component in the `components` key of `config/shopper/components/dashboard.php`. Shopper registers the entries of this file after its built-in widgets, so your class wins: ```php 'components' => [ 'locale-switcher' => Components\LocaleSwitcher::class, 'dashboard.revenue-chart' => App\Livewire\Dashboard\SalesReport::class, ], ``` The widget aliases are `setup-guide`, `dashboard.stat-cards`, `dashboard.revenue-chart`, `dashboard.top-selling-products` and `dashboard.recent-orders`. To change the layout or remove a widget, override the dashboard Blade view. Shopper has no publish tag for its views. Copy `vendor/shopper/framework/resources/views/livewire/pages/dashboard.blade.php` to `resources/views/vendor/shopper/livewire/pages/dashboard.blade.php`: Laravel loads your copy instead of the package view. The view shows the setup guide until it is completed or dismissed, then renders each widget with a Livewire tag that you can replace (simplified below: the file also holds the grid markup and the two dashboard render hooks): ```blade @if ($this->showSetupGuide) @else @can('browse_orders') @endcan @endif ``` Replace any tag with your own Livewire component or plain Blade content. The copy no longer follows updates of the package view, so compare it with the original after each Shopper upgrade. ## Adding Content via Render Hooks [#adding-content-via-render-hooks] If you only want to inject content above or below the dashboard without replacing the page or publishing views, use the layout render hooks: ```php use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; Shopper::renderHook( LayoutRenderHook::DASHBOARD_START, fn (): string => view('dashboard.store-alert-banner')->render(), ); Shopper::renderHook( LayoutRenderHook::DASHBOARD_END, fn (): string => view('dashboard.custom-reports')->render(), ); ``` Register these hooks in a service provider's `boot` method. See the [Render Hooks](/2.x/render-hooks) documentation for the full list of available injection points. # Demo Store (/2.x/demo-store) The official Shopper demo is a complete e-commerce application with a storefront and admin panel. It covers product browsing, variant selection, multi-step checkout, customer accounts, a blog, and multi-zone support with country-based currency switching. The full source code is [available on GitHub](https://github.com/shopperlabs/demo.laravelshopper.dev). Browse the storefront and explore the admin panel at demo.laravelshopper.dev Shopper demo store homepage ## What's Included [#whats-included] The demo store covers the full e-commerce experience: - **Product catalog** with categories, collections, attribute filtering, and search - **Product pages** with variant selection, image gallery, multi-currency pricing, and reviews - **Multi-step checkout** with address selection, shipping method, and payment (Stripe or cash on delivery) - **Customer accounts** with profile management, address book, and order history - **Blog** with articles, categories, featured images, and rich content - **Multi-zone support** with country-based currency switching and shipping options - **Admin panel** at `/cpanel` powered by Shopper with Filament ## Key Patterns [#key-patterns] The demo is designed as a reference implementation. Here are the main patterns you can study in the codebase. **Extending Shopper models** with custom logic. The demo's `Product` model adds a `HasProductPricing` trait for multi-currency price formatting, and all catalog models (Category, Brand, Collection) are extended in `app/Models/` to show how model swapping works in practice. **Multi-step checkout** built with Livewire. The `CheckoutWizard` component orchestrates three steps (Shipping, Delivery, Payment), each as its own Livewire component under `app/Livewire/Checkout/`. Session state is managed through a dedicated `CheckoutSession` class. **Domain actions** for business logic. Instead of putting logic in controllers, the demo uses Action classes in `app/Actions/` for operations like `CreateOrder`, `AddToCart`, and `ResolveVariantAvailability`. Each action has a single responsibility and is easy to test. **Extending the admin sidebar.** The demo adds a Blog section to Shopper's admin panel through `app/Sidebar/BlogSidebar.php`, with custom Livewire pages for managing posts and categories under `app/Livewire/Shopper/Blog/`. **Multi-currency pricing** via shipping zones. The `ZoneSessionManager` action and `ZoneSelector` slide-over component handle country-based currency switching. The `HasProductPricing` trait on the Product model formats prices based on the active zone's currency. **Payment gateway integration** with Shopper's payment drivers. The checkout offers Stripe (with webhooks via `StripeWebhookController`) and cash on delivery. Each zone lists the payment methods its customers can choose, and the Stripe keys live in `config/shopper/payment.php`. **Feature toggling.** The demo disables the Suppliers feature in `config/shopper/features.php` to show that you can turn off any part of Shopper you don't need. ## Admin Panel Access [#admin-panel-access] You can log in to the admin panel at [`/cpanel`](https://demo.laravelshopper.dev/cpanel): - **Email:** `admin@laravelshopper.dev` - **Password:** `demo.Shopper@2026!` The demo database is reset periodically. Please be respectful when editing data. ## Source Code [#source-code] The full source code is available on GitHub. You can clone it and run it locally to explore the codebase, modify it, or use it as a starting point for your own store. Browse the source code on GitHub To run the demo locally, clone the repository and run the setup command. This handles environment configuration, database migrations, and seeding with demo data. ```bash git clone https://github.com/shopperlabs/demo.laravelshopper.dev.git shopper-demo && cd shopper-demo composer install npm install && npm run build composer setup ``` Then access the storefront at the URL provided by your local server. The storefront is built with Livewire 3, Volt, and Flux UI, styled with Tailwind CSS 4. The production deployment uses Docker with FrankenPHP (Octane). # Discounts (/2.x/discounts) Discounts allow you to create promotional offers for your customers. Shopper supports percentage and fixed amount discounts with flexible application rules, eligibility conditions, and usage limits. ## Models [#models] Shopper uses two models to manage discounts: | Model | Purpose | |-------|---------| | `Shopper\Core\Models\Discount` | The discount definition (code, type, value, rules) | | `Shopper\Core\Models\DiscountDetail` | Polymorphic link connecting discounts to specific products or customers | The Discount model implements `Shopper\Core\Models\Contracts\Discount` and the DiscountDetail model implements `Shopper\Core\Models\Contracts\DiscountDetail`. Neither model is configurable via `config/shopper/models.php`. Each discount also has a computed `status` attribute that returns a `Shopper\Core\Enum\DiscountStatus` case. The first matching rule wins: | Status | Database Value | When | |--------|---------------|------| | Draft | `draft` | The discount is not saved yet | | Disabled | `disabled` | `is_active` is `false` | | Expired | `expired` | `end_at` is in the past | | LimitReached | `limit_reached` | `total_use` has reached `usage_limit` | | Scheduled | `scheduled` | `start_at` is in the future | | Active | `active` | None of the above | ```php use Shopper\Core\Enum\DiscountStatus; if ($discount->status === DiscountStatus::Active) { // The code can be offered to customers } ``` ## Database Schema [#database-schema] ### Discount Table [#discount-table] The table is `discounts`, prefixed with `config('shopper.core.table_prefix')` (`sh_` by default). | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `code` | string | no | - | Unique discount code | | `type` | string | no | - | Discount type enum | | `value` | integer | no | - | Discount value (percentage or cents) | | `is_active` | boolean | no | false | Whether the code can be used | | `apply_to` | string | no | - | Application scope enum | | `min_required` | string | no | - | Requirement type enum | | `min_required_value` | string | yes | null | Minimum value required | | `eligibility` | string | no | - | Eligibility type enum | | `usage_limit` | unsigned integer | yes | null | Maximum total uses (null = unlimited) | | `usage_limit_per_user` | boolean | no | false | Limit one use per customer | | `total_use` | unsigned integer | no | 0 | Current total usage count | | `start_at` | datetime | no | - | Discount start date | | `end_at` | datetime | yes | null | Discount end date (null = no expiry) | | `zone_id` | bigint | yes | null | FK to zone (null = all zones), set to null when the zone is deleted | | `metadata` | jsonb | yes | null | Additional custom data (cast to array) | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Discountable Table (Pivot) [#discountable-table-pivot] The table is `discountables`, with the same prefix. | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `condition` | string | yes | Condition type (apply_to, eligibility) | | `total_use` | unsigned integer | no | Default `0`. Shopper does not increment it: the per-user limit counts orders instead | | `discountable_id` | bigint | no | Polymorphic relation ID | | `discountable_type` | string | no | Polymorphic relation type | | `discount_id` | bigint | no | FK to discount, deleted with the discount | | `created_at` | timestamp | yes | Creation timestamp | | `updated_at` | timestamp | yes | Last update timestamp | ## Discount Type [#discount-type] The `DiscountType` enum defines value types: ```php use Shopper\Core\Enum\DiscountType; DiscountType::Percentage // percentage - e.g., 10% off DiscountType::FixedAmount // fixed_amount - e.g., $10 off ``` | Type | Database Value | Value Handling | |------|---------------|----------------| | Percentage | `percentage` | Stored as-is (10 = 10%) | | Fixed Amount | `fixed_amount` | Stored in cents (1000 = $10.00), or in whole units for a [zero-decimal currency](/2.x/currencies#zero-decimal-currencies) | ## Discount Application [#discount-application] The `DiscountApplyTo` enum defines where the discount applies: ```php use Shopper\Core\Enum\DiscountApplyTo; DiscountApplyTo::Order // order - Applies to entire order DiscountApplyTo::Products // products - Applies to specific products ``` | Scope | Database Value | Description | |-------|---------------|-------------| | Order | `order` | Discount applies to every cart line | | Products | `products` | Discount applies only to lines of linked products. A variant line matches when its parent product is linked | ## Discount Eligibility [#discount-eligibility] The `DiscountEligibility` enum defines who can use the discount: ```php use Shopper\Core\Enum\DiscountEligibility; DiscountEligibility::Everyone // everyone - All customers DiscountEligibility::Customers // customers - Specific customers only ``` | Eligibility | Database Value | Description | |-------------|---------------|-------------| | Everyone | `everyone` | Any customer can use, guests included | | Customers | `customers` | Only linked customers can use. The cart must belong to a logged-in customer | ## Discount Requirements [#discount-requirements] The `DiscountRequirement` enum defines minimum conditions: ```php use Shopper\Core\Enum\DiscountRequirement; DiscountRequirement::None // none - No minimum DiscountRequirement::Price // price - Minimum order amount DiscountRequirement::Quantity // quantity - Minimum items count ``` | Requirement | Database Value | min_required_value | |-------------|---------------|-------------------| | None | `none` | Not used | | Price | `price` | Minimum cart subtotal in cents (unit price times quantity for each line, before the discount) | | Quantity | `quantity` | Minimum number of items (sum of the cart line quantities) | ## Discount Condition [#discount-condition] The `DiscountCondition` enum is used on the `DiscountDetail` pivot model to distinguish whether a linked record represents a product (the discount applies to) or a customer (who is eligible): ```php use Shopper\Core\Enum\DiscountCondition; DiscountCondition::ApplyTo // apply_to - Links a product to the discount DiscountCondition::Eligibility // eligibility - Links a customer to the discount ``` ## Relationships [#relationships] ### Items (DiscountDetail) [#items-discountdetail] Store the same `discountable_type` values as the admin panel: `config('shopper.models.product')` for products and `config('auth.providers.users.model')` for customers. The cart only accepts a customer link whose type matches `config('auth.providers.users.model')`. ```php use Shopper\Core\Enum\DiscountCondition; // Get all discount items (products or customers) $discount->items; // Collection of DiscountDetail models // Add a product to discount $discount->items()->create([ 'condition' => DiscountCondition::ApplyTo, 'discountable_type' => config('shopper.models.product'), 'discountable_id' => $productId, ]); // Add eligible customer $discount->items()->create([ 'condition' => DiscountCondition::Eligibility, 'discountable_type' => config('auth.providers.users.model'), 'discountable_id' => $userId, ]); ``` ### Zone [#zone] ```php // Get discount zone (market) $discount->zone; // Zone model or null // Restrict discount to a zone $discount->update(['zone_id' => $zoneId]); ``` ## Value Handling [#value-handling] Fixed amount values are stored in cents. Percentage values are stored as the percentage number. For a $10 fixed discount, store `1000` (cents). For a 15% percentage discount, store `15`: ```php use Shopper\Core\Enum\DiscountType; $discount->update([ 'type' => DiscountType::FixedAmount, 'value' => 1000, // 1000 cents = $10.00 ]); $discount->update([ 'type' => DiscountType::Percentage, 'value' => 15, // 15% ]); ``` Saving a discount throws `Shopper\Core\Exceptions\InvalidDiscountValueException` when `value` is `0` or less, or when a percentage is above `100`. A percentage is applied to each applicable line and rounded to the cent. A fixed amount is capped at the subtotal of the applicable lines and split across them in proportion to their subtotal. The cart applies the stored amount as-is, without currency conversion: the admin form reads it in the currency of the discount's zone, or in the store currency when no zone is set. ## Usage Limit Enforcement [#usage-limit-enforcement] Discounts can cap the total number of redemptions with `usage_limit` and restrict each customer to one redemption with `usage_limit_per_user`. Both limits are enforced with strong consistency guarantees so that a coupon can never be silently over-redeemed under concurrent checkout. ### Global Usage Limit [#global-usage-limit] The `usage_limit` column caps the total number of redemptions across all customers. The `total_use` counter is incremented atomically inside the `CreateOrderFromCartAction` transaction: 1. The discount row is locked with `lockForUpdate` to serialize concurrent checkouts. 2. A conditional `UPDATE` increments `total_use` **only if** it is still below `usage_limit`. 3. If the conditional update affects zero rows, the limit was exhausted between cart validation and commit. `DiscountLimitReachedException::global()` is thrown and the order transaction rolls back, so no order is created. This compare-and-swap check was added in v2.8. If you upgrade from an older release, follow the [v2.7 to v2.8 upgrade guide](/2.x/upgrade/v2-7-to-v2-8). ### Per-User Limit [#per-user-limit] When `usage_limit_per_user` is `true`, each customer can redeem the discount at most once. The check counts prior orders on the `orders.discount_id` column (introduced in v2.8), not the legacy `DiscountDetail.total_use` counter: ```php config('shopper.models.order')::query() ->where('discount_id', $discount->id) ->where('customer_id', $cart->customer_id) ->exists(); ``` The same query runs in two places. `DiscountValidator` runs it each time the cart is calculated, so a customer who already used the code sees the cart total without the discount before checkout. `CreateOrderFromCartAction` re-checks at commit and throws `DiscountLimitReachedException::perUser()` if the customer redeemed it in the meantime. A per-user limit needs an identified customer, so a guest cart (no `customer_id`) can never apply a discount that sets `usage_limit_per_user`. `DiscountValidator` skips the discount with the `discount.requires_login` reason, and `CreateOrderFromCartAction` throws `DiscountLimitReachedException::perUser()`. ### Helpers [#helpers] ```php $discount->hasReachedLimit(); if ($discount->usage_limit !== null) { $remaining = $discount->usage_limit - $discount->total_use; } ``` ### Handling DiscountLimitReachedException [#handling-discountlimitreachedexception] Wrap your checkout flow to surface a friendly message to the customer when either limit is hit at commit time: ```php use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Exceptions\DiscountLimitReachedException; try { $order = resolve(CreateOrderFromCartAction::class)->execute($cart); } catch (DiscountLimitReachedException $e) { return back()->with('error', 'This discount can no longer be used.'); } ``` The exception has two static constructors that match the two limit types: | Constructor | Thrown When | |---|---| | `DiscountLimitReachedException::global($code)` | Global `usage_limit` was reached between cart validation and order commit | | `DiscountLimitReachedException::perUser($code)` | Customer already redeemed a discount with `usage_limit_per_user` set, or a guest cart uses such a discount | ## Creating Discounts [#creating-discounts] ### Percentage Discount for All Orders [#percentage-discount-for-all-orders] ```php use Shopper\Core\Models\Discount; use Shopper\Core\Enum\DiscountType; use Shopper\Core\Enum\DiscountApplyTo; use Shopper\Core\Enum\DiscountEligibility; use Shopper\Core\Enum\DiscountRequirement; $discount = Discount::query()->create([ 'code' => 'SUMMER20', 'type' => DiscountType::Percentage, 'value' => 20, // 20% off 'is_active' => true, 'apply_to' => DiscountApplyTo::Order, 'eligibility' => DiscountEligibility::Everyone, 'min_required' => DiscountRequirement::None, 'start_at' => now(), 'end_at' => now()->addMonth(), ]); ``` ### Fixed Amount Discount with Minimum Order [#fixed-amount-discount-with-minimum-order] ```php $discount = Discount::query()->create([ 'code' => 'SAVE10', 'type' => DiscountType::FixedAmount, 'value' => 1000, // 1000 cents = $10 off 'is_active' => true, 'apply_to' => DiscountApplyTo::Order, 'eligibility' => DiscountEligibility::Everyone, 'min_required' => DiscountRequirement::Price, 'min_required_value' => '5000', // Minimum 5000 cents = $50 order 'start_at' => now(), 'usage_limit' => 100, // Max 100 uses ]); ``` ### Product-Specific Discount [#product-specific-discount] ```php $discount = Discount::query()->create([ 'code' => 'PRODUCT15', 'type' => DiscountType::Percentage, 'value' => 15, 'is_active' => true, 'apply_to' => DiscountApplyTo::Products, 'eligibility' => DiscountEligibility::Everyone, 'min_required' => DiscountRequirement::None, 'start_at' => now(), ]); // Link specific products $discount->items()->createMany([ [ 'condition' => 'apply_to', 'discountable_type' => config('shopper.models.product'), 'discountable_id' => $product1->id, ], [ 'condition' => 'apply_to', 'discountable_type' => config('shopper.models.product'), 'discountable_id' => $product2->id, ], ]); ``` ### VIP Customer Discount [#vip-customer-discount] ```php $discount = Discount::query()->create([ 'code' => 'VIP30', 'type' => DiscountType::Percentage, 'value' => 30, 'is_active' => true, 'apply_to' => DiscountApplyTo::Order, 'eligibility' => DiscountEligibility::Customers, 'min_required' => DiscountRequirement::None, 'start_at' => now(), 'usage_limit_per_user' => true, // One use per customer ]); // Link eligible customers foreach ($vipCustomers as $customer) { $discount->items()->create([ 'condition' => 'eligibility', 'discountable_type' => config('auth.providers.users.model'), 'discountable_id' => $customer->id, ]); } ``` ## Retrieving Discounts [#retrieving-discounts] ```php use Shopper\Core\Models\Discount; // Get all active discounts $discounts = Discount::query() ->where('is_active', true) ->where('start_at', '<=', now()) ->where(function ($q) { $q->whereNull('end_at') ->orWhere('end_at', '>', now()); }) ->get(); // Get discount by code $discount = Discount::query() ->where('code', 'SUMMER20') ->where('is_active', true) ->first(); // Get discounts for a zone $discounts = Discount::query() ->where('is_active', true) ->where(function ($q) use ($zoneId) { $q->whereNull('zone_id') ->orWhere('zone_id', $zoneId); }) ->get(); // Get discounts with available uses $discounts = Discount::query() ->where('is_active', true) ->where(function ($q) { $q->whereNull('usage_limit') ->orWhereColumn('total_use', '<', 'usage_limit'); }) ->get(); ``` ## Discount Validation [#discount-validation] `CartManager::applyCoupon()` only checks that the code exists. The [Cart package](/2.x/cart#discount-validation) validates the discount each time the cart is calculated: `Shopper\Cart\Discounts\DiscountValidator` checks the active flag, the value, the date range, the usage limits, the eligibility, the zone and the minimum amount or quantity. You do not need to build these rules yourself. A discount that fails a check is skipped: the cart total is calculated without it, no exception is thrown and the code stays on the cart. To tell the customer why, call `DiscountValidator::validate()` yourself. It returns a `DiscountValidationResult` with a `valid` boolean and a translated `failureReason` (see the [Storefront Example](#storefront-example)). For a quick check outside the cart, without a cart context: ```php use Shopper\Core\Models\Discount; $discount = Discount::query() ->where('code', $code) ->where('is_active', true) ->first(); if ($discount && ! $discount->hasReachedLimit()) { // Active and has remaining uses. Dates, eligibility, zone and minimums are not checked here. } ``` ## Configuration [#configuration] ### Disabling Discounts [#disabling-discounts] If your store doesn't use discount codes, disable the feature in `config/shopper/features.php`. This removes the Discounts page and its menu item from the admin panel. The cart does not read this flag: `CartManager::applyCoupon()` still accepts the codes already in the database. ```php use Shopper\Enum\FeatureState; return [ 'discount' => FeatureState::Disabled, ]; ``` ### Permissions [#permissions] The admin panel generates five permissions for discount management: | Permission | Description | |------------|-------------| | `browse_discounts` | View the discounts list and its menu item | | `read_discounts` | Generated with the others, not checked by the 2.x admin panel | | `add_discounts` | Create new discounts | | `edit_discounts` | Edit existing discounts | | `delete_discounts` | Delete discounts | ## Components [#components] To customize the admin UI for discount management: ```bash php artisan shopper:component:publish discount ``` Creates `config/shopper/components/discount.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'discount-index' => Livewire\Pages\Discount\Index::class, ], 'components' => [ 'slide-overs.discount-form' => Livewire\SlideOvers\DiscountForm::class, ], ]; ``` ## Storefront Example [#storefront-example] Applying a discount code on the storefront uses the [Cart package](/2.x/cart) API. The `CartManager::applyCoupon()` method validates the code exists, and the calculation pipeline handles the rest (validation rules, discount calculation, and adjustment creation). A code that exists but breaks a rule is still saved on the cart, so the example runs the validator and removes the code when it does not apply: ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Shopper\Cart\CartManager; use Shopper\Cart\Discounts\DiscountValidator; use Shopper\Cart\Exceptions\InvalidDiscountException; use Shopper\Cart\Facades\Cart; use Shopper\Core\Models\Discount; class CouponController extends Controller { public function apply(Request $request) { $request->validate(['code' => 'required|string']); $manager = resolve(CartManager::class); $cart = Cart::current(); if ($cart === null) { return back()->with('error', 'Your cart is empty.'); } try { $manager->applyCoupon($cart, $request->code); } catch (InvalidDiscountException $e) { return back()->with('error', $e->getMessage()); } $discount = Discount::query()->where('code', $request->code)->first(); $result = resolve(DiscountValidator::class)->validate($discount, $manager->calculate($cart)); if (! $result->valid) { $manager->removeCoupon($cart); return back()->with('error', $result->failureReason); } return back()->with('success', 'Discount applied.'); } public function remove() { $cart = Cart::current(); if ($cart === null) { return back(); } resolve(CartManager::class)->removeCoupon($cart); return back()->with('success', 'Discount removed.'); } } ``` ## Use Cases [#use-cases] | Scenario | Type | Apply To | Eligibility | Requirement | |----------|------|----------|-------------|-------------| | Site-wide sale | Percentage | Order | Everyone | None | | $10 off orders over $50 | Fixed | Order | Everyone | Price | | Buy 3+ get 10% off | Percentage | Order | Everyone | Quantity | | VIP member exclusive | Percentage | Order | Customers | None | | Product clearance | Percentage | Products | Everyone | None | | Welcome code for selected customers | Fixed | Order | Customers | None | # Events (/2.x/events) Shopper dispatches events at key moments in the order, product, and cart lifecycle. These events allow you to hook into the system and add custom behavior like sending notifications, syncing with external services, updating analytics, or triggering workflows without modifying any Shopper code. The events on this page are organized by domain across two namespaces: - `Shopper\Core\Events`: order and product events - `Shopper\Cart\Events`: cart events The admin panel also dispatches events that this page does not cover: `Shopper\Events\TwoFactor\TwoFactorAuthenticationEnabled` when a user turns on [two-factor authentication](/2.x/two-factor#interfaces-and-traits), `Shopper\Events\LoadShopper` on every admin request, and `Shopper\Sidebar\SidebarBuilder` when it builds the [sidebar](/2.x/sidebar/shopper-extension). ```php use Shopper\Core\Events\Orders\OrderCompleted; use Shopper\Core\Events\Orders\OrderPaid; use Shopper\Core\Events\Products\ProductCreated; ``` ## Listening to Events [#listening-to-events] Register listeners with Laravel's event discovery (a listener in `app/Listeners` whose `handle` method type-hints the event), with `Event::listen()` in a service provider, or in the `$listen` array of an `EventServiceProvider`: ```php use Shopper\Core\Events\Orders\OrderCompleted; use Shopper\Core\Events\Orders\OrderPaid; protected $listen = [ OrderPaid::class => [ GenerateInvoice::class, SendPaymentConfirmation::class, ], OrderCompleted::class => [ SendOrderCompletedEmail::class, ], ]; ``` Every event carries the relevant model as a public property, accessible directly in your listener: ```php use Shopper\Core\Events\Orders\OrderPaid; class GenerateInvoice { public function handle(OrderPaid $event): void { $order = $event->order; $order->load('items', 'customer', 'billingAddress'); Invoice::generate($order); } } ``` ## Order Events [#order-events] Order events cover the full lifecycle of a purchase, from creation to completion, cancellation, or archival. ### Available Events [#available-events] | Event | Payload | Trigger | |-------|---------|---------| | `OrderCreated` | `Order $order` | Order is inserted in the database | | `OrderItemCreated` | `OrderItem $orderItem` | Order item is inserted in the database | | `OrderPaid` | `Order $order` | Admin marks order as paid | | `OrderCompleted` | `Order $order` | Admin marks order as completed | | `OrderShipped` | `Order $order` | All items reach shipped status | | `OrderCancelled` | `Order $order` | Admin cancels the order | | `OrderArchived` | `Order $order` | Admin archives the order | | `OrderDeleted` | `Order $order` | Order is being deleted (soft or force delete) | | `OrderNoteAdded` | `Order $order` | Admin adds a note to the order | All order events except `OrderItemCreated` carry a single `public Order $order` property. It is typed with the `Shopper\Core\Models\Contracts\Order` contract, so you receive an instance of the model set in `config('shopper.models.order')`. `OrderItemCreated` carries `public OrderItem $orderItem` (`Shopper\Core\Models\OrderItem`). ### Lifecycle Flow [#lifecycle-flow] ``` OrderCreated │ ├── OrderPaid │ │ │ ├── OrderShipped ──> OrderCompleted │ │ │ └── OrderCancelled │ ├── OrderCancelled │ ├── OrderArchived │ └── OrderDeleted ``` ### How They Are Dispatched [#how-they-are-dispatched] `OrderCreated` and `OrderDeleted` are dispatched by `Shopper\Core\Observers\OrderObserver`, registered on the model set in `config('shopper.models.order')`. They fire on every Eloquent insert and delete, whether the operation comes from the admin panel, the cart checkout or your own code. `OrderDeleted` fires from the `deleting` hook, before the row is soft-deleted or removed. `OrderItemCreated` works the same way through `OrderItemObserver`, once per order item. Mass updates and deletes run through the query builder skip model events. ```php use Shopper\Core\Models\Order; $order = Order::query()->create([ 'number' => generate_number(), 'price_amount' => 12900, 'currency_code' => shopper_currency(), 'customer_id' => $customer->id, ]); ``` Status-related events (`OrderPaid`, `OrderCompleted`, `OrderCancelled`, `OrderArchived`) are dispatched from the admin panel when an administrator changes the order status with the **Mark as paid**, **Mark complete**, **Cancel Order** or **Archive** action of the order detail page. Updating `status` or `payment_status` in your own code dispatches nothing: dispatch the event yourself, for example `event(new OrderPaid($order))`. Two built-in paths also change these statuses without an event: capturing an authorized payment sets `payment_status` to `paid` without `OrderPaid`, and delivering the last package sets `status` to `completed` without `OrderCompleted`. `OrderShipped` is dispatched by `SyncOrderShippingStatusAction` when the order's `shipping_status` transitions to `Shipped`, which means every item has the shipped fulfillment status. The action runs each time a shipment is recorded as picked up, delivered or returned, so you don't dispatch it manually. ### Dispatch After Commit [#queueing] All order events implement Laravel's `ShouldDispatchAfterCommit` contract. When one is dispatched inside a database transaction, Laravel holds it until the transaction commits and drops it if the transaction rolls back. Outside a transaction, it is dispatched at once. The checkout creates the order and its items in the same transaction, so an `OrderCreated` listener finds the items. The contract does not queue anything: a listener runs during the request unless it implements `Illuminate\Contracts\Queue\ShouldQueue`. | Event | After commit | |-------|--------| | `OrderCreated` | Yes | | `OrderItemCreated` | Yes | | `OrderPaid` | Yes | | `OrderCompleted` | Yes | | `OrderShipped` | Yes | | `OrderCancelled` | Yes | | `OrderArchived` | Yes | | `OrderDeleted` | Yes | | `OrderNoteAdded` | Yes | ## Shipment Events [#shipment-events] Shipment events track the creation and delivery of individual packages within an order. A single order can have multiple shipments. ### Available Events [#available-events-1] | Event | Payload | Trigger | |-------|---------|---------| | `OrderShipmentCreated` | `Order $order`, `OrderShipping $shipment` | Admin creates a shipping label, which creates a new shipment | | `OrderShipmentDelivered` | `Order $order`, `OrderShipping $shipment` | A shipment is marked as delivered with `MarkShipmentDeliveredAction` | Both shipment events carry two properties: the order and the specific shipment. This is useful when an order has multiple packages and you need to know which one was created or delivered. Both implement `ShouldDispatchAfterCommit`. `OrderShipmentDelivered` comes from `MarkShipmentDeliveredAction`, which the **Mark as delivered** action of the shipments list calls. Recording a **Delivered** status with **Add event** in the shipment panel updates the shipment and its items but does not dispatch it. ```php use Shopper\Core\Events\Orders\OrderShipmentDelivered; class NotifyCustomerOfDelivery { public function handle(OrderShipmentDelivered $event): void { $order = $event->order; $shipment = $event->shipment; $trackingNumber = $shipment->tracking_number; $deliveredItems = $shipment->items; } } ``` ### Shipment vs Order Events [#shipment-vs-order-events] Shipment events fire at the **package level**, order events fire at the **order level**: | Scenario | Events fired | |----------|-------------| | Label created for the first package (2 of 3 items) | `OrderShipmentCreated` | | Label created for the second package (last item) | `OrderShipmentCreated` | | Last package picked up, every item now shipped | `OrderShipped` | | First package delivered | `OrderShipmentDelivered` | | Last package delivered | `OrderShipmentDelivered`, and the order `status` becomes `completed` if it was `processing` (no `OrderCompleted`) | `OrderShipped` needs every item shipped at the same time. If a package is delivered before the last one is picked up, the order goes from partially shipped to partially delivered and `OrderShipped` is not dispatched. ## Product Events [#product-events] Product events are dispatched when products are created, updated, or deleted through the admin panel. ### Available Events [#available-events-2] | Event | Payload | Trigger | |-------|---------|---------| | `ProductCreated` | `Product $product` | Product is created via admin | | `ProductUpdated` | `Product $product` | Product **Overview** form is saved via admin | | `ProductDeleted` | `Product $product` | Product is deleted via admin, dispatched just before the delete | These events come from the admin actions, not from a model observer: `Product::query()->create()` or `$product->update()` in your own code dispatches nothing. Saving the other tabs of the product page (media, files, inventory, shipping, SEO) does not dispatch `ProductUpdated`. ```php use Shopper\Core\Events\Products\ProductCreated; class SyncProductToCatalog { public function handle(ProductCreated $event): void { $product = $event->product; ExternalCatalog::push($product); } } ``` All product events implement `ShouldDispatchAfterCommit`: inside a database transaction, they wait for the commit. Listeners run during the request unless they implement `ShouldQueue`. ## Example: Order Notification System [#example-order-notification-system] Here's how you might use Shopper events to build a notification flow for your store. Each listener handles a single responsibility. Register your listeners: ```php use Shopper\Core\Events\Orders\OrderCreated; use Shopper\Core\Events\Orders\OrderPaid; use Shopper\Core\Events\Orders\OrderShipped; use Shopper\Core\Events\Orders\OrderShipmentDelivered; protected $listen = [ OrderCreated::class => [ SendOrderConfirmationToCustomer::class, NotifyWarehouseTeam::class, ], OrderPaid::class => [ GenerateInvoice::class, SyncPaymentToAccounting::class, ], OrderShipped::class => [ SendShippingConfirmation::class, ], OrderShipmentDelivered::class => [ SendDeliveryConfirmation::class, RequestProductReview::class, ], ]; ``` A listener that sends a shipping confirmation: ```php use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Mail; use Shopper\Core\Events\Orders\OrderShipped; class SendShippingConfirmation implements ShouldQueue { public function handle(OrderShipped $event): void { $order = $event->order; $order->load('customer', 'shippings.carrier'); if ($order->customer === null) { return; } Mail::to($order->customer->email) ->send(new OrderShippedMail($order)); } } ``` ## Cart Events [#cart-events] Cart events are dispatched when a cart reaches a key state during the checkout process. ### Available Events [#available-events-3] | Event | Payload | Trigger | |-------|---------|---------| | `CartCompleted` | `Cart $cart`, `Order $order` | `CreateOrderFromCartAction` converts the cart to an order | | `CouponApplied` | `Cart $cart`, `string $code` | `CartManager::applyCoupon()` stores a code that matches an existing discount on the cart | | `CouponRemoved` | `Cart $cart` | `CartManager::removeCoupon()` clears the coupon code from the cart | `CouponRemoved` does not carry the removed code: the cart's `coupon_code` is already `null` when it fires. Cart events do not implement `ShouldDispatchAfterCommit`. `CartCompleted` is dispatched inside the checkout transaction, before the commit: a listener that runs during the request runs inside that transaction, and an exception it throws rolls the order back. A queued listener should implement `Illuminate\Contracts\Queue\ShouldQueueAfterCommit` so it never runs before the order is saved. Cart events are in the `Shopper\Cart\Events` namespace: ```php use Shopper\Cart\Events\CartCompleted; use Shopper\Cart\Events\CouponApplied; use Shopper\Cart\Events\CouponRemoved; ``` ### Example: Sending a Cart Recovery Email on Coupon Removal [#example-sending-a-cart-recovery-email-on-coupon-removal] ```php use Illuminate\Support\Facades\Mail; use Shopper\Cart\Events\CouponRemoved; class OfferAlternativeCoupon { public function handle(CouponRemoved $event): void { $cart = $event->cart; $customer = $cart->customer; if ($customer) { Mail::to($customer->email)->send(new AlternativeDiscountMail($cart)); } } } ``` ## All Events Reference [#all-events-reference] | Namespace | Event | Payload | After commit | |-----------|-------|---------|--------| | `Events\Orders` | `OrderCreated` | `Order $order` | Yes | | `Events\Orders` | `OrderItemCreated` | `OrderItem $orderItem` | Yes | | `Events\Orders` | `OrderPaid` | `Order $order` | Yes | | `Events\Orders` | `OrderCompleted` | `Order $order` | Yes | | `Events\Orders` | `OrderShipped` | `Order $order` | Yes | | `Events\Orders` | `OrderCancelled` | `Order $order` | Yes | | `Events\Orders` | `OrderArchived` | `Order $order` | Yes | | `Events\Orders` | `OrderDeleted` | `Order $order` | Yes | | `Events\Orders` | `OrderNoteAdded` | `Order $order` | Yes | | `Events\Orders` | `OrderShipmentCreated` | `Order $order`, `OrderShipping $shipment` | Yes | | `Events\Orders` | `OrderShipmentDelivered` | `Order $order`, `OrderShipping $shipment` | Yes | | `Events\Products` | `ProductCreated` | `Product $product` | Yes | | `Events\Products` | `ProductUpdated` | `Product $product` | Yes | | `Events\Products` | `ProductDeleted` | `Product $product` | Yes | | `Cart\Events` | `CartCompleted` | `Cart $cart`, `Order $order` | No | | `Cart\Events` | `CouponApplied` | `Cart $cart`, `string $code` | No | | `Cart\Events` | `CouponRemoved` | `Cart $cart` | No | # Fulfillment (/2.x/fulfillment) Order fulfillment in Shopper is designed around the concept of **shipments**, physical packages sent to customers. A single order can have multiple shipments, each with its own carrier, tracking number, and set of items. ## Architecture [#architecture] The fulfillment system connects four models: ``` Order (1) ──> (many) OrderShipping (1) ──> (many) OrderItem (shipment) │ (items in this package) └──> (many) OrderShippingEvent (tracking timeline) ``` - **Order** has many **shipments** (`OrderShipping`) and tracks overall `shipping_status` - Each **shipment** has its own `status` (ShipmentStatus) and a timeline of **events** (`OrderShippingEvent`) - Each **item** tracks its own **fulfillment status** independently ```php use Shopper\Core\Models\Order; use Shopper\Core\Models\OrderShipping; use Shopper\Core\Models\OrderShippingEvent; use Shopper\Core\Models\OrderItem; use Shopper\Core\Enum\ShippingStatus; use Shopper\Core\Enum\ShipmentStatus; use Shopper\Core\Enum\FulfillmentStatus; ``` ## Database Schema [#database-schema] ### OrderShipping Table [#ordershipping-table] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `order_id` | bigint | no | FK to order | | `carrier_id` | bigint | yes | FK to carrier | | `status` | string(32) | yes | Shipment status enum | | `shipped_at` | datetime | yes | When the shipment was dispatched | | `received_at` | datetime | yes | When the customer received it | | `returned_at` | datetime | yes | If the shipment was returned | | `tracking_number` | string | yes | Carrier tracking number | | `tracking_url` | string | yes | URL for customer tracking | | `voucher` | json | yes | Shipping label/voucher data | | `created_at` | timestamp | yes | Creation timestamp | | `updated_at` | timestamp | yes | Last update timestamp | ### OrderShippingEvent Table [#ordershippingevent-table] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `order_shipping_id` | bigint | no | FK to shipment | | `status` | string(32) | no | Shipment status at this event | | `description` | text | yes | Event description | | `location` | string | yes | Location name | | `latitude` | decimal(11,7) | yes | GPS latitude | | `longitude` | decimal(10,7) | yes | GPS longitude | | `occurred_at` | datetime | no | When the event occurred (`logEvent()` sets it to now when you omit it) | | `metadata` | jsonb | yes | Additional event data | | `created_at` | timestamp | yes | Creation timestamp | | `updated_at` | timestamp | yes | Last update timestamp | ### OrderItem Fulfillment Columns [#orderitem-fulfillment-columns] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `order_shipping_id` | bigint | yes | FK to the shipment this item belongs to | | `fulfillment_status` | string | yes | Current fulfillment state of this item. `pending` when the item is created through the `OrderItem` model; items created before this column existed keep `null` | ## Fulfillment Status [#fulfillment-status] The `FulfillmentStatus` enum defines the lifecycle of each item: ```php use Shopper\Core\Enum\FulfillmentStatus; FulfillmentStatus::Pending // Awaiting processing FulfillmentStatus::ForwardedToSupplier // Sent to external supplier (dropshipping) FulfillmentStatus::Processing // Being prepared for shipment FulfillmentStatus::Shipped // In transit FulfillmentStatus::Delivered // Received by customer FulfillmentStatus::Cancelled // Fulfillment cancelled ``` ### Status Flow [#status-flow] | From | Possible Transitions | |------|---------------------| | Pending | Processing, ForwardedToSupplier, Shipped, Cancelled | | ForwardedToSupplier | Processing, Shipped, Cancelled | | Processing | Shipped, Cancelled | | Shipped | Delivered, Cancelled | | Delivered | Cancelled | | Cancelled | (terminal state) | The table lists the transitions that make sense for an item. Nothing on `OrderItem` enforces them: `fulfillment_status` accepts any case. Shopper performs three of them, in [`RecordShipmentEventAction`](/2.x/fulfillment#recordshipmenteventaction), on the items of the shipment that receives the event: `Pending` to `Shipped` when the carrier picks up the package, `Shipped` to `Delivered` on delivery, and any status to `Cancelled` when the package is returned. Your own code sets every other transition. Shopper never sets `Processing` or `ForwardedToSupplier`, and the pickup leaves items in these two statuses as they are, so move them to `Shipped` yourself, as the [dropshipping workflow](/2.x/fulfillment#dropshipping-workflow) does. The admin's shipping label form only offers items that are in no shipment yet and whose status is `Pending` (or `null`), so an item you moved to `Processing` or `ForwardedToSupplier` cannot be added to a label there. ## Shipping Status (Order Level) [#shipping-status-order-level] The `ShippingStatus` enum lives on the **Order** model (`shipping_status`, `Unfulfilled` by default). [`SyncOrderShippingStatusAction`](/2.x/fulfillment#syncordershippingstatusaction) computes it from the fulfillment status of all the order's items. It answers "has this order been shipped/delivered?". ```php use Shopper\Core\Enum\ShippingStatus; ShippingStatus::Unfulfilled // No items shipped yet ShippingStatus::PartiallyShipped // Some items shipped ShippingStatus::Shipped // All items shipped ShippingStatus::PartiallyDelivered // Some items delivered ShippingStatus::Delivered // All items delivered ShippingStatus::PartiallyReturned // Some items returned ShippingStatus::Returned // All items returned ``` ## Shipment Status (Package Level) [#shipment-status-package-level] The `ShipmentStatus` enum lives on the **OrderShipping** model and tracks the delivery progress of a single package. Each shipment goes through this lifecycle independently. ```php use Shopper\Core\Enum\ShipmentStatus; ShipmentStatus::Pending // Label created, waiting for pickup ShipmentStatus::PickedUp // Carrier collected the package ShipmentStatus::InTransit // On the way ShipmentStatus::AtSortingCenter // At a sorting facility ShipmentStatus::OutForDelivery // With the local delivery driver ShipmentStatus::Delivered // Delivered to the customer ShipmentStatus::DeliveryFailed // Delivery attempt failed ShipmentStatus::Returned // Returned to sender ``` ### Shipment Transitions [#shipment-transitions] The `HasFulfillmentTransitions` trait on `OrderShipping` defines the valid state transitions. `transitionTo()` and the [actions](/2.x/fulfillment#actions) check them; writing `status` with `update()` skips the check. | From | Possible Transitions | |------|---------------------| | Pending | PickedUp, Returned | | PickedUp | InTransit, DeliveryFailed, Returned | | InTransit | AtSortingCenter, OutForDelivery, DeliveryFailed, Returned | | AtSortingCenter | InTransit, OutForDelivery, DeliveryFailed, Returned | | OutForDelivery | Delivered, DeliveryFailed, Returned | | Delivered | Returned | | DeliveryFailed | InTransit, OutForDelivery, Returned | | Returned | (terminal state) | A shipment whose `status` is `null` (created without one) can only move to `Pending`. ```php $shipment->canTransitionTo(ShipmentStatus::InTransit); // true or false $shipment->allowedTransitions(); // array of valid next statuses $shipment->canBeDelivered(); // shorthand for canTransitionTo(Delivered) OrderShipping::shipmentTransitions(); // the full table above, keyed by status value ``` ### Transitioning Shipment Status [#transitioning-shipment-status] Use `transitionTo()` to update the shipment status. It checks the transition and automatically logs a tracking event: ```php $shipment->transitionTo(ShipmentStatus::PickedUp, [ 'description' => 'Package collected by carrier', 'location' => 'Paris Distribution Center', 'latitude' => 48.8566, 'longitude' => 2.3522, ]); ``` This creates an `OrderShippingEvent` record with the status, timestamp, and optional location data. When the transition is not allowed, `transitionTo()` returns without saving anything and throws no exception. It only changes the shipment and its timeline: to also update the items and the order, use [`RecordShipmentEventAction`](/2.x/fulfillment#recordshipmenteventaction). ### Tracking Events [#tracking-events] Each shipment has a timeline of events that record its journey. Adding an event does not change the shipment `status`: ```php $shipment->events; // Collection $shipment->events()->create([ 'status' => ShipmentStatus::InTransit, 'description' => 'Package departed sorting facility', 'location' => 'Lyon Hub', 'occurred_at' => now(), 'metadata' => ['facility_code' => 'LYS-01'], ]); // logEvent() writes the same record and sets occurred_at to now when omitted $shipment->logEvent(ShipmentStatus::InTransit, [ 'description' => 'Package departed sorting facility', 'location' => 'Lyon Hub', ]); ``` ## Relationships [#relationships] ### Order to Shipments [#order--shipments] ```php // Get all shipments for an order $order->shippings; // Collection // Load shipments with their carrier and items $order->load('shippings.carrier', 'shippings.items'); // Check if every item has been delivered $allDelivered = $order->items->every( fn (OrderItem $item) => $item->fulfillment_status === FulfillmentStatus::Delivered ); ``` ### OrderShipping to Items and Events [#ordershipping--items--events] ```php // Get all items in a shipment $shipment->items; // Collection // Get the carrier for this shipment $shipment->carrier; // Carrier model // Get the parent order $shipment->order; // Order model // Get the tracking timeline $shipment->events; // Collection ``` ### OrderItem to Shipment [#orderitem--shipment] ```php // Get the shipment for an item $item->shipment; // OrderShipping (nullable) // Get tracking info for an item $item->shipment?->tracking_number; $item->shipment?->tracking_url; $item->shipment?->carrier?->name; ``` ## Creating Shipments [#creating-shipments] ### Single Shipment (All Items Together) [#single-shipment-all-items-together] When all items ship in one package: ```php use Shopper\Core\Actions\RecordShipmentEventAction; $order = Order::query()->find($orderId); // Create the shipment: the label exists, the carrier has not collected the package yet $shipment = $order->shippings()->create([ 'carrier_id' => $carrier->id, 'status' => ShipmentStatus::Pending, 'tracking_number' => '1Z999AA10123456784', 'tracking_url' => 'https://ups.com/track?num=1Z999AA10123456784', ]); // Link all items to the package $order->items()->update(['order_shipping_id' => $shipment->id]); // Record the carrier pickup resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp); ``` Recording `PickedUp` sets `shipped_at`, moves the linked items from `Pending` to `Shipped`, moves a `New` order to `Processing`, and recomputes the order's `shipping_status`. Create the shipment with the `Pending` status: a shipment without a status can only move to `Pending`, so recording `PickedUp` on it does nothing. ### Partial Shipment (Split Across Packages) [#partial-shipment-split-across-packages] When items ship in multiple packages with different carriers: ```php use Shopper\Core\Actions\RecordShipmentEventAction; $order = Order::query() ->with('items') ->find($orderId); $recordEvent = resolve(RecordShipmentEventAction::class); // First package: items 1 and 2 via Colissimo $shipment1 = $order->shippings()->create([ 'carrier_id' => $colissimoId, 'status' => ShipmentStatus::Pending, 'tracking_number' => 'LP123456789FR', 'tracking_url' => 'https://laposte.fr/suivi/LP123456789FR', ]); $order->items() ->whereIn('id', [$item1->id, $item2->id]) ->update(['order_shipping_id' => $shipment1->id]); $recordEvent->execute($shipment1, ShipmentStatus::PickedUp); // Second package: item 3 via UPS (ships later) $shipment2 = $order->shippings()->create([ 'carrier_id' => $upsId, 'status' => ShipmentStatus::Pending, 'tracking_number' => '1Z999AA10987654321', 'tracking_url' => 'https://ups.com/track?num=1Z999AA10987654321', ]); $order->items() ->where('id', $item3->id) ->update(['order_shipping_id' => $shipment2->id]); $recordEvent->execute($shipment2, ShipmentStatus::PickedUp); ``` After the first pickup the order's `shipping_status` is `PartiallyShipped`. After the second it is `Shipped`, and `OrderShipped` is dispatched. ### Marking as Delivered [#marking-as-delivered] ```php use Shopper\Core\Actions\MarkShipmentDeliveredAction; resolve(MarkShipmentDeliveredAction::class)->execute($shipment, [ 'description' => 'Left with the building concierge', ]); ``` The action sets `received_at`, moves the shipment's `Shipped` items to `Delivered`, recomputes the order's `shipping_status`, and moves the order from `Processing` to `Completed` once every item of the order is delivered. `Delivered` is only reachable from `OutForDelivery`: on a shipment in any other status the action does nothing, so record `InTransit` and `OutForDelivery` with `RecordShipmentEventAction` first. ## Dropshipping Workflow [#dropshipping-workflow] For external products sourced from suppliers, the fulfillment flow includes an additional step where the order is forwarded to the supplier who ships directly to the customer. Dropshipping requires the [Supplier](/2.x/suppliers) feature to be enabled. External products must be linked to a supplier. ### Complete Dropshipping Flow [#complete-dropshipping-flow] ```php use Shopper\Core\Actions\RecordShipmentEventAction; $order = Order::query() ->with('items.product') ->find($orderId); // Step 1: Forward items to their suppliers foreach ($order->items as $item) { if ($item->product->supplier_id) { $item->update([ 'fulfillment_status' => FulfillmentStatus::ForwardedToSupplier, ]); } } // Step 2: When the supplier ships, create the shipment $shipment = $order->shippings()->create([ 'carrier_id' => $carrierId, 'status' => ShipmentStatus::Pending, 'tracking_number' => $trackingFromSupplier, 'tracking_url' => $trackingUrlFromSupplier, ]); // Link supplier items to the shipment and mark them shipped: // the pickup event below only moves Pending items to Shipped $order->items() ->where('fulfillment_status', FulfillmentStatus::ForwardedToSupplier) ->update([ 'order_shipping_id' => $shipment->id, 'fulfillment_status' => FulfillmentStatus::Shipped, ]); resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp); ``` `OrderItem::product()` is polymorphic: a variant line points to a `ProductVariant`, which has no `supplier_id` and no `supplier` relation. For those lines, read the supplier from the parent product: `$item->product->product->supplier_id`. ### Mixed Orders (Own Products + Supplier Products) [#mixed-orders-own-products--supplier-products] An order can contain both your own products and dropshipped products: ```php use Shopper\Core\Actions\RecordShipmentEventAction; $order = Order::query() ->with('items.product') ->find($orderId); $ownItems = $order->items->filter( fn ($item) => ! $item->product->supplier_id ); $supplierItems = $order->items->filter( fn ($item) => $item->product->supplier_id ); // Ship your own products immediately if ($ownItems->isNotEmpty()) { $shipment = $order->shippings()->create([ 'carrier_id' => $yourCarrierId, 'status' => ShipmentStatus::Pending, 'tracking_number' => $yourTracking, ]); $order->items() ->whereIn('id', $ownItems->pluck('id')) ->update(['order_shipping_id' => $shipment->id]); resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp); } // Forward supplier items if ($supplierItems->isNotEmpty()) { $order->items() ->whereIn('id', $supplierItems->pluck('id')) ->update([ 'fulfillment_status' => FulfillmentStatus::ForwardedToSupplier, ]); } ``` ## Querying Fulfillment Data [#querying-fulfillment-data] ### Items by Status [#items-by-status] ```php use Illuminate\Database\Eloquent\Relations\MorphTo; // Get all unfulfilled items across orders $unfulfilledItems = OrderItem::query() ->whereNull('fulfillment_status') ->orWhere('fulfillment_status', FulfillmentStatus::Pending) ->with('order.customer') ->get(); // Get items waiting for supplier, with the supplier of product lines // (variant lines have no supplier relation) $awaitingSupplier = OrderItem::query() ->where('fulfillment_status', FulfillmentStatus::ForwardedToSupplier) ->with(['product' => fn (MorphTo $morphTo) => $morphTo->morphWith([ config('shopper.models.product') => ['supplier'], ])]) ->get(); ``` ### Orders Needing Attention [#orders-needing-attention] ```php // Orders with items not yet shipped $ordersToFulfill = Order::query() ->whereHas('items', fn ($q) => $q ->where('fulfillment_status', FulfillmentStatus::Pending) ->orWhereNull('fulfillment_status') ) ->with('items', 'shippings') ->get(); // Orders partially shipped $partiallyShipped = Order::query() ->where('shipping_status', ShippingStatus::PartiallyShipped) ->get(); ``` ### Shipment History [#shipment-history] ```php // Get all shipments for a customer $customerShipments = OrderShipping::query() ->whereHas('order', fn ($q) => $q->where('customer_id', $customerId)) ->with(['carrier', 'items', 'order']) ->latest('shipped_at') ->get(); ``` ## Handling Returns [#handling-returns] ```php use Shopper\Core\Actions\RecordShipmentEventAction; resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::Returned, [ 'description' => 'Returned to sender: recipient unknown at this address', ]); ``` Recording `Returned` sets `returned_at`, marks every item of the shipment as `Cancelled`, and recomputes the order's `shipping_status`: `Returned` when every item of the order is cancelled, `PartiallyReturned` when the other items are shipped or delivered. Any status except `Returned` can move to `Returned`. The order `status` does not change. ## Actions [#actions] Shopper provides dedicated action classes for fulfillment operations. These handle side effects like syncing order statuses, updating item states, and dispatching events automatically. ### RecordShipmentEventAction [#recordshipmenteventaction] The recommended way to record shipment events. It checks the transition, updates the shipment status, logs the event, and handles side effects based on the new status. It returns the created `OrderShippingEvent`, or `null` without changing anything when the transition is not allowed or when `occurred_at` is earlier than the shipment's latest event: ```php use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\ShipmentStatus; $action = resolve(RecordShipmentEventAction::class); $action->execute($shipment, ShipmentStatus::PickedUp, [ 'description' => 'Package collected by carrier', 'location' => 'Paris Distribution Center', 'occurred_at' => now(), ]); ``` When a shipment transitions to **PickedUp**, the action sets `shipped_at` to the event date, updates the shipment's `Pending` items to `FulfillmentStatus::Shipped` (items in another status keep it), and changes the order status from `New` to `Processing`. When a shipment transitions to **Delivered**, the action sets `received_at`, updates the shipment's `Shipped` items to `FulfillmentStatus::Delivered`, and moves the order from `Processing` to `Completed` when every item of the order is delivered. It does not dispatch `OrderShipmentDelivered` or `OrderCompleted`: use `MarkShipmentDeliveredAction` below when your listeners need the delivery event. When a shipment transitions to **Returned**, the action sets `returned_at` and updates all items of the shipment to `FulfillmentStatus::Cancelled`. After each of these three transitions, the action runs `SyncOrderShippingStatusAction` on the order. Other statuses (`InTransit`, `AtSortingCenter`, `OutForDelivery`, `DeliveryFailed`) only update the shipment and its timeline. ### MarkShipmentDeliveredAction [#markshipmentdeliveredaction] A convenience action for marking a shipment as delivered. It records the `Delivered` event through `RecordShipmentEventAction` and dispatches the `OrderShipmentDelivered` event. When the shipment cannot transition to `Delivered` (its status is not `OutForDelivery`), it does nothing: ```php use Shopper\Core\Actions\MarkShipmentDeliveredAction; $action = resolve(MarkShipmentDeliveredAction::class); $action->execute($shipment, [ 'description' => 'Delivered to customer', 'location' => 'Customer address', ]); ``` ### SyncOrderShippingStatusAction [#syncordershippingstatusaction] This action computes the order-level `shipping_status` from the fulfillment statuses of all its items. `RecordShipmentEventAction` runs it after a `PickedUp`, `Delivered` or `Returned` event. Call it yourself when you update item statuses directly: ```php use Shopper\Core\Actions\SyncOrderShippingStatusAction; $action = resolve(SyncOrderShippingStatusAction::class); $action->execute($order); ``` The algorithm counts items by fulfillment status and determines the order shipping status. The first matching row wins, and an order without items is left unchanged: | Condition | Order Shipping Status | |-----------|----------------------| | All items cancelled | `Returned` | | Some cancelled, rest shipped/delivered | `PartiallyReturned` | | No items shipped or delivered | `Unfulfilled` | | All items delivered | `Delivered` | | Some items delivered | `PartiallyDelivered` | | All items shipped or delivered | `Shipped` | | Otherwise | `PartiallyShipped` | When the status transitions to `Shipped`, the `OrderShipped` event is dispatched. ## Events [#events] `OrderShipped` and `OrderShipmentDelivered` are dispatched by the actions above. `OrderShipmentCreated` is dispatched by the admin when a staff member creates a shipping label; creating a shipment in your own code does not dispatch it, so dispatch it yourself if your listeners need it: `OrderShipmentCreated::dispatch($order, $shipment)`. | Event | Dispatched When | Properties | |-------|-----------------|------------| | `OrderShipmentCreated` | A shipping label is created from the admin | `Order $order`, `OrderShipping $shipment` | | `OrderShipped` | Order `shipping_status` transitions to `Shipped` (`SyncOrderShippingStatusAction`) | `Order $order` | | `OrderShipmentDelivered` | A shipment is marked as delivered with `MarkShipmentDeliveredAction` | `Order $order`, `OrderShipping $shipment` | ```php use Shopper\Core\Events\Orders\OrderShipmentCreated; use Shopper\Core\Events\Orders\OrderShipped; use Shopper\Core\Events\Orders\OrderShipmentDelivered; ``` ## Storefront Example [#storefront-example] ### Order Tracking Page [#order-tracking-page] ```php namespace App\Http\Controllers; use Shopper\Core\Models\Order; class OrderTrackingController extends Controller { public function show(Order $order) { abort_unless($order->customer_id === auth()->id(), 403); $order->load([ 'items.shipment.carrier', 'shippings.carrier', 'shippings.items', ]); return view('orders.tracking', [ 'order' => $order, 'shipments' => $order->shippings->map(fn ($shipment) => [ 'carrier' => $shipment->carrier?->name, 'tracking_number' => $shipment->tracking_number, 'tracking_url' => $shipment->tracking_url, 'shipped_at' => $shipment->shipped_at, 'received_at' => $shipment->received_at, 'items' => $shipment->items->map(fn ($item) => [ 'name' => $item->name, 'quantity' => $item->quantity, 'status' => $item->fulfillment_status, ]), ]), ]); } } ``` ## Best Practices [#best-practices] | Practice | Description | |----------|-------------| | Update statuses atomically | Record shipment events with `RecordShipmentEventAction` so the shipment, its items and the order `shipping_status` change together | | Complete orders automatically | Let `RecordShipmentEventAction` complete the order on delivery; if you change item statuses yourself, check that all items are delivered and update the order status | | Group items by carrier | Items from the same supplier or warehouse should share a shipment | | Store tracking URLs | Always provide `tracking_url` so customers can track packages directly | | Handle mixed orders | Process your own products and supplier products as separate shipments | # Introduction (/2.x/getting-started) Shopper is an open-source headless e-commerce package for Laravel. It provides a production-ready admin panel, a flexible product catalog, and all the commerce logic your store needs, built on the tools you already know, without taking over your codebase. Shopper ## Why Shopper? [#why-shopper] There are several ways to add e-commerce to a Laravel application. You could integrate an external platform like Shopify, adopt a full e-commerce system like Lunar or Bagisto, or build everything from scratch. Each approach has trade-offs. Shopper takes a different path. It is a Laravel package, not a platform. You install it into your existing application the same way you would install `spatie/laravel-permission` or `laravel/cashier`. Your routes, your middleware, your authentication, your deploy pipeline stay unchanged. You add e-commerce to your app, not the other way around. ### Building Blocks, Not a Monolith [#building-blocks-not-a-monolith] Most e-commerce systems assume one-size-fits-all. But selling cars is not the same as selling sneakers, and a subscription box service has nothing in common with a marketplace. Shopper recognizes this by giving you composable building blocks instead of a rigid platform. The main Eloquent models (products, categories, orders and more) can be swapped for your own classes through configuration. The admin pages can be replaced with your own Livewire components. Optional sections such as brands, discounts or reviews can be turned off. You start with a production-ready foundation and shape it to match your business. ### Headless from Day One [#headless-from-day-one] Shopper handles the commerce logic and the admin panel. You build the storefront with whatever stack your team already ships with. Blade, Livewire, Inertia, Next.js, Nuxt, React Native, or anything else. Shopper has no opinion on how you present your store to customers. ### A Package, Not a Platform [#a-package-not-a-platform] This distinction matters. A platform owns your application. You build on top of it, adapt to its conventions, and work within its constraints. A package is a tool you control. Shopper adds e-commerce capabilities to your Laravel application without replacing your User model, your authentication system, or your application structure. Your User model gains Shopper capabilities through a trait. The admin panel is a feature of your app, not the other way around. Your database is extended, not replaced. ## Tech Stack [#tech-stack] Shopper is built on top of [Laravel](https://laravel.com), [Filament](https://filamentphp.com), and [Tailwind CSS](https://tailwindcss.com). The admin panel is made of [Livewire](https://livewire.laravel.com) pages that use Filament's tables, forms and actions. It is not a Filament panel plugin: it registers its own routes and layout. Although the admin panel uses Laravel Livewire, there is no requirement for the storefront to use Livewire. You can build your storefront with any stack. ## Packages [#packages] Shopper is made up of several Composer packages that work together. Installing `shopper/framework` pulls in `core`, `cart`, `payment`, `shipping` and `sidebar`: - `shopper/core` is the e-commerce engine: models, contracts, migrations, enums and observers. It has no dependency on any UI layer. - `shopper/framework` is the admin panel, for managing products, orders, customers, and more. It provides all Livewire pages and components, and adds media library support (through [Spatie Media Library](https://spatie.be/docs/laravel-medialibrary)) to products, variants, categories, brands and collections. - `shopper/cart` handles shopping carts and calculates their totals through a pipeline (lines, discounts, taxes). - `shopper/payment` provides a driver-based payment architecture. The official [Stripe](https://stripe.com) driver is a separate package, `shopper/stripe`, that you install with Composer. - `shopper/shipping` calculates shipping rates through drivers, with FedEx, UPS and USPS drivers included. Carriers and zones themselves are core models. - `shopper/sidebar` builds the admin panel navigation. You use it when you add your own entries to the [sidebar](/2.x/sidebar/overview). - `shopper/upgrade` is a temporary package for upgrades: an Artisan command for data fixes and [Laravel Boost](https://github.com/laravel/boost) skills that guide an AI assistant through breaking changes. You install it as a dev dependency when an [upgrade guide](/2.x/upgrade) asks for it, and remove it after. For storefront development, the npm package `@shopperlabs/shopper-types` provides TypeScript type definitions for Shopper's models. The `core` package defines contracts (interfaces) for its models. When you swap a model via configuration, the entire system (admin panel, relationships, route bindings) uses your custom class automatically. ## Key Features [#key-features] Shopper ships with everything you need to run an online store: Variants, attributes, media, and multiple product types (standard, virtual, external, variant). Full order lifecycle with independent payment, shipping, and order statuses. Unlimited hierarchical nesting with SEO fields and media. Manual or rule-based product grouping. Customer profiles, addresses, and order history. Discount codes with rules, conditions, and usage limits. Multi-warehouse stock tracking with allocation and audit trails. Carriers, zones, rates, and shipment tracking. Driver-based payment processing, with an official Stripe driver. Organize products by brand with media and SEO. Customer product reviews and ratings. Assign products to the sales channels they are sold on, such as a web store or a mobile app. ## Extensibility [#extensibility] Shopper is designed to be extended, not forked. Three mechanisms make this possible. **Model swapping** lets you replace a model with your own class that extends it. The twelve swappable models (products, variants, categories, brands, collections, orders, channels, inventories, suppliers, addresses, tax zones and tax rates) are listed in `config/shopper/models.php`. Point an entry to your class and the entire system uses it, including the admin panel, relationships, and route model binding. **Component overriding** lets you replace an admin panel page or form with your own Livewire component. Run `php artisan shopper:component:publish product` to get `config/shopper/components/product.php`, where each page and form of that section points to a class you can change. Pass `--all` to publish every section at once. **Feature toggling** lets you remove optional sections of the admin panel: attributes, brands, categories, collections, discounts, reviews, suppliers and tags. Set a feature to `FeatureState::Disabled` in `config/shopper/features.php` and its pages and menu entries disappear. ## Stability and Versioning [#stability-and-versioning] Shopper follows [Semantic Versioning](https://semver.org/). Minor and patch releases never contain breaking changes. Every component is tested, and upgrade guides are published for every major version bump. For details on supported versions and maintenance windows, see the [Version Support Policy](/2.x/version-support-policy). ## When Shopper Fits [#when-shopper-fits] Shopper is the right choice when you already have a Laravel application (or want to build one) and need to add e-commerce capabilities without adopting an opinionated platform. It works well when your storefront is non-standard: a product configurator, a subscription service, an auction site, or anything that does not fit the typical "browse and checkout" template. If you need a store running in an hour, Shopify is a better fit. If you are not in the Laravel ecosystem, MedusaJS is worth considering. ## Next Steps [#next-steps] Check server requirements before installing. Install Shopper in your Laravel application. Explore a working Shopper store. # Installation (/2.x/installation) Shopper requires an existing Laravel 11.28+, 12 or 13 application. If you do not have one yet, create a new Laravel project first by following the [Laravel installation guide](https://laravel.com/docs/installation). Check the [Requirements](/2.x/requirements) page before you start: Composer refuses to install Shopper while a required PHP extension, such as `intl`, is missing. ## Install the Package [#install-the-package] Install `shopper/framework` via Composer: ```bash composer require shopper/framework:"^2.0" ``` The package pulls in `shopper/core`, `shopper/cart`, `shopper/payment`, `shopper/shipping` and `shopper/sidebar`, along with Filament and Livewire. If you have a cached config from a previous setup, run `php artisan config:clear` before installing. ## Prepare Your User Model [#prepare-your-user-model] Shopper relies on your `User` model having certain relationships and methods for authentication, permissions, and admin panel access. In your existing User model, add the `InteractsWithShopper` trait, implement the `ShopperUser` interface and replace the fillable columns with the ones Shopper writes. Keep the other traits your model already uses: ```php title="app/Models/User.php" use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; class User extends Authenticatable implements ShopperUser { use InteractsWithShopper; use Notifiable; protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'phone_number', 'gender', 'birth_date', 'opt_in', 'email_verified_at', 'avatar_type', 'avatar_location', 'last_login_ip', ]; protected $hidden = [ 'password', 'remember_token', 'store_two_factor_secret', 'store_two_factor_recovery_codes', ]; } ``` The `InteractsWithShopper` trait provides roles and permissions, orders, addresses, discounts and the profile photo. Two-factor authentication needs two more contracts and traits, described on the [Two-Factor Authentication](/2.x/two-factor) page. The `ShopperUser` interface declares the methods the admin panel calls on the signed-in user, such as `isAdmin()` and `canAccessDashboard()`, and the setup wizard answers with a 403 error to a user whose model does not implement it. The admin panel creates and updates customers, team members and profiles with mass assignment, so the fillable list replaces Laravel's default `name`, `email` and `password`: the Shopper migrations rename the `name` column to `last_name`. `Notifiable` sends the login details to new customers and team members, and the password reset email. The two extra hidden attributes hold the two-factor authentication secret and recovery codes. ## Run the Installer [#run-the-installer] The install command publishes configuration files, creates the asset symlink, and optionally runs migrations and seeders: ```bash php artisan shopper:install ``` The installer performs these steps: 1. Publishes Shopper config files to `config/shopper/` 2. Publishes Spatie MediaLibrary migrations 3. Publishes Filament assets 4. Runs `php artisan shopper:link`, which links `public/cpanel` (or your configured prefix) to the panel assets in `vendor/shopper/framework/public` 5. Prompts you to run migrations and seed the database with roles, permissions, and default data (countries, currencies, legal pages, a sales channel, a carrier and payment methods) If `config/shopper/admin.php` already exists, the installer stops and prints the commands to publish the configuration and run the migrations by hand. It does not print the seeders: if the database has never been seeded, run the two seeders listed on the [Configuration](/2.x/configuration#database-table-prefix) page after the migrations. The migrations change your `users` table: the `name` column is renamed to `last_name` (or created when the table has none), `password` becomes nullable, and columns such as `first_name`, `gender`, `phone_number`, `birth_date`, `timezone` and `last_login_at` are added. Update any code, factory or form of your application that reads or writes `name` before you migrate. All Shopper database tables are prefixed with `sh_` by default to avoid conflicts with your existing tables. To use another prefix, answer no when the installer asks to run the migrations, change `table_prefix` in `config/shopper/core.php`, then run `php artisan migrate` and the two seeders listed on the [Configuration](/2.x/configuration#database-table-prefix) page. Product, variant, category, collection and brand images, profile photos and the store logo and cover are stored on the disk set by `storage.disk_name` in `config/shopper/media.php`, `public` by default. If your application has never run it, create the storage link so that they are served: ```bash php artisan storage:link ``` Shopper queues the assignment of a discount to its products and customers, and the product sync of automatic collections. A new Laravel application uses the `database` queue connection, so run a worker with `php artisan queue:work`, or these jobs never run. ## Create an Admin User [#create-an-admin-user] Create your first admin user to access the dashboard: ```bash php artisan shopper:user ``` The command prompts for an email, first name, last name, and password (at least 6 characters). The user is assigned the administrator role, which exists only once the seeders have run: if you skipped them in the installer, run them first. Without the role, the command prints an error but still saves the user, who then gets a 403 error in the admin panel. Run the seeders, then give the role to that user in `php artisan tinker`: ```php App\Models\User::query() ->where('email', 'admin@laravelshopper.dev') ->first() ->assignRole(config('shopper.admin.roles.admin')); ``` ## Access the Admin Panel [#access-the-admin-panel] If you are using [Laravel Herd](https://herd.laravel.com) or [Laravel Valet](https://laravel.com/docs/valet), visit your application at: ``` http://your-project.test/cpanel/login ``` If you are using `php artisan serve`, the admin panel is available at `http://localhost:8000/cpanel/login`. On the first login, Shopper redirects you to a setup wizard that asks for the store name and email, its country, the currencies it sells in, its address and, optionally, its social links. The admin panel opens once these are saved: until the store has an email and a street address, every admin page sends you back to the wizard. See [Setup Store](/2.x/setup-store) for what the wizard creates. The `/cpanel` prefix is configurable. See the [Configuration](/2.x/configuration) page for details. ## Next Steps [#next-steps] Customize the admin prefix, models, middleware, and settings. Learn about the dashboard components and how to customize them. Start building your product catalog. # Legal (/2.x/legal) As with any e-commerce site, it is important for users to know the terms and conditions and privacy policy that your site offers. This is for their own safety and yours as well. This section allows you to set up your pages for your privacy policy, refund policy, terms of use and shipping policy to be presented to customers. ## Model [#model] The model used is `Shopper\Core\Models\Legal`. It uses the `HasSlug` trait: a slug you assign is converted with `Str::slug()` and gets a `-1`, `-2` suffix when another page already uses it. The trait does not build the slug from the title. It also adds `Legal::findBySlug('privacy')`, which returns the page whether it is enabled or not and throws a `ModelNotFoundException` when no page has that slug. ### Database Schema [#database-schema] Legal pages are stored in the `sh_legals` table (`sh_` is the default [table prefix](/2.x/configuration#database-table-prefix)). | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `title` | string | no | - | Legal page title | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `content` | longtext | yes | null | Legal page content, HTML from the rich text editor | | `is_enabled` | boolean | no | false | Whether this legal page is published | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Components [#components] The components used to manage Legal pages are found in the component configuration file `config/shopper/components/setting.php`. To publish it in your application: ```bash php artisan shopper:component:publish setting ``` ```php use Shopper\Livewire; return [ 'pages' => [ // ... 'legal' => Livewire\Pages\Settings\LegalPage::class, // ... ], 'components' => [ // ... 'settings.legal.privacy' => Livewire\Components\Settings\Legal\Privacy::class, 'settings.legal.refund' => Livewire\Components\Settings\Legal\Refund::class, 'settings.legal.shipping' => Livewire\Components\Settings\Legal\Shipping::class, 'settings.legal.terms' => Livewire\Components\Settings\Legal\Terms::class, 'settings.legal.form' => Livewire\Components\Settings\Legal\PolicyForm::class, // ... ], ]; ``` `LegalPage` renders the tabs. Each tab component (`Privacy`, `Refund`, `Shipping`, `Terms`) shows the heading of its policy, and `PolicyForm` is the form the four tabs share. ## Add Legal content [#add-legal-content] In your admin panel, click **Settings** at the bottom of the sidebar, then **Legal**. The page is at `/{prefix}/setting/legal`, where the prefix is `config('shopper.admin.prefix')` (`cpanel` by default), and it requires the [`access_setting`](/2.x/acl#system-permissions) permission. The installer seeds four legal pages through `Shopper\Core\Database\Seeders\LegalsPageTableSeeder`, with the slugs `privacy`, `terms`, `shipping` and `refund`. Each one is a tab of this page: Privacy policy, Terms of use, Shipping policy and Refund policy. The admin panel edits these four pages and has no button to add or rename one. Write the content of each page, turn on the **Enabled** toggle and click **Save**. Only enabled pages are returned by `Legal::enabled()` in your front-end. The seeded pages start enabled and without content, and the form requires content to save, even to disable a page: write the content of a page before you link to it from your store. Shopper does not generate the routes for the legal pages, you should set them up yourself. As mentioned in the [introduction](/2.x/getting-started#headless-from-day-one) of this documentation, Shopper provides the admin panel and your application builds the storefront. ## Retrieve Data [#retrieve-data] Once the information is filled in, we can display it to our users in the views we have created. To do this we will start by creating a controller that will take care of collecting our information and send it to a view ```bash php artisan make:controller LegalController ``` We will add the functions for each of our pages and return the information to present them to our users. Our controller will look like this ```php namespace App\Http\Controllers; use Shopper\Core\Models\Legal; class LegalController extends Controller { public function privacy() { return view('legal.privacy', [ 'legal' => Legal::enabled()->where('slug', 'privacy')->firstOrFail(), ]); } public function refund() { return view('legal.refund', [ 'legal' => Legal::enabled()->where('slug', 'refund')->firstOrFail(), ]); } public function terms() { return view('legal.terms', [ 'legal' => Legal::enabled()->where('slug', 'terms')->firstOrFail(), ]); } public function shipping() { return view('legal.shipping', [ 'legal' => Legal::enabled()->where('slug', 'shipping')->firstOrFail(), ]); } } ``` `Legal::enabled()` is a scope that filters legal pages where `is_enabled` is `true`. This ensures draft pages are not shown to customers. `firstOrFail()` answers with a 404 when the page is disabled or the slug does not exist, so the view always receives a page. ### Routes [#routes] Once we have created the controllers we will associate the routes that will allow us to display our contents. We will display our content in the `web.php`. ```php use App\Http\Controllers\LegalController; use Illuminate\Support\Facades\Route; /* * Legal routes */ Route::get('/privacy', [LegalController::class, 'privacy'])->name('legal.privacy'); Route::get('/terms-of-use', [LegalController::class, 'terms'])->name('legal.terms'); Route::get('/refund-policy', [LegalController::class, 'refund'])->name('legal.refund'); Route::get('/shipping', [LegalController::class, 'shipping'])->name('legal.shipping'); ``` ### Views [#views] You can create views in this way to arrange the content of your legal pages. ```text resources/views/legal/ privacy.blade.php terms.blade.php refund.blade.php shipping.blade.php ``` It's just an idea of how to make your views, not a recommendation. If your front-end is in react, vue or svelte you will not necessarily have the same architecture. So keep in mind that it's just to display your content. Example of a view ```blade @extends('layouts.app') @section('body')

{{ __('Privacy Policy') }}

{{ __('Last update: :date', ['date' => $legal->updated_at->format('d, F Y')]) }}
{!! str($legal->content)->sanitizeHtml() !!}
@endsection ``` The content is the HTML saved by the rich text editor. `sanitizeHtml()` is a string helper registered by Filament, which the Shopper admin panel requires: it removes scripts and unsafe attributes before `{!! !!}` prints the HTML. # Locations (/2.x/locations) Locations represent physical places where you store inventory and ship orders from: warehouses, retail stores, fulfillment centers, or even your apartment. Each location has its own address and can track stock independently, so a product can have 50 units in your Paris warehouse and 20 in your New York store. When Shopper is first installed, the [setup wizard](/2.x/setup-store) creates a default location using your store's address. The initial quantity you enter when creating a product or variant in the admin is recorded at this location. If your business ships from multiple places, you can add more locations and assign stock to each one. ## Model [#model] The model used is `Shopper\Core\Models\Inventory`. It implements `Shopper\Core\Models\Contracts\Inventory` and is configurable via `config/shopper/models.php`. ### Extending the Model [#extending-the-model] To add custom behavior, extend the model and update your configuration: ```php namespace App\Models; use Shopper\Core\Models\Inventory as BaseInventory; class Inventory extends BaseInventory { } ``` Update `config/shopper/models.php`: ```php return [ 'inventory' => \App\Models\Inventory::class, ]; ``` ## Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Location name | | `code` | string | no | - | Unique identifier code | | `description` | text | yes | null | Location description | | `email` | string | no | - | Location contact email (unique) | | `street_address` | string | no | - | Street address | | `street_address_plus` | string | yes | null | Additional address line | | `postal_code` | string | no | - | Postal/ZIP code | | `city` | string | no | - | City | | `state` | string | yes | null | State/province/region | | `phone_number` | string | yes | null | Phone number | | `priority` | integer | no | 0 | Allocation order at checkout, lower values first | | `latitude` | decimal(11,5) | yes | null | GPS latitude | | `longitude` | decimal(10,5) | yes | null | GPS longitude | | `is_default` | boolean | no | false | Default location for stock | | `country_id` | bigint | yes | null | FK to countries table, set to null when the country is deleted | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Relationships [#relationships] ### Country [#country] Each location belongs to a country: ```php $location->country; // Country model ``` ### Inventory Histories [#inventory-histories] Every stock mutation (increase, decrease, set) on any product or variant creates an `InventoryHistory` record tied to a specific location. This is how Shopper tracks stock per location. ```php $location->histories; // Collection of InventoryHistory records ``` ## Query Scopes [#query-scopes] The `default` scope returns the location marked as the default inventory. The admin action `Shopper\Actions\Store\InitialQuantityInventory` uses it to record the initial quantity entered when creating a product or variant. With no default location, that initial quantity is not recorded. ```php use Shopper\Core\Models\Inventory; $defaultLocation = Inventory::query()->default()->first(); ``` ## How Locations Connect to Stock [#how-locations-connect-to-stock] When you call `mutateStock()`, `decreaseStock()`, or `setStock()` on a [product](/2.x/products#modifying-stock) or [variant](/2.x/product-variants#modifying-stock), you pass an `$inventoryId`. This ties the stock mutation to a specific location: ```php $product->mutateStock( inventoryId: $warehouse->id, quantity: 100, event: 'Shipment received', ); ``` `setStock()` works differently: it computes its delta from the total stock across all locations, then records that delta at the given location, as described in [Modifying Stock](/2.x/products#modifying-stock). To get stock for a product at a specific location: ```php $product->stockInventory($warehouse->id); ``` To batch-load stock for a specific location across multiple products (avoiding N+1): ```php use Shopper\Models\Product; $products = Product::query()->get(); Product::loadStockForInventory($products, $warehouse->id); ``` After this call, `$product->stock` returns the stock at that location, not the total. At checkout, Shopper reserves the stock of each line that tracks inventory, as described in [Stock Reservation](/2.x/cart#stock-reservation). Three services, bound in `Shopper\Core\CoreServiceProvider`, decide which locations the stock comes from: - `Shopper\Core\Stock\DefaultInventoryResolver` (contract `Shopper\Core\Contracts\InventoryResolver`) returns every location ordered by `priority`, lowest first, then by ID. It ignores `is_default`. - `Shopper\Core\Stock\PriorityStockAllocator` (contract `Shopper\Core\Contracts\StockAllocator`) takes the whole quantity from the first location that holds it. When no single location does, it splits the quantity across locations in the same order. - `Shopper\Core\Stock\LockingStockReserver` (contract `Shopper\Core\Contracts\StockReserver`) records one `decreaseStock()` movement per location, with the order as reference. When the locations together hold less than the quantity, it records nothing and the order is refused with `InsufficientStockException`. For a product with `allow_backorder` enabled, it takes the whole quantity from the first location returned by the resolver, whose stock goes negative. To change which locations an order draws from, or in which order, write your own resolver. This one tries the default location first, then the others by priority: ```php namespace App\Stock; use Illuminate\Database\Eloquent\Collection; use Shopper\Core\Contracts\InventoryResolver; use Shopper\Core\Models\Contracts\Stockable; use Shopper\Core\Models\Inventory; final class DefaultFirstInventoryResolver implements InventoryResolver { public function resolve(Stockable $product): Collection { return Inventory::query() ->orderByDesc('is_default') ->orderBy('priority') ->orderBy('id') ->get(); } } ``` Bind it in the `register` method of one of your service providers. The allocator and the reserver receive the resolver from the container, so they use yours: ```php use App\Stock\DefaultFirstInventoryResolver; use Shopper\Core\Contracts\InventoryResolver; $this->app->bind(InventoryResolver::class, DefaultFirstInventoryResolver::class); ``` ## Creating Locations [#creating-locations] To create a new warehouse location: ```php use Shopper\Core\Models\Inventory; use Shopper\Core\Models\Country; $france = Country::query()->where('cca2', 'FR')->first(); $warehouse = Inventory::query()->create([ 'name' => 'Paris Warehouse', 'code' => 'WH-PARIS', 'email' => 'paris@mystore.com', 'street_address' => '15 Rue du Commerce', 'city' => 'Paris', 'postal_code' => '75015', 'country_id' => $france->id, 'priority' => 1, 'latitude' => 48.8466, 'longitude' => 2.2958, ]); ``` ## Retrieving Locations [#retrieving-locations] To get the default location: ```php $default = Inventory::query()->default()->first(); ``` To get all locations ordered by priority: ```php $locations = Inventory::query() ->with('country') ->orderBy('priority') ->get(); ``` To find the nearest location to a customer (if latitude/longitude are set). This straight-line distance on coordinates is an approximation, enough to rank nearby locations: ```php $locations = Inventory::query() ->whereNotNull('latitude') ->whereNotNull('longitude') ->get() ->sortBy(function ($location) use ($customerLat, $customerLng) { return sqrt( pow($location->latitude - $customerLat, 2) + pow($location->longitude - $customerLng, 2) ); }); $nearest = $locations->first(); ``` ## Default Location [#default-location] The default location receives the initial quantity entered when you create a product or variant in the admin. It is not a fallback for stock operations: `mutateStock()`, `decreaseStock()` and `setStock()` always need an `$inventoryId`, and checkout allocation follows `priority`, not `is_default`. Only one location can be the default. When you create or update a location with `is_default` set to `true`, Shopper sets `is_default` to `false` on every other location. The admin does not show a delete button on the default location. Shopper does not take a shipping origin from your locations. When you request carrier rates, you build the `from` address yourself, and a location's address is the usual source, as shown in [Checkout Shipping Selection](/2.x/carriers#checkout-shipping-selection). Deleting a location removes all inventory history records tied to it. This affects stock levels for every product that had stock in that location. Proceed with caution. ## Components [#components] To customize the admin UI for location management: ```bash php artisan shopper:component:publish setting ``` Location-related components in `config/shopper/components/setting.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'location-index' => Livewire\Pages\Settings\Locations\Index::class, 'location-create' => Livewire\Pages\Settings\Locations\Create::class, 'location-edit' => Livewire\Pages\Settings\Locations\Edit::class, ], 'components' => [ 'settings.locations.form' => Livewire\Components\Settings\Locations\InventoryForm::class, ], ]; ``` # Media (/2.x/media) Shopper supports assigning images to products, variants, brands, collections and categories. It is an additional layer provided by the framework with the help of the [Spatie Media Library](https://spatie.be/docs/laravel-medialibrary/v11/introduction) ## Configuration [#configuration] The `config/shopper/media.php` file allows you to customize how media files are handled. The `shopper:install` command publishes it with the other Shopper configuration files, along with the Spatie Media Library migration that creates the `media` table. Below are the available configuration options: ### Storage Disk [#storage-disk] Specifies the storage disk used to save media files and the names of the media collections. By default, Shopper uses the `public` disk, but you can set `disk_name` to any disk of `config/filesystems.php`, such as S3, Cloudinary, or other storage systems. With the `public` disk, run `php artisan storage:link` so the image URLs resolve. Each model listed above has two Spatie Media Library collections: `collection_name` names the gallery, which holds several images, and `thumbnail_collection` names the thumbnail, which holds a single image (adding a new thumbnail replaces the previous one). ```php title="config/shopper/media.php" 'storage' => [ 'collection_name' => 'uploads', 'thumbnail_collection' => 'thumbnail', 'disk_name' => 'public', ] ``` Choose the collection names before the first upload: each row of the `media` table stores its collection name, so images uploaded under an old name no longer show after a rename. ### Accepts Mime Types [#accepts-mime-types] Lists the image MIME types that the gallery and thumbnail collections accept. Add a type to the list if your store needs another format. ```php title="config/shopper/media.php" 'accepts_mime_types' => [ 'image/jpeg', 'image/png', 'image/webp', 'image/avif', ] ``` This allowlist applies to the gallery and thumbnail collections of products, variants, brands, collections and categories, whether the file comes from the admin panel or from your code: Spatie Media Library throws `Spatie\MediaLibrary\MediaCollections\Exceptions\FileUnacceptableForCollection` for any other type. Since v2.11.2, it also applies to the account avatar and the store logo and cover in the settings. Before v2.11.2, those three settings fields accepted any `image/*` type regardless of this configuration. SVG is deliberately excluded from the default list. An SVG file can embed scripts that execute when the file is opened from your storage URL, which allows a staff account to attack an administrator session. Only add `image/svg+xml` back if you understand and accept that risk. ### Accepts File Types [#accepts-file-types] Lists the MIME types accepted by the `files` collection of products, which holds the downloadable files of virtual products (see [Downloadable Files](/2.x/products#downloadable-files)). The admin panel shows this upload field in the **Files** tab of a virtual product. HTML, SVG and JavaScript files are excluded from the default list for the same reason as SVG images. ```php title="config/shopper/media.php" 'accepts_file_types' => [ 'application/pdf', 'application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/plain', 'text/csv', ] ``` ### Media Filesize [#media-filesize] Sets the maximum file size of the admin panel upload fields, in kilobytes. This helps control file sizes to avoid performance issues. `thumbnail` applies to the thumbnail of products, variants, brands, categories and collections, and `images` to each gallery image of products and variants. ```php title="config/shopper/media.php" 'max_size' => [ 'thumbnail' => 1024, // Default size for thumbnail image (1MB). 'images' => 2048, // Default size for individual collection image for product (2MB) ] ``` These limits apply to the admin panel only, not to files you add from code with `addMedia()`. The account avatar and the store logo and cover have a fixed limit of 1024 KB, and the downloadable files of virtual products have no limit of their own. A file larger than PHP's `upload_max_filesize` or `post_max_size`, or than Livewire's temporary upload limit (12 MB by default, set in `livewire.temporary_file_upload.rules`), is refused before these limits apply: raise those too when you raise a value here. ### Image Conversions [#image-conversions] Configures image conversions to generate resized or optimized versions of uploaded images. For example, you can create thumbnails or mobile-friendly images. Each key is the name of a conversion, with its `width` and `height` in pixels. ```php title="config/shopper/media.php" 'conversions' => [ 'large' => [ 'width' => 800, 'height' => 800, ], 'medium' => [ 'width' => 500, 'height' => 500, ], ] ``` ## Image Conversions [#image-conversions-1] Shopper registers image conversions from the `config/shopper/media.php` `conversions` array on products, variants, brands, categories and collections. By default, two conversions are available: `large` (800x800) and `medium` (500x500). All conversions use `Fit::Fill`, which resizes the image to fit inside the width and height without cropping or distorting it and fills the remaining space with a background color, and all of them preserve the original image format. To add custom conversions, add entries to the `conversions` config: ```php 'conversions' => [ 'large' => ['width' => 800, 'height' => 800], 'medium' => ['width' => 500, 'height' => 500], 'small' => ['width' => 200, 'height' => 200], ], ``` Spatie Media Library generates the conversions after each upload, on the queue by default: run a queue worker, or set `QUEUE_CONVERSIONS_BY_DEFAULT=false` in your `.env` file to generate them during the upload. A new or changed conversion only applies to new uploads. To rebuild the conversions of the images already stored, run: ```bash php artisan media-library:regenerate ``` ## Retrieving Images [#retrieving-images] The media methods below come from Spatie Media Library. They exist on the `Shopper\Models` classes set in `config/shopper/models.php` (`Shopper\Models\Product`, `Shopper\Models\Brand` and the others), not on their `Shopper\Core\Models` parents. Query the configured model, or your own model that extends it (see [Model](/2.x/products#model)). To get the thumbnail URL for a product, variant, brand, category or collection: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $product->getFirstMediaUrl($collection); $product->getFirstMediaUrl($collection, 'medium'); ``` When the collection is empty, `getFirstMediaUrl()` returns the Shopper placeholder image, not an empty string. Check `$product->hasMedia($collection)` first if your storefront should show something else. To get gallery images: ```php $collection = config('shopper.media.storage.collection_name'); $product->getMedia($collection); $product->getFirstMediaUrl($collection); $largeImageUrls = $product->getMedia($collection) ->map(fn ($media) => $media->getUrl('large')); ``` ## Advanced Customization [#advanced-customization] If you need further customization, configure a custom disk in `config/filesystems.php` and update the `disk_name` in `config/shopper/media.php`. See the [Laravel Filesystem documentation](https://laravel.com/docs/filesystem) for details. The new disk applies to new uploads only: each row of the `media` table keeps the disk its file was stored on, in the `disk` and `conversions_disk` columns. On a live store, move the existing files and update those columns yourself. # Orders (/2.x/orders) Orders represent customer purchases and are central to your e-commerce operations. Shopper stores each order with its items, addresses, shipments, refund, and three statuses (order, payment, shipping). ## Models [#models] Shopper uses seven models to manage orders: | Model | Purpose | |-------|---------| | `Shopper\Core\Models\Order` | The main order with statuses, totals, and foreign keys | | `Shopper\Core\Models\OrderItem` | Products in the order with quantity, price, and fulfillment status | | `Shopper\Core\Models\OrderAddress` | Billing and shipping addresses snapshot | | `Shopper\Core\Models\OrderShipping` | Shipments with carrier, tracking, and delivery dates | | `Shopper\Core\Models\OrderShippingEvent` | Tracking events for each shipment (location, status changes) | | `Shopper\Core\Models\OrderTaxLine` | Tax breakdown per item or shipment | | `Shopper\Core\Models\OrderRefund` | Refund requests with status tracking | The Order model implements `Shopper\Core\Models\Contracts\Order` and uses `SoftDeletes`. It is configurable via `config/shopper/models.php`. ### Extending the Model [#extending-the-model] To add custom behavior, extend the model and update your configuration: ```php namespace App\Models; use Shopper\Core\Models\Order as BaseOrder; class Order extends BaseOrder { } ``` Update `config/shopper/models.php`: ```php return [ 'order' => \App\Models\Order::class, ]; ``` ## Database Schema [#database-schema] ### Order Table [#order-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `number` | string(32) | no | - | Order number | | `price_amount` | integer | yes | null | Order total in cents | | `tax_amount` | unsigned int | yes | null | Total tax in cents | | `status` | string(32) | no | - | Order status enum, set to `new` by the model | | `payment_status` | string(32) | no | pending | Payment status enum | | `shipping_status` | string(32) | no | unfulfilled | Shipping status enum | | `currency_code` | string | no | - | Currency code (USD, EUR, etc.) | | `notes` | text | yes | null | Order notes | | `metadata` | jsonb | yes | null | Custom key/value data | | `parent_order_id` | bigint | yes | null | FK to parent order | | `payment_method_id` | bigint | yes | null | FK to payment method | | `channel_id` | bigint | yes | null | FK to channel | | `customer_id` | bigint | yes | null | FK to user | | `zone_id` | bigint | yes | null | FK to zone | | `billing_address_id` | bigint | yes | null | FK to order address | | `shipping_address_id` | bigint | yes | null | FK to order address | | `shipping_option_id` | bigint | yes | null | FK to carrier option | | `discount_id` | bigint | yes | null | FK to the discount that was redeemed (nullOnDelete) | | `discount_code` | string | yes | null | Snapshot of the discount code at placement | | `discount_type` | string(32) | yes | null | Snapshot of the discount type (`percentage`/`fixed_amount`) | | `discount_value_at_apply` | unsigned int | yes | null | Snapshot of the discount value (cents for fixed amount, raw for percentage) | | `discount_currency_code` | char(3) | yes | null | Currency the discount was applied in | | `cancelled_at` | timestamp | yes | null | Cancellation date | | `archived_at` | timestamp | yes | null | Archive date | | `deleted_at` | timestamp | yes | null | Soft delete timestamp | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### OrderItem Table [#orderitem-table] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `name` | string | yes | Product name at time of purchase | | `sku` | string | yes | Product SKU at time of purchase | | `quantity` | integer | no | Quantity ordered | | `unit_price_amount` | integer | no | Unit price in cents | | `tax_amount` | integer | no | Tax amount in cents | | `discount_amount` | integer | no | Discount amount in cents | | `product_id` | bigint | no | Polymorphic relation ID | | `product_type` | string | no | Polymorphic relation type | | `order_id` | bigint | no | FK to order | | `order_shipping_id` | bigint | yes | FK to order_shipping (shipment) | | `fulfillment_status` | string | yes | Fulfillment status enum value | ### OrderAddress Table [#orderaddress-table] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `customer_id` | bigint | yes | FK to user | | `first_name` | string | no | First name | | `last_name` | string | no | Last name | | `company` | string | yes | Company name | | `street_address` | string | no | Street address | | `street_address_plus` | string | yes | Additional address line | | `postal_code` | string | no | Postal/ZIP code | | `city` | string | no | City | | `state` | string | yes | State/province/region | | `phone` | string | yes | Phone number | | `country_name` | string | yes | Country name | ### OrderShipping Table [#ordershipping-table] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `status` | string(32) | yes | Shipment status enum | | `shipped_at` | datetime | yes | Shipment date | | `received_at` | datetime | yes | Delivery date | | `returned_at` | datetime | yes | Return date | | `tracking_number` | string | yes | Carrier tracking number | | `tracking_url` | string | yes | Tracking URL | | `voucher` | json | yes | Shipping voucher data | | `order_id` | bigint | no | FK to order | | `carrier_id` | bigint | yes | FK to carrier | ### OrderRefund Table [#orderrefund-table] | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `reason` | text | yes | Refund reason | | `amount` | integer | no | Refund amount in cents | | `status` | string | no | Refund status enum | | `currency` | string | no | Currency code | | `notes` | text | yes | Admin notes | | `metadata` | jsonb | yes | Custom key/value data | | `order_id` | bigint | no | FK to order | | `user_id` | bigint | yes | FK to user, loaded with `$refund->customer` | ## Order Status [#order-status] Every order tracks three independent statuses: order status, payment status, and shipping status. This separation allows each aspect of the order to progress independently. For example, an order can be paid before it's shipped, or partially shipped while still processing. ### Order Status [#order-status-1] The `OrderStatus` enum tracks the overall lifecycle of the order: ```php use Shopper\Core\Enum\OrderStatus; OrderStatus::New // new (default) OrderStatus::Processing // processing OrderStatus::Completed // completed OrderStatus::Cancelled // cancelled OrderStatus::Archived // archived ``` | Status | Database Value | Color | Description | |--------|---------------|-------|-------------| | New | `new` | info | Newly placed order | | Processing | `processing` | primary | Order is being prepared | | Completed | `completed` | teal | Order finished | | Cancelled | `cancelled` | danger | Order cancelled | | Archived | `archived` | gray | Removed from active list | ### Payment Status [#payment-status] The `PaymentStatus` enum tracks whether payment has been collected. It is updated automatically by the [`PaymentProcessingService`](/2.x/payments#processing-payments) as transactions succeed. In the admin panel, the **Mark as paid** action of a pending or authorized order sets `Paid` directly: it does not call the payment driver and records no transaction. On an authorized Stripe payment, use **Capture payment** instead: once the order is `Paid`, the capture action is hidden and Shopper never captures the authorization (see [Status Transitions](/2.x/payments#status-transitions)). ```php use Shopper\Core\Enum\PaymentStatus; PaymentStatus::Pending // pending (default) PaymentStatus::Authorized // authorized PaymentStatus::Paid // paid PaymentStatus::PartiallyRefunded // partially_refunded PaymentStatus::Refunded // refunded PaymentStatus::Voided // voided ``` | Status | Database Value | Color | Description | |--------|---------------|-------|-------------| | Pending | `pending` | warning | Awaiting payment | | Authorized | `authorized` | info | Funds held, not yet captured | | Paid | `paid` | success | Funds collected | | Partially Refunded | `partially_refunded` | orange | Some amount refunded | | Refunded | `refunded` | gray | Full amount refunded | | Voided | `voided` | danger | Cancelled before capture | For the full payment lifecycle, capture strategies, and transaction recording, see the [Payments](/2.x/payments) page. ### Shipping Status [#shipping-status] The `ShippingStatus` enum tracks the overall shipping state at the order level. Shopper computes it from the fulfillment status of the order's items each time a shipment is picked up, delivered or returned (`Shopper\Core\Actions\SyncOrderShippingStatusAction`). ```php use Shopper\Core\Enum\ShippingStatus; ShippingStatus::Unfulfilled // unfulfilled (default) ShippingStatus::PartiallyShipped // partially_shipped ShippingStatus::Shipped // shipped ShippingStatus::PartiallyDelivered // partially_delivered ShippingStatus::Delivered // delivered ShippingStatus::PartiallyReturned // partially_returned ShippingStatus::Returned // returned ``` | Status | Database Value | Color | Description | |--------|---------------|-------|-------------| | Unfulfilled | `unfulfilled` | warning | No items shipped yet | | Partially Shipped | `partially_shipped` | info | Some items shipped | | Shipped | `shipped` | indigo | All items shipped | | Partially Delivered | `partially_delivered` | primary | Some packages delivered | | Delivered | `delivered` | success | All packages delivered | | Partially Returned | `partially_returned` | orange | Some items returned | | Returned | `returned` | gray | All items returned | For shipment-level tracking (individual packages with carriers and tracking numbers), see the [Fulfillment](/2.x/fulfillment) page. ### Status Check Methods [#status-check-methods] ```php $order->isNew(); // true if status is New $order->isProcessing(); // true if status is Processing $order->isCompleted(); // true if status is Completed $order->isArchived(); // true if status is Archived $order->isNotCancelled(); // true if status is NOT Cancelled $order->canBeCancelled(); // true if not Cancelled/Archived and no package is delivered or returned $order->isPaid(); // true if payment_status is Paid $order->isPaymentPending(); // true if payment_status is Pending $order->isPaymentAuthorized(); // true if payment_status is Authorized $order->isRefunded(); // true if payment_status is Refunded $order->isShipped(); // true if shipping_status is Shipped $order->isShippingPending(); // true if shipping_status is Unfulfilled ``` ## Fulfillment Status [#fulfillment-status] The `FulfillmentStatus` enum tracks individual item fulfillment, enabling partial shipments and multi-carrier delivery: ```php use Shopper\Core\Enum\FulfillmentStatus; FulfillmentStatus::Pending // pending FulfillmentStatus::ForwardedToSupplier // forwarded_to_supplier (dropshipping) FulfillmentStatus::Processing // processing FulfillmentStatus::Shipped // shipped FulfillmentStatus::Delivered // delivered FulfillmentStatus::Cancelled // cancelled ``` | Status | Database Value | Color | Description | |--------|---------------|-------|-------------| | Pending | `pending` | warning | Awaiting processing | | Forwarded to Supplier | `forwarded_to_supplier` | info | Sent to external supplier (dropshipping) | | Processing | `processing` | primary | Being prepared | | Shipped | `shipped` | indigo | In transit | | Delivered | `delivered` | success | Received by customer | | Cancelled | `cancelled` | danger | Fulfillment cancelled | `FulfillmentStatus` is applied per **item**, not per order. This allows partial fulfillment when items ship at different times or from different carriers. See the [Fulfillment](/2.x/fulfillment) page for complete workflows. ## Refund Status [#refund-status] The `OrderRefundStatus` enum defines refund states: ```php use Shopper\Core\Enum\OrderRefundStatus; OrderRefundStatus::Pending // pending (default) OrderRefundStatus::Awaiting // awaiting OrderRefundStatus::Treatment // treatment OrderRefundStatus::Partial_Refund // partial_refund OrderRefundStatus::Refunded // refunded OrderRefundStatus::Rejected // rejected OrderRefundStatus::Cancelled // cancelled ``` ## Relationships [#relationships] ### Customer [#customer] ```php $order->customer; Order::query() ->where('customer_id', $userId) ->get(); ``` ### Items [#items] ```php $order->items; ``` To add an item to an order, retrieve the product price for the order's currency: ```php $price = $product->getPrice($order->currency_code); $order->items()->create([ 'name' => $product->name, 'sku' => $product->sku, 'quantity' => 2, 'unit_price_amount' => $price->amount, 'product_id' => $product->id, 'product_type' => $product->getMorphClass(), ]); ``` ### Addresses [#addresses] ```php $order->shippingAddress; $order->billingAddress; $order->shippingAddress->full_name; ``` ### Shipping [#shipping] ```php $order->shippingOption; $order->shippings; ``` To create a shipment, link items to it, and record the carrier pickup: ```php use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\ShipmentStatus; $shipment = $order->shippings()->create([ 'carrier_id' => $carrierId, 'status' => ShipmentStatus::Pending, 'tracking_number' => '1Z999AA10123456784', 'tracking_url' => 'https://www.ups.com/track?tracknum=1Z999AA10123456784', ]); $order->items() ->whereIn('id', [$itemId1, $itemId2]) ->update(['order_shipping_id' => $shipment->id]); resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp); ``` Recording `PickedUp` sets `shipped_at`, moves the linked items from `Pending` to `Shipped`, moves a `New` order to `Processing`, and recomputes the order's `shipping_status`. Create the shipment with the `Pending` status: a shipment without a status can only move to `Pending`, so recording `PickedUp` on it does nothing. Record `InTransit` and `OutForDelivery` the same way, then call `Shopper\Core\Actions\MarkShipmentDeliveredAction`: it records `Delivered` and dispatches `OrderShipmentDelivered`. ### Item Shipment [#item-shipment] ```php $item->shipment; $item->shipment?->carrier; $shipment->items; ``` For complete multi-shipment and dropshipping workflows, see the [Fulfillment](/2.x/fulfillment) page. ### Refund [#refund] ```php $order->refund; ``` To create a refund: ```php use Shopper\Core\Enum\OrderRefundStatus; $order->refund()->create([ 'reason' => 'Product damaged', 'amount' => $order->total(), 'currency' => $order->currency_code, 'status' => OrderRefundStatus::Pending, ]); ``` ### Channel and Zone [#channel-and-zone] ```php $order->channel; $order->zone; ``` ### Discount [#discount] Orders snapshot the discount that was redeemed at placement time. The `discount_id` column points to the original discount while it exists and becomes `null` when that discount is deleted. The four snapshot columns (`discount_code`, `discount_type`, `discount_value_at_apply`, `discount_currency_code`) keep the data even after the discount is edited or deleted. This follows the Shopify pattern of immutable order records. The 2.x `Order` model has no `discount` relationship. Load the discount from its id: ```php use Shopper\Core\Models\Discount; $discount = Discount::query()->find($order->discount_id); $order->discount_code; $order->discount_type; $order->discount_value_at_apply; $order->discount_currency_code; ``` To find every order that redeemed a given discount: ```php use Shopper\Core\Models\Order; $orders = Order::query() ->where('discount_id', $discount->id) ->get(); ``` Shopper runs the same query with `->where('customer_id', $customerId)->exists()` to enforce the per-user usage limit. For the full validation and atomic reservation rules, see [Usage Limit Enforcement](/2.x/discounts#usage-limit-enforcement) on the Discounts page. ### Parent/Child Orders [#parentchild-orders] For split orders, an order can have a parent and children: ```php $order->parent; $order->children; ``` ## Computed Values [#computed-values] ### Order Total [#order-total] The `total()` method returns the sum of all item totals in cents: ```php $order->total(); ``` Each item's `total` is `unit_price_amount * quantity - discount_amount`, without tax. The `price_amount` column is a different value: the total computed at checkout by `CreateOrderFromCartAction`, which adds tax when your prices exclude it. Orders you create yourself only get a `price_amount` if you set it. ## Events [#events] Shopper dispatches these events during the order lifecycle. `OrderCreated`, `OrderDeleted` and `OrderItemCreated` fire on every Eloquent create or delete, whatever code runs it. `OrderShipped` fires when the order's `shipping_status` becomes `shipped`, and `OrderShipmentDelivered` fires from `MarkShipmentDeliveredAction`. The others fire from the order detail page of the admin panel: updating `status` or `payment_status` in your own code dispatches nothing. ```php use Shopper\Core\Events\Orders\OrderCreated; use Shopper\Core\Events\Orders\OrderItemCreated; use Shopper\Core\Events\Orders\OrderPaid; use Shopper\Core\Events\Orders\OrderShipped; use Shopper\Core\Events\Orders\OrderCompleted; use Shopper\Core\Events\Orders\OrderCancelled; use Shopper\Core\Events\Orders\OrderArchived; use Shopper\Core\Events\Orders\OrderDeleted; use Shopper\Core\Events\Orders\OrderShipmentCreated; use Shopper\Core\Events\Orders\OrderShipmentDelivered; use Shopper\Core\Events\Orders\OrderNoteAdded; ``` For the full events reference including shipment events, payload details, and usage examples, see the [Events](/2.x/events#order-events) page. ## Creating Orders [#creating-orders] ### Basic Order [#basic-order] ```php use Shopper\Core\Models\Order; use Shopper\Core\Enum\OrderStatus; $order = Order::query()->create([ 'number' => generate_number(), 'customer_id' => auth()->id(), 'currency_code' => shopper_currency(), 'channel_id' => $channelId, 'status' => OrderStatus::New, ]); ``` ### Complete Order with Items and Addresses [#complete-order-with-items-and-addresses] Create the shipping and billing addresses, then the order and its items from the cart lines: ```php use Shopper\Core\Models\Order; use Shopper\Core\Models\OrderAddress; $shippingAddress = OrderAddress::query()->create([ 'customer_id' => auth()->id(), 'first_name' => 'John', 'last_name' => 'Doe', 'street_address' => '123 Main St', 'city' => 'New York', 'state' => 'NY', 'postal_code' => '10001', 'country_name' => 'United States', 'phone' => '+1234567890', ]); $billingAddress = OrderAddress::query()->create([ 'customer_id' => auth()->id(), 'first_name' => 'John', 'last_name' => 'Doe', 'street_address' => '123 Main St', 'city' => 'New York', 'state' => 'NY', 'postal_code' => '10001', 'country_name' => 'United States', ]); $order = Order::query()->create([ 'number' => generate_number(), 'customer_id' => auth()->id(), 'currency_code' => $cart->currency_code, 'shipping_address_id' => $shippingAddress->id, 'billing_address_id' => $billingAddress->id, 'shipping_option_id' => $carrierOptionId, 'zone_id' => $zoneId, ]); foreach ($cart->lines as $line) { $order->items()->create([ 'name' => $line->purchasable->name, 'sku' => $line->purchasable->sku, 'quantity' => $line->quantity, 'unit_price_amount' => $line->unit_price_amount, 'product_id' => $line->purchasable_id, 'product_type' => $line->purchasable_type, ]); } ``` This example only copies the lines. To turn a cart into an order, use `CreateOrderFromCartAction` (see the [Storefront Example](#storefront-example)): it also sets `price_amount` and `tax_amount`, reserves stock and the discount, and writes the tax lines. ## Query Scopes [#query-scopes] The Order model provides two scopes for filtering by archive status: ```php Order::query()->archived()->get(); // Only archived orders Order::query()->notArchived()->get(); // Exclude archived orders ``` ## Retrieving Orders [#retrieving-orders] To get all non-archived orders with their relationships: ```php use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Models\Order; $orders = Order::query() ->notArchived() ->with(['customer', 'items', 'shippingAddress']) ->latest() ->get(); $newOrders = Order::query() ->where('status', OrderStatus::New) ->get(); ``` Query orders by customer with pagination: ```php $customerOrders = Order::query() ->where('customer_id', $customerId) ->with('items.product') ->latest() ->paginate(10); ``` Find an order by number: ```php $order = Order::query() ->where('number', $orderNumber) ->with(['items', 'shippingAddress', 'billingAddress', 'refund']) ->firstOrFail(); ``` ## Order Number Generation [#order-number-generation] Use the `generate_number()` helper to create the next order number: ```php $orderNumber = generate_number(); ``` This returns a formatted string like `ORD-20260327-001234`. The format is configurable under the `generator` key of `config/shopper/orders.php` (`config('shopper.orders.generator')`): | Key | Default | Description | |-----|---------|-------------| | `prefix` | `ORD` | Text before the number, `null` to remove it | | `separator` | `-` | Character between each part | | `date_format` | `Ymd` | PHP date format of the date part, `null` to remove it | | `start_sequence_from` | `1` | Added to the id of the last order to get the sequence | | `pad_length` | `6` | Length of the sequence after padding | | `pad_string` | `0` | Character used for padding | ## Permissions [#permissions] The admin panel generates five permissions for order management: | Permission | Description | |------------|-------------| | `browse_orders` | View the orders list | | `read_orders` | View a single order detail | | `add_orders` | Create new orders | | `edit_orders` | Edit existing orders | | `delete_orders` | Delete orders | ## Components [#components] To customize the admin UI for order management: ```bash php artisan shopper:component:publish order ``` Creates `config/shopper/components/order.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'order-index' => Livewire\Pages\Order\Index::class, 'order-detail' => Livewire\Pages\Order\Detail::class, 'order-shipments' => Livewire\Pages\Order\Shipments::class, 'order-abandoned-carts' => Livewire\Pages\Order\AbandonedCarts::class, ], 'components' => [ 'order-customer' => Livewire\Components\Orders\OrderCustomer::class, 'order-fulfillment' => Livewire\Components\Orders\Fulfillment::class, 'order-items' => Livewire\Components\Orders\OrderItems::class, 'order-notes' => Livewire\Components\Orders\OrderNotes::class, 'order-summary' => Livewire\Components\Orders\OrderSummary::class, 'slide-overs.create-shipping-label' => Livewire\SlideOvers\CreateShippingLabel::class, 'slide-overs.shipment-add-event' => Livewire\SlideOvers\ShipmentAddEvent::class, 'slide-overs.shipment-detail' => Livewire\SlideOvers\ShipmentDetail::class, 'slide-overs.abandoned-cart-detail' => Livewire\SlideOvers\AbandonedCartDetail::class, ], ]; ``` ## Storefront Example [#storefront-example] In most cases, orders are created automatically when a [cart is converted](/2.x/cart#converting-to-order) via `CreateOrderFromCartAction`. You rarely need to create orders manually. Here is how the checkout flow and order display work: ```php namespace App\Http\Controllers; use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Facades\Cart; use Shopper\Core\Models\Order; class CheckoutController extends Controller { public function store() { $cart = Cart::current(); abort_if($cart === null, 404); $order = resolve(CreateOrderFromCartAction::class)->execute($cart); Cart::forget(); return redirect()->route('orders.show', $order); } public function show(Order $order) { abort_unless($order->customer_id === auth()->id(), 403); return view('orders.show', [ 'order' => $order->load(['items.product', 'shippingAddress', 'billingAddress']), ]); } } ``` The `CreateOrderFromCartAction` handles everything in a single transaction: calculating totals, creating addresses, creating order items, reserving the discount and the stock, writing the tax lines, and marking the cart as completed. It throws `CartCompletedException` when the cart was already converted, `DiscountLimitReachedException` when the discount has reached a usage limit, and `InsufficientStockException` when the stock cannot cover a line (all in `Shopper\Cart\Exceptions`). It does not set `shipping_option_id`, because the 2.x cart has no shipping option: set it on the order yourself. See the [Cart](/2.x/cart#order-conversion) page for details. ## Order Status Flow [#order-status-flow] The order detail page of the admin panel offers these transitions: | From Status | Possible Transitions | |-------------|---------------------| | New | Processing, Cancelled, Archived | | Processing | Completed, Cancelled, Archived | | Completed | (terminal state) | | Cancelled | Archived | | Archived | (terminal state) | **Mark complete** needs a paid order. **Archive** is offered only while the order is unpaid. **Cancel Order** follows `canBeCancelled()`. **Mark as paid** also moves a `New` order to `Processing`. Shipments change the status too: the first pickup moves a `New` order to `Processing`, and once every item is delivered, a `Processing` order moves to `Completed`. The model itself does not block any transition when you update `status` in your own code. # Payment Methods (/2.x/payment-methods) Payment methods represent the ways customers can pay for their orders. Shopper provides a flexible system to manage multiple payment providers, each with its own driver, description, and customer-facing instructions. ## Model [#model] The model used is `Shopper\Core\Models\PaymentMethod`. It implements `Shopper\Core\Models\Contracts\PaymentMethod` and uses the `HasSlug` and `HasZones` traits. The model is not configurable via `config/shopper/models.php`. ## Database Schema [#database-schema] ### PaymentMethod Table [#paymentmethod-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `title` | string | no | - | Payment method name | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `logo` | string | yes | null | Not read by Shopper: the logo comes from the driver, see [Logo Handling](/2.x/payment-methods#logo-handling) | | `link_url` | string | yes | null | Payment provider website or documentation URL | | `description` | text | yes | null | Description displayed to customers when choosing a payment method | | `instructions` | text | yes | null | Instructions displayed to customers after placing an order | | `is_enabled` | boolean | no | false | Whether the method is active. Methods added in the admin start disabled | | `driver` | string | yes | null | Payment driver code (`manual`, `stripe` or a custom driver), added by `shopper/payment`. `null` is handled as `manual` | | `metadata` | jsonb | yes | null | Custom data. The model does not cast it, so it reads back as a JSON string | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The admin fills `slug` from the title. In code, the slug is not generated: pass it yourself. The `HasSlug` trait turns the value into a slug and appends `-1`, `-2` when it is already taken. ## Contract [#contract] The `PaymentMethod` contract defines the interface that all payment method models must implement: ```php namespace Shopper\Core\Models\Contracts; use Illuminate\Database\Eloquent\Relations\MorphToMany; interface PaymentMethod { public function zones(): MorphToMany; } ``` Payment methods use zones to control availability by geographic region. A payment method can be assigned to multiple zones, and a zone can have multiple payment methods. The `driver` column connects a payment method to a registered payment driver. `manual` is built in, `stripe` comes with the `shopper/stripe` package, and you add others with `Payment::extend()`. A `null` driver resolves to `manual`, and a code that no driver is registered under makes `Payment::driver()` throw an `InvalidArgumentException`. When the `PaymentProcessingService` processes a payment, it uses this value to resolve the correct driver. See [Payments](/2.x/payments) for driver registration and the full payment lifecycle. ## Relationships [#relationships] ### Zones [#zones] Payment methods can be scoped to specific geographic zones using the `HasZones` trait: ```php $paymentMethod->zones; $paymentMethod->zones()->attach([$zoneId1, $zoneId2]); $paymentMethod->zones()->detach($zoneId); ``` In the admin, payment methods are assigned to a zone from the zone form. From the zone side, use `$zone->paymentMethods` (see [Zones](/2.x/zones#payment-methods)). ### Orders [#orders] Orders reference payment methods via the `payment_method_id` foreign key: ```php $order->paymentMethod; ``` ```php Order::query() ->where('payment_method_id', $paymentMethod->id) ->get(); ``` The foreign key is nullable: deleting a payment method keeps its orders and sets their `payment_method_id` to `null`. ## Query Scopes [#query-scopes] ```php PaymentMethod::query()->enabled()->get(); ``` ## Logo Handling [#logo-handling] A payment method shows the logo of its driver. The `logo()` method returns the URL the driver provides (the `manual` and `stripe` drivers ship one), or `null` when the driver has none or `shopper/payment` is not installed. `PaymentProcessingService::getLogoUrl()` returns the same value: ```php use Shopper\Payment\Services\PaymentProcessingService; $paymentMethod->logo(); // Driver logo URL or null $service = resolve(PaymentProcessingService::class); $service->getLogoUrl($paymentMethod); // Same as $paymentMethod->logo() ``` The `logo` column is neither filled by the admin nor read by `logo()`. To show a logo for your own driver, return its URL from the driver's `logo()` method (see [Custom Drivers](/2.x/payments#custom-drivers)). ## Creating Payment Methods [#creating-payment-methods] ### Basic Payment Method [#basic-payment-method] The `stripe` driver needs the `shopper/stripe` package (see [Available Drivers](/2.x/payments#available-drivers)). Leave out `is_enabled` and the method is created disabled. ```php use Shopper\Core\Models\PaymentMethod; $paymentMethod = PaymentMethod::query()->create([ 'title' => 'Credit Card', 'slug' => 'credit-card', 'driver' => 'stripe', 'link_url' => 'https://stripe.com', 'description' => 'Pay securely with your credit or debit card.', 'instructions' => 'Your card will be charged immediately upon order confirmation.', 'is_enabled' => true, ]); ``` ### Cash on Delivery [#cash-on-delivery] ```php $cod = PaymentMethod::query()->create([ 'title' => 'Cash on Delivery', 'slug' => 'cash-on-delivery', 'driver' => 'manual', 'description' => 'Pay with cash when your order is delivered.', 'instructions' => 'Please have the exact amount ready for the delivery driver.', 'is_enabled' => true, ]); ``` ### Bank Transfer [#bank-transfer] ```php $bankTransfer = PaymentMethod::query()->create([ 'title' => 'Bank Transfer', 'slug' => 'bank-transfer', 'driver' => 'manual', 'description' => 'Pay via direct bank transfer.', 'instructions' => 'Please transfer the total amount to the following account: IBAN XX00 0000 0000 0000. Use your order number as the payment reference.', 'is_enabled' => true, ]); ``` ### Zone-Scoped Payment Method [#zone-scoped-payment-method] ```php $mobileMoney = PaymentMethod::query()->create([ 'title' => 'Mobile Money', 'slug' => 'mobile-money', 'link_url' => 'https://notchpay.co', 'description' => 'Pay with your mobile money wallet.', 'is_enabled' => true, ]); $mobileMoney->zones()->attach([$africaZoneId]); ``` ## Retrieving Payment Methods [#retrieving-payment-methods] ```php $methods = PaymentMethod::query()->enabled()->get(); ``` Find by slug: ```php $method = PaymentMethod::query() ->where('slug', 'credit-card') ->first(); ``` `PaymentMethod::findBySlug('credit-card')` from the `HasSlug` trait does the same, but throws a `ModelNotFoundException` when no method matches. Payment methods available in a specific zone: ```php $methods = PaymentMethod::query() ->enabled() ->whereHas('zones', fn ($q) => $q->where('zone_id', $zoneId)) ->get(); ``` `PaymentProcessingService::getMethodsForZone()` returns the zone's enabled methods whose driver is configured. It only returns methods attached to the zone (see [Payments](/2.x/payments#getting-available-payment-methods-for-a-zone)): ```php use Shopper\Payment\Services\PaymentProcessingService; $methods = resolve(PaymentProcessingService::class)->getMethodsForZone($zone); ``` Payment methods with no zone restriction (available everywhere): ```php $globalMethods = PaymentMethod::query() ->enabled() ->whereDoesntHave('zones') ->get(); ``` ## Working with Orders [#working-with-orders] When creating an order, associate it with the selected payment method: ```php use Shopper\Core\Models\Order; $order = Order::query()->create([ 'number' => $orderNumber, 'customer_id' => $customerId, 'payment_method_id' => $paymentMethod->id, // ... other order fields ]); $order->paymentMethod->title; $order->paymentMethod->instructions; ``` `CreateOrderFromCartAction` does not set `payment_method_id`. Set it on the order the action returns (see [Order Conversion](/2.x/cart#order-conversion)): ```php $order->update(['payment_method_id' => $paymentMethod->id]); ``` ## Storefront Example [#storefront-example] ### Checkout Payment Selection [#checkout-payment-selection] ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Shopper\Cart\Facades\Cart; use Shopper\Core\Models\PaymentMethod; use Shopper\Core\Models\Zone; class CheckoutController extends Controller { public function showPayment() { $zone = $this->getCustomerZone(); $paymentMethods = PaymentMethod::query() ->enabled() ->where(function ($query) use ($zone): void { $query->whereHas('zones', fn ($q) => $q->where('zone_id', $zone?->id)) ->orWhereDoesntHave('zones'); }) ->get(); return view('checkout.payment', compact('paymentMethods')); } public function storePayment(Request $request) { $paymentMethod = PaymentMethod::query()->enabled()->findOrFail( $request->input('payment_method_id') ); session()->put('checkout.payment_method_id', $paymentMethod->id); return redirect()->route('checkout.review'); } private function getCustomerZone(): ?Zone { $countryId = Cart::current()?->shippingAddress()?->country_id; if (! $countryId) { return null; } return Zone::query() ->enabled() ->whereHas('countries', fn ($q) => $q->where('id', $countryId)) ->first(); } } ``` In this example, payment methods without any zone are shown to all customers regardless of their location. `getMethodsForZone()` does not follow this rule: it only returns methods attached to the zone. ## Use Cases [#use-cases] Any of these can be a payment method. A method that charges online needs a driver: Shopper ships `manual` and `stripe`, and you write [custom drivers](/2.x/payments#custom-drivers) for the others. | Payment Method | Description | |----------------|-------------| | Credit Card | Online card payments via Stripe, PayPal, etc. | | Bank Transfer | Direct bank wire transfer | | Cash on Delivery | Payment at delivery time | | Mobile Money | Mobile wallet payments (M-Pesa, Orange Money, etc.) | | PayPal | PayPal account or guest checkout | | Cryptocurrency | Bitcoin, Ethereum, etc. | | Scenario | Implementation | |----------|----------------| | Single payment provider | Create one enabled payment method | | Region-specific methods | Use zones to restrict availability | | Offline payments | Use `instructions` field for post-order guidance | | Gateway documentation | Use `link_url` to reference provider docs | | Display at checkout | Query enabled methods filtered by customer zone | # Payments (/2.x/payments) The `shopper/payment` package handles payment processing through a driver-based architecture. It sits between your storefront and payment providers, giving you a single API to initiate, authorize, capture, and refund payments, regardless of which provider you use. Every payment operation that goes through the `PaymentProcessingService` is recorded as a transaction, whether it succeeds or fails. When an operation succeeds, the service also updates the order's payment status. ## How It Works [#how-it-works] The payment system has four main pieces: 1. **PaymentManager** resolves payment drivers by name (`manual`, `stripe` from `shopper/stripe`, or a custom driver such as `paypal`) 2. **PaymentDriver** is the contract every provider must implement 3. **PaymentProcessingService** wraps driver calls with transaction recording and status sync 4. **PaymentTransaction** stores every operation for audit and debugging ![Payment architecture showing how a payment flows from the Storefront through Shopper to the Payment Provider and back](/images/shared/payment-architecture.png) ## Payment Drivers [#payment-drivers] ### Available Drivers [#available-drivers] | Driver | Package | Code | Description | |--------|---------|------|-------------| | Manual | `shopper/payment` | `manual` | No API. For cash on delivery, bank transfers, etc. | | [Stripe](/2.x/addons/stripe) | `shopper/stripe` | `stripe` | Stripe PaymentIntents with 3D Secure support | `shopper/payment` is installed with the admin panel. The Stripe driver is a separate package: ```bash composer require shopper/stripe ``` It registers the `stripe` driver and reads its settings from `config('shopper.stripe')`. Set them in your `.env`, or publish `config/shopper/stripe.php` with `php artisan vendor:publish --tag=shopper-stripe-config`: ```dotenv STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_CAPTURE_METHOD=manual PAYMENT_STRIPE_ENABLED=true ``` The driver counts as configured once `STRIPE_SECRET_KEY` is set. `PAYMENT_STRIPE_ENABLED` only decides whether `Payment::configuredDrivers()` lists it. ### Using the Facade [#using-the-facade] The `Payment` facade gives you access to the driver manager: ```php use Shopper\Payment\Facades\Payment; $stripe = Payment::driver('stripe'); $manual = Payment::driver('manual'); $manual = Payment::driver(); Payment::availableDrivers(); Payment::configuredDrivers(); Payment::isConfigured('stripe'); ``` `driver()` without a name returns the `manual` driver, and throws an `InvalidArgumentException` for a code no package registered. `availableDrivers()` returns `manual` plus every code registered with `Payment::extend()`. `configuredDrivers()` keeps `manual` and the drivers whose `shopper.payment.drivers..enabled` config is `true`. `isConfigured()` asks the driver whether its credentials are set, and returns `false` for an unknown code. ### The PaymentDriver Contract [#the-paymentdriver-contract] Every driver implements `Shopper\Payment\Contracts\PaymentDriver`: | Method | Return | Purpose | |--------|--------|---------| | `code()` | `string` | Unique identifier (`stripe`, `paypal`, etc.) | | `name()` | `string` | Display name for the admin panel | | `logo()` | `?string` | URL to the provider's logo | | `isConfigured()` | `bool` | Whether API credentials are set | | `supportsWebhooks()` | `bool` | Whether the driver handles webhook events | | `supportsRefunds()` | `bool` | Whether the driver can process refunds | | `initiatePayment(int $amount, string $currency, array $context = [])` | `PaymentResult` | Create a payment session with the provider | | `authorizePayment(string $reference, array $data = [])` | `PaymentResult` | Confirm/authorize a payment | | `capturePayment(string $reference, ?int $amount = null)` | `PaymentResult` | Capture funds from an authorized payment | | `refundPayment(string $reference, int $amount, ?string $reason = null)` | `PaymentResult` | Refund a captured payment (full or partial) | | `cancelPayment(string $reference)` | `PaymentResult` | Cancel a payment before capture | | `retrievePayment(string $reference)` | `PaymentResult` | Check payment status from the provider | | `handleWebhook(array $payload, array $headers = [])` | `WebhookResult` | Process an incoming webhook event | Amounts are integers in cents. Shopper provides an abstract `Shopper\Payment\Drivers\Driver` class. Extend it and implement `code()`, `name()`, `isConfigured()` and `initiatePayment()`. The other operations throw `PaymentException::notSupported()` until you override them, `logo()` returns `null`, and `supportsWebhooks()` and `supportsRefunds()` return `true`: override them to return `false` when your driver does not handle webhooks or refunds. ## Processing Payments [#processing-payments] The `PaymentProcessingService` is the recommended way to process payments. It resolves the driver from the order's payment method and wraps every driver call with: - A `PaymentTransaction` row, with the status `success` or `failed` from the driver's result - An update of the order's `payment_status` when the operation succeeds The service does not catch exceptions. A driver that cannot complete the call throws a `PaymentException` (`StripeException` for Stripe, for an API error or a declined card), and no transaction is recorded for that call. Wrap the calls in `try`/`catch` where your storefront must show an error. ```php use Shopper\Payment\Services\PaymentProcessingService; $service = app(PaymentProcessingService::class); ``` ### Initiating a Payment [#initiating-a-payment] This is the first step in any payment flow. It creates a payment session with the provider and records an `initiate` transaction. It does not change the order's `payment_status`. `initiate()` charges the order's `price_amount` in its `currency_code`, with the driver of the order's payment method (`manual` when the method has no driver), so set `payment_method_id` on the order first. `CreateOrderFromCartAction` fills `price_amount` with the cart total (lines, discounts and taxes), which does not include shipping. The driver receives `order_number` and `order_id` in its context. Pass a second argument to add keys: the Stripe driver reads `payment_method`, `customer`, `metadata` and `idempotency_key`. Without an `idempotency_key`, each call creates a new PaymentIntent. ```php $result = $service->initiate($order, [ 'idempotency_key' => 'order-'.$order->number, ]); ``` Here's how the [demo store](https://demo.laravelshopper.dev) initiates a payment at checkout: ```php use Shopper\Payment\Services\PaymentProcessingService; $service = resolve(PaymentProcessingService::class); $result = $service->initiate($order); if (! $result->success) { session()->flash('error', $result->message ?? 'Payment initiation failed.'); return redirect()->route('order-confirmed', $order->number); } if ($result->clientSecret) { session()->put('stripe_payment', [ 'client_secret' => $result->clientSecret, 'publishable_key' => $result->data['publishable_key'], ]); return redirect()->route('stripe-payment', $order->number); } if ($result->redirectUrl) { return redirect($result->redirectUrl); } return redirect()->route('order-confirmed', $order->number); ``` The `PaymentResult` tells you what to do next: - **`clientSecret`** is set. Redirect the customer to a page with the Stripe.js Payment Element - **`redirectUrl`** is set. Redirect the customer to the provider (PayPal, 3D Secure, etc.) - **Neither**. The customer has nothing to do online. The manual driver, for example, returns the status `authorized` and a `manual_` reference: the money is collected outside Shopper (cash on delivery, bank transfer) ### Authorizing a Payment [#authorizing-a-payment] Confirms a previously initiated payment. On success, the order's `payment_status` is updated to `Authorized`. The Stripe driver confirms the PaymentIntent with the `payment_method` and `return_url` keys of the third argument. Pass `return_url` so that, when the bank asks for 3D Secure, `redirectUrl` holds the page to send the customer to. ```php $result = $service->authorize($order, $reference, [ 'payment_method' => 'pm_card_visa', 'return_url' => route('payment.callback', $order), ]); if ($result->requiresAction()) { return redirect($result->redirectUrl); } ``` ### Capturing a Payment [#capturing-a-payment] Captures an authorized payment. This is when funds are actually collected from the customer. On success, the order's `payment_status` is updated to `Paid`. Without `amount`, the full authorized amount is captured; pass an amount in cents to capture less. ```php $result = $service->capture($order, $reference); $result = $service->capture($order, $reference, amount: 5000); ``` ### Refunding a Payment [#refunding-a-payment] Refunds a captured payment. The service automatically determines whether the order becomes `PartiallyRefunded` or `Refunded` by comparing the total refunded amount against the order total. ```php $result = $service->refund( order: $order, reference: $reference, amount: 2000, reason: 'requested_by_customer', ); ``` `amount` is required, in cents. With Stripe, `reference` is the PaymentIntent ID (`pi_...`) returned by `initiate()`, and `reason` is sent to Stripe, which only accepts `duplicate`, `fraudulent` or `requested_by_customer`. The manual driver does not support refunds (`supportsRefunds()` returns `false`) and throws a `PaymentException`. ### Cancelling a Payment [#cancelling-a-payment] Cancels a payment that hasn't been captured yet. On success, the order's `payment_status` is updated to `Voided`. No funds are collected. ```php $result = $service->cancel($order, $reference); ``` The manual driver does not implement `cancelPayment()` and throws a `PaymentException`. ### Querying Transactions [#querying-transactions] ```php $transactions = $service->getTransactions($order); $reference = $service->getLatestReference($order); ``` `getTransactions()` returns the order's transactions, newest first. `getLatestReference()` returns the reference of the order's latest successful transaction, or `null`. After a Stripe refund, that reference is the refund ID (`re_...`), not the PaymentIntent. ### Getting Available Payment Methods for a Zone [#getting-available-payment-methods-for-a-zone] The service returns the zone's enabled payment methods whose driver is configured (a method without a driver uses `manual`, which is always configured): ```php $methods = $service->getMethodsForZone($zone); ``` This is used at checkout to show only the payment methods available in the customer's region. `getLogoUrl()` returns the logo of the method's driver. Here's how the demo store loads payment methods: ```php use Shopper\Core\Models\PaymentMethod; use Shopper\Core\Models\Zone; use Shopper\Payment\Services\PaymentProcessingService; $zone = Zone::query() ->whereHas('countries', fn ($q) => $q->where('id', $countryId)) ->where('is_enabled', true) ->first(); $service = resolve(PaymentProcessingService::class); $paymentMethods = $service->getMethodsForZone($zone) ->map(fn (PaymentMethod $method) => [ 'id' => $method->id, 'title' => $method->title, 'description' => $method->description, 'logo' => $service->getLogoUrl($method), ]) ->values() ->all(); ``` ## Data Transfer Objects [#data-transfer-objects] ### PaymentResult [#paymentresult] Every driver operation returns a `PaymentResult`. This is an immutable object that carries the outcome of the operation. ```php use Shopper\Payment\DataTransferObjects\PaymentResult; $result->success; // Did the operation succeed? $result->status; // Status set by the driver (pending, requires_action, authorized, captured, canceled, failed, etc.) $result->reference; // Provider reference ID (Stripe PaymentIntent ID, etc.) $result->clientSecret; // For frontend SDKs (Stripe.js, etc.) $result->redirectUrl; // For 3D Secure, PayPal redirect, etc. $result->amount; // Amount in cents $result->message; // Error message on failure $result->data; // Extra driver data (Stripe: stripe_status, publishable_key, etc.) $result->requiresAction(); // True when redirectUrl is set or the status is requires_action $result->toArray(); // Convert to array for JSON responses PaymentResult::failed('Card declined', $reference); ``` ### WebhookResult [#webhookresult] Webhook handlers return a `WebhookResult` that tells you what happened on the provider side: ```php use Shopper\Payment\DataTransferObjects\WebhookResult; $result->action; // What happened: authorized, captured, failed, canceled, refunded, ignored $result->reference; // Provider reference ID $result->amount; // Amount in cents $result->data; // Additional event data $result->isIgnored(); // True for unhandled event types $result->toArray(); // Convert to array WebhookResult::ignored(); // Create an ignored result ``` Shopper 2.x does not register a webhook route and does not update orders from webhooks: your app receives the request, passes it to the driver, and acts on the result. The Stripe driver verifies the signature with `STRIPE_WEBHOOK_SECRET`. It needs the raw request body under the `_raw_body` key and the `stripe-signature` header as a string, and throws a `StripeException` when either is missing or the signature does not match. For a PaymentIntent event, `reference` is the PaymentIntent ID, the same reference as the order's `initiate` transaction: ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use Shopper\Core\Enum\PaymentStatus; use Shopper\Payment\Exceptions\PaymentException; use Shopper\Payment\Facades\Payment; use Shopper\Payment\Models\PaymentTransaction; final class StripeWebhookController { public function __invoke(Request $request): Response { try { $result = Payment::driver('stripe')->handleWebhook( payload: ['_raw_body' => $request->getContent()], headers: ['stripe-signature' => (string) $request->header('Stripe-Signature')], ); } catch (PaymentException) { return response('Invalid payload', 400); } if ($result->isIgnored()) { return response('Ignored'); } $order = PaymentTransaction::query() ->where('reference', $result->reference) ->first() ?->order; $status = match ($result->action) { 'authorized' => PaymentStatus::Authorized, 'captured' => PaymentStatus::Paid, 'canceled' => PaymentStatus::Voided, default => null, }; if ($order !== null && $status !== null) { $order->update(['payment_status' => $status]); } return response('OK'); } } ``` The Stripe driver maps `payment_intent.amount_capturable_updated` to `authorized`, `payment_intent.succeeded` to `captured`, `payment_intent.payment_failed` to `failed`, `payment_intent.canceled` to `canceled`, and `charge.refunded` to `refunded`, where `amount` is the total refunded on the charge. Every other event is `ignored`. ## Payment Status [#payment-status] The `PaymentStatus` enum on the Order model tracks the overall payment state. It is updated automatically by the `PaymentProcessingService` as transactions succeed. ```php use Shopper\Core\Enum\PaymentStatus; PaymentStatus::Pending // Awaiting payment PaymentStatus::Authorized // Funds held, not yet captured PaymentStatus::Paid // Funds collected PaymentStatus::PartiallyRefunded // Some amount refunded PaymentStatus::Refunded // Full amount refunded PaymentStatus::Voided // Cancelled before capture ``` ### Status Transitions [#status-transitions] The service sets the status from the operation that succeeded, without checking the current status. `initiate` and failed operations leave it unchanged. A payment the customer confirms with Stripe.js changes nothing on the order until your code calls the service or handles the [webhook](/2.x/payments#webhookresult). In the admin panel, the **Mark as paid** action of a pending or authorized order sets `Paid` directly: it does not call the driver and records no transaction. On an authorized Stripe payment, use **Capture payment** instead: once the order is `Paid`, the capture action is hidden and Shopper never captures the authorization. | From | To | When | |------|----|------| | Pending | Authorized | `authorize` succeeds | | Pending | Paid | `capture` succeeds on an order never authorized through the service (payment confirmed with Stripe.js, manual driver) | | Pending | Voided | `cancel` succeeds | | Authorized | Paid | `capture` succeeds | | Authorized | Voided | `cancel` succeeds | | Paid | Partially Refunded | Partial `refund` succeeds | | Paid | Refunded | Full `refund` succeeds | | Partially Refunded | Refunded | Remaining amount refunded | ## Transaction Model [#transaction-model] Every payment operation is recorded as a `PaymentTransaction`: ```php Shopper\Payment\Models\PaymentTransaction ``` ### Database Schema [#database-schema] The table is `payment_transactions`, with the [table prefix](/2.x/configuration#database-table-prefix). | Column | Type | Description | |--------|------|-------------| | `id` | bigint | Primary key | | `driver` | string | Driver code (`stripe`, `manual`, etc.) | | `type` | string | Operation type (initiate, authorize, capture, refund, cancel) | | `status` | string | Result (pending, success, failed) | | `amount` | integer | Amount in cents | | `currency_code` | string(3) | ISO currency code | | `reference` | string | Provider reference ID (nullable, indexed) | | `data` | json | The `data` of the driver's `PaymentResult` (nullable) | | `notes` | text | The `message` of the driver's `PaymentResult`, such as the failure reason (nullable) | | `metadata` | json | Custom data (nullable) | | `order_id` | bigint | FK to order (nullable, set to null when the order is deleted) | | `payment_method_id` | bigint | FK to payment method (nullable, set to null when the method is deleted) | | `created_at` | timestamp | Creation timestamp | | `updated_at` | timestamp | Last update timestamp | ### Enums [#enums] ```php use Shopper\Payment\Enum\TransactionType; TransactionType::Initiate // Payment session created TransactionType::Authorize // Payment authorized TransactionType::Capture // Funds collected TransactionType::Refund // Funds returned TransactionType::Cancel // Payment voided ``` ```php use Shopper\Payment\Enum\TransactionStatus; TransactionStatus::Pending // In progress TransactionStatus::Success // Completed TransactionStatus::Failed // Failed ``` ### Querying Transactions [#querying-transactions-1] ```php use Shopper\Payment\Enum\TransactionType; use Shopper\Payment\Models\PaymentTransaction; PaymentTransaction::query()->successful()->get(); PaymentTransaction::query()->forDriver('stripe')->get(); PaymentTransaction::query()->ofType(TransactionType::Capture)->get(); $order->paymentTransactions; $transaction->isSuccessful(); $transaction->order; $transaction->paymentMethod; ``` The `paymentTransactions` relationship is registered automatically when the payment package is installed. ## Capture Methods [#capture-methods] Shopper supports two capture strategies. This determines _when_ the customer's funds are actually collected. The Stripe driver reads its strategy from `config('shopper.stripe.capture_method')` (`STRIPE_CAPTURE_METHOD`): `manual` (the default) or `automatic`. ### Manual Capture (Authorize-then-Capture) [#manual-capture-authorize-then-capture] Recommended for physical goods. Funds are held on the customer's card at checkout but only collected when you decide to capture. ![Checkout Authorize flow: customer places order, Shopper initiates payment with capture_method manual, provider holds funds, transaction recorded as authorized](/images/shared/checkout-autorize.png) This gives you the flexibility to: - Verify stock availability before collecting payment - Cancel an order without processing a refund (and without refund fees) - Capture only when the order is ready to ship When the order is ready to ship, the merchant captures the payment from the admin panel. The "Capture payment" action on the order page shows when the order's `payment_status` is `authorized` and the user has the `edit_orders` permission. It captures the full amount on the reference returned by `getLatestReference()`: ![Capture flow: merchant clicks Capture on order detail, Shopper calls capturePayment on the provider, funds are transferred, transaction recorded as captured and order marked as Paid](/images/shared/capture.png) ### Automatic Capture [#automatic-capture] Funds are collected immediately when the customer confirms payment. Use this for digital products, subscriptions, or when fulfillment is instant. Manual capture is the default for the Stripe driver. Authorization holds typically last 7 days (varies by card network), so you must capture within that window or the hold is released automatically. ## Custom Drivers [#custom-drivers] You can create drivers for any payment provider: PayPal, Mollie, Razorpay, NotchPay, etc. ### Step 1: Create the Driver Class [#step-1-create-the-driver-class] Extend the abstract `Driver` class and implement the methods your provider supports: ```php namespace App\Payment\Drivers; use Illuminate\Support\Facades\Http; use Shopper\Payment\DataTransferObjects\PaymentResult; use Shopper\Payment\DataTransferObjects\WebhookResult; use Shopper\Payment\Drivers\Driver; use Shopper\Payment\Exceptions\PaymentException; final class PayPalDriver extends Driver { public function __construct( private readonly string $clientId, private readonly string $clientSecret, private readonly bool $sandbox = false, ) {} public function code(): string { return 'paypal'; } public function name(): string { return 'PayPal'; } public function logo(): string { return asset('images/payments/paypal.svg'); } public function isConfigured(): bool { return filled($this->clientId) && filled($this->clientSecret); } public function initiatePayment(int $amount, string $currency, array $context = []): PaymentResult { if (! $this->isConfigured()) { throw PaymentException::notConfigured('paypal'); } $response = Http::withToken($this->getAccessToken()) ->post($this->baseUrl().'/v2/checkout/orders', [ 'intent' => 'AUTHORIZE', 'purchase_units' => [[ 'amount' => [ 'currency_code' => mb_strtoupper($currency), 'value' => number_format($amount / 100, 2, '.', ''), ], 'reference_id' => $context['order_number'] ?? null, ]], ]); if ($response->failed()) { throw PaymentException::apiError('paypal', $response->body()); } $data = $response->json(); $approveUrl = collect($data['links']) ->firstWhere('rel', 'approve')['href'] ?? null; return new PaymentResult( success: true, status: 'pending', reference: $data['id'], redirectUrl: $approveUrl, amount: $amount, ); } public function capturePayment(string $reference, ?int $amount = null): PaymentResult { $response = Http::withToken($this->getAccessToken()) ->post($this->baseUrl()."/v2/checkout/orders/{$reference}/capture"); if ($response->failed()) { throw PaymentException::apiError('paypal', $response->body()); } $data = $response->json(); return new PaymentResult( success: $data['status'] === 'COMPLETED', status: 'captured', reference: $reference, amount: $amount, ); } public function handleWebhook(array $payload, array $headers = []): WebhookResult { return match ($payload['event_type'] ?? '') { 'PAYMENT.CAPTURE.COMPLETED' => new WebhookResult( action: 'captured', reference: $payload['resource']['supplementary_data']['related_ids']['order_id'] ?? null, amount: (int) round((float) ($payload['resource']['amount']['value'] ?? 0) * 100), ), default => WebhookResult::ignored(), }; } private function baseUrl(): string { return $this->sandbox ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com'; } private function getAccessToken(): string { return Http::asForm() ->withBasicAuth($this->clientId, $this->clientSecret) ->post($this->baseUrl().'/v1/oauth2/token', ['grant_type' => 'client_credentials']) ->json('access_token'); } } ``` The example keeps `handleWebhook()` short and skips the signature check. A production driver must verify the provider's signature first and throw `PaymentException::webhookVerificationFailed('paypal')` when it does not match. ### Step 2: Register the Driver [#step-2-register-the-driver] In a service provider, use `Payment::extend()` to register your driver. The closure is called lazily, only when the driver is first accessed. Once registered, the driver is listed by `Payment::availableDrivers()` and in the driver select of the admin payment methods settings. ```php namespace App\Providers; use App\Payment\Drivers\PayPalDriver; use Illuminate\Support\ServiceProvider; use Shopper\Payment\Facades\Payment; class PaymentServiceProvider extends ServiceProvider { public function boot(): void { Payment::extend('paypal', fn (): PayPalDriver => new PayPalDriver( clientId: (string) config('shopper.payment.drivers.paypal.credentials.client_id'), clientSecret: (string) config('shopper.payment.drivers.paypal.credentials.client_secret'), sandbox: (bool) config('shopper.payment.drivers.paypal.sandbox', false), )); } } ``` ### Step 3: Add Configuration [#step-3-add-configuration] Add the driver credentials under `drivers` in `config/shopper/payment.php`. The file is published by `php artisan shopper:install`, or by `php artisan vendor:publish --tag=shopper-config`, and already ships a `paypal` entry: ```php 'drivers' => [ 'paypal' => [ 'enabled' => env('PAYMENT_PAYPAL_ENABLED', false), 'sandbox' => env('PAYMENT_SANDBOX', false), 'credentials' => [ 'client_id' => env('PAYPAL_CLIENT_ID'), 'client_secret' => env('PAYPAL_CLIENT_SECRET'), 'webhook_id' => env('PAYPAL_WEBHOOK_ID'), ], ], ], ``` The `enabled` key decides whether `Payment::configuredDrivers()` lists the driver. And in your `.env`: ```dotenv PAYMENT_PAYPAL_ENABLED=true PAYMENT_SANDBOX=true PAYPAL_CLIENT_ID=your-client-id PAYPAL_CLIENT_SECRET=your-client-secret ``` ### Step 4: Create the Payment Method [#step-4-create-the-payment-method] Link the driver to a payment method record. This is what makes it selectable at checkout: ```php use Shopper\Core\Models\PaymentMethod; $paypal = PaymentMethod::query()->create([ 'title' => 'PayPal', 'slug' => 'paypal', 'driver' => 'paypal', 'description' => 'Pay with your PayPal account.', 'is_enabled' => true, ]); $paypal->zones()->attach($zone); ``` `getMethodsForZone()` only returns the methods attached to the zone. The `driver` column connects this payment method to your registered driver. When a customer selects "PayPal" at checkout and the `PaymentProcessingService` processes the order, it resolves the `paypal` driver and calls `initiatePayment()`. ## Payment Method Model [#payment-method-model] The `Shopper\Core\Models\PaymentMethod` model represents a payment option available at checkout. Each method is linked to a driver (`manual`, `stripe` once `shopper/stripe` is installed, or a [custom driver](/2.x/payments#custom-drivers) such as the PayPal one above) and can be scoped to specific [zones](/2.x/zones). | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `title` | string | no | Display name | | `slug` | string | yes | URL-friendly identifier (unique) | | `logo` | string | yes | Logo path. The admin and `getLogoUrl()` show the driver's logo instead | | `driver` | string | yes | Driver code linking to a registered payment driver (`null` means `manual`) | | `is_enabled` | boolean | no | Whether the method is active (default `false`) | | `description` | text | yes | Description shown at checkout | | `link_url` | string | yes | External payment URL | | `instructions` | text | yes | Post-purchase instructions | | `metadata` | jsonb | yes | Additional custom data | The model uses the `HasSlug` trait and the `HasZones` trait for zone-based availability. `HasSlug` turns the slug you set into a unique slug (`paypal`, then `paypal-1`): ```php use Shopper\Core\Models\PaymentMethod; PaymentMethod::query()->enabled()->get(); $method = PaymentMethod::findBySlug('paypal'); $method->zones; $method->zones()->attach([$zoneId1, $zoneId2]); ``` ## Storefront Checkout Example [#storefront-checkout-example] Here is a complete checkout flow showing how the demo store creates an order and processes payment. ### Checkout Session [#checkout-session] The checkout wizard stores each step's data in the session: ```php final class CheckoutSession { public const string KEY = 'checkout'; public const string SHIPPING_ADDRESS = 'checkout.shipping_address'; public const string BILLING_ADDRESS = 'checkout.billing_address'; public const string SAME_AS_SHIPPING = 'checkout.same_as_shipping'; public const string SHIPPING_OPTION = 'checkout.shipping_option'; public const string PAYMENT = 'checkout.payment'; } ``` ### Creating the Order [#creating-the-order] After the customer completes the checkout steps, convert the [cart to an order](/2.x/cart#converting-to-order) and set the payment method: ```php use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Facades\Cart; $order = resolve(CreateOrderFromCartAction::class)->execute(Cart::current()); $order->update([ 'payment_method_id' => session('checkout.payment.0.id'), 'shipping_option_id' => session('checkout.shipping_option.0.id'), ]); Cart::forget(); ``` ### Processing the Payment [#processing-the-payment] Once the order exists, initiate the payment and handle the result: ```php use Shopper\Payment\Services\PaymentProcessingService; $service = resolve(PaymentProcessingService::class); $result = $service->initiate($order); session()->forget(CheckoutSession::KEY); if ($result->clientSecret) { session()->put('stripe_payment', [ 'client_secret' => $result->clientSecret, 'publishable_key' => $result->data['publishable_key'], ]); return redirect()->route('stripe-payment', $order->number); } if ($result->redirectUrl) { return redirect($result->redirectUrl); } return redirect()->route('order-confirmed', $order->number); ``` ### Routes [#routes] ```php use App\Http\Controllers\StripeWebhookController; Route::middleware('auth')->group(function (): void { Route::get('/checkout', Checkout::class)->name('checkout'); Route::get('/payment/{number}', StripePayment::class)->name('stripe-payment'); Route::get('/order/confirmed/{number}', OrderConfirmed::class)->name('order-confirmed'); }); Route::post('/webhooks/stripe', StripeWebhookController::class); ``` Stripe cannot send a CSRF token, so exclude the webhook route from CSRF verification in `bootstrap/app.php`: ```php use Illuminate\Foundation\Configuration\Middleware; ->withMiddleware(function (Middleware $middleware): void { $middleware->validateCsrfTokens(except: [ 'webhooks/stripe', ]); }) ``` # Pricing (/2.x/pricing) Shopper supports multi-currency pricing for [products](/2.x/products) and [product variants](/2.x/product-variants). Each priceable model can have one price per currency, stored in a shared `prices` table through a polymorphic relationship. Prices are stored in **cents** following the Stripe/Shopify standard. ## Money Storage Standard [#money-storage-standard] All monetary values are stored as integers in **cents**. $29.99 is stored as `2999` cents. For zero-decimal currencies (XAF, JPY, KRW), the value is stored as-is since the currency has no subdivision (15000 FCFA is stored as `15000`). ```php $product->prices()->create(['amount' => 2999, 'currency_id' => $usdCurrency->id]); $product->prices()->create(['amount' => 15000, 'currency_id' => $xafCurrency->id]); ``` ### Display [#display] Use `shopper_money_format()` to convert cents to a human-readable format. The helper divides by 100 for standard currencies and passes zero-decimal currencies through unchanged. It uses Laravel's `Number::currency()` with the application locale, so the output follows `app()->getLocale()`. When you omit the currency, it uses the store's default currency from `shopper_currency()`. ```php shopper_money_format(2999, 'USD'); // "$29.99" shopper_money_format(15000, 'XAF'); // "FCFA 15,000" with the "en" locale, "15 000 FCFA" with "fr" shopper_money_format(2999); // Formatted in the store's default currency ``` ### Default Currency [#default-currency] The `shopper_currency()` helper returns the store's default currency code. It reads the `default_currency_id` setting, looks up the currency code, caches it for one hour, and falls back to `'USD'` if no default is configured or the default currency is disabled. Saving the default currency in the admin settings clears this cache. ```php shopper_currency(); // "USD" ``` ### Zero-Decimal Currencies [#zero-decimal-currencies] These helpers let you check whether a currency uses decimal subdivisions. The list holds BIF, CLP, DJF, GNF, HTG, JPY, KMF, KRW, MGA, PYG, RWF, VND, VUV, XAF, XAG, XAU, XDR, XOF and XPF. Every other currency is divided by 100. ```php zero_decimal_currencies(); // ['BIF', 'CLP', 'DJF', 'GNF', 'HTG', 'JPY', ...] is_no_division_currency('XAF'); // true is_no_division_currency('USD'); // false ``` ## Price Model [#price-model] The model used is `Shopper\Core\Models\Price`. It implements `Shopper\Core\Models\Contracts\Price` and is not configurable via `config/shopper/models.php`. ### Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `priceable_type` | string | no | - | Morph alias: `product` or `variant` | | `priceable_id` | bigint | no | - | Foreign key to the priceable model | | `amount` | integer (unsigned) | yes | null | Selling price in cents, indexed | | `compare_amount` | integer (unsigned) | yes | null | Original/compare-at price in cents, for strikethrough display | | `cost_amount` | integer (unsigned) | yes | null | Cost price in cents, for margin and profit tracking | | `currency_id` | bigint | no | - | Foreign key to currencies table. Deleting a currency deletes its prices | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Price Fields [#price-fields] Each price record has three amount fields that serve distinct business purposes: | Field | What it represents | Shown to customers | Example | |-------|-------------------|-------------------|---------| | `amount` | The current selling price | Yes | 1999 cents = $19.99 | | `compare_amount` | The original price before a sale or discount. Displayed as a strikethrough next to the selling price (what Shopify calls "compare at price") | Yes (as strikethrough) | 2999 cents = $29.99 | | `cost_amount` | What you paid your supplier. Used to calculate profit margins. Never displayed on the storefront | No | 850 cents = $8.50 | For a product on sale, you would set all three: cost at 850, selling at 1999, and compare-at at 2999. The storefront shows "$19.99 ~~$29.99~~" and you know the margin is $11.49. ### Relationships [#relationships] The `priceable` relationship connects a price to its parent model (Product or ProductVariant): ```php $price->priceable; // Returns the Product or ProductVariant ``` The `currency` relationship returns the currency for this price: ```php $price->currency; // Currency model $price->currency_code; // "USD" (computed accessor) ``` ### Price Helper [#price-helper] The Price model provides three methods that return a `Shopper\Core\Helpers\Price` value object with both the raw amount and a pre-formatted string. Each method returns `null` when its field is `null` or `0`: ```php $priceHelper = $price->amountPrice(); $priceHelper->amount; // 2999 $priceHelper->formatted; // "$29.99" $priceHelper->currency; // "USD" $price->compareAmountPrice(); // Same pattern for compare_amount $price->costAmountPrice(); // Same pattern for cost_amount ``` These three methods format the amount in the store's default currency (`shopper_currency()`), not in the currency of the price record. For a price in another currency, create the helper yourself with the record's currency code. You can also create a Price helper directly. Pass the amount in cents as an integer: ```php use Shopper\Core\Helpers\Price as PriceHelper; $helper = PriceHelper::from(2999, 'USD'); $helper->formatted; // "$29.99" PriceHelper::from($price->amount, $price->currency_code)->formatted; // "€27.99" for a EUR price ``` ## HasPrices Trait [#hasprices-trait] The `Shopper\Core\Models\Traits\HasPrices` trait is used by [Product](/2.x/products) and [ProductVariant](/2.x/product-variants) to provide pricing capabilities. Any model implementing the `Shopper\Core\Contracts\Priceable` interface can use this trait. To get the price for the store's default currency (`shopper_currency()`): ```php $price = $product->getPrice(); // ?Price model ``` To get the price for a specific currency: ```php $price = $product->getPrice('EUR'); // ?Price model ``` The method checks if the `prices` relationship is already loaded to avoid extra queries. When eager-loaded, it filters the collection in memory instead of hitting the database, and loads each price's `currency` only if it is missing. To access all prices: ```php $product->prices; // Collection of Price models ``` Deleting a product or a variant deletes its prices. For products this also happens on a soft delete. ## Currency Model [#currency-model] The model used is `Shopper\Core\Models\Currency`. It implements `Shopper\Core\Models\Contracts\Currency` and has no timestamps. ### Currency Schema [#currency-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Currency name (e.g., "US Dollar") | | `code` | string(10) | no | - | ISO 4217 code (e.g., "USD"), unique | | `symbol` | string(25) | no | - | Currency symbol (e.g., "$") | | `format` | string(50) | no | - | Display format pattern | | `exchange_rate` | decimal(10,2) | yes | null | Exchange rate relative to base currency. Stored for reference only: Shopper never converts prices with it, so each currency needs its own price | | `is_enabled` | boolean | no | true | Whether the currency is active | ### Enabled Scope [#enabled-scope] The Currency model has a global `enabled` scope that automatically filters out disabled currencies. All queries return only enabled currencies by default. ```php use Shopper\Core\Models\Currency; Currency::query()->get(); // Only enabled currencies Currency::query()->withoutGlobalScopes()->get(); // All currencies, including disabled ``` ### Zone Relationship [#zone-relationship] Each [zone](/2.x/zones) sells in one currency. The `zone` relationship returns a zone that uses this currency: ```php $currency->zone; // ?Zone model ``` Several zones can share one currency, and `zone` returns only one of them. To get every zone that uses a currency, query the zones directly: ```php use Shopper\Core\Models\Zone; Zone::query()->where('currency_id', $currency->id)->get(); ``` ## Creating Prices [#creating-prices] To set a price on a product or variant, create a Price record through the `prices()` relationship: ```php use Shopper\Models\Product; $product = Product::query()->find($id); $product->prices()->create([ 'amount' => 2999, 'compare_amount' => 3999, 'cost_amount' => 850, 'currency_id' => $currencyId, ]); ``` The `prices` table has no unique index on the model and currency pair. Calling `create()` twice for the same currency adds a second row, and `getPrice()` returns only one of them. To change an existing price, use `updateOrCreate()` or the `SavePricingAction` below. ### Multi-Currency Pricing [#multi-currency-pricing] To set prices in multiple currencies at once, use the `SavePricingAction`. It accepts an array keyed by currency ID and creates or updates prices in a single pass: ```php use Shopper\Actions\Store\Product\SavePricingAction; $pricing = [ $usdCurrencyId => [ 'amount' => 2999, 'compare_amount' => 3999, 'cost_amount' => 850, ], $eurCurrencyId => [ 'amount' => 2799, 'compare_amount' => 3799, 'cost_amount' => 800, ], ]; app()->call(SavePricingAction::class, [ 'pricing' => $pricing, 'model' => $product, ]); ``` The action uses `updateOrCreate` on each entry, so existing prices for a currency are updated rather than duplicated. An entry without an `amount` (or with `0`) is skipped, and the action never deletes a price: a currency missing from the array keeps its current price. ## Retrieving Prices [#retrieving-prices] To get a product's price for the default currency and format it for display: ```php $price = $product->getPrice(); if ($price) { shopper_money_format($price->amount, $price->currency_code); } ``` To display a sale price with strikethrough: ```php $price = $product->getPrice(); if ($price && $price->compare_amount) { $selling = shopper_money_format($price->amount, $price->currency_code); $original = shopper_money_format($price->compare_amount, $price->currency_code); // Display: "$19.99" with "$29.99" crossed out } ``` To eager-load prices and avoid N+1 queries when listing products: ```php $products = Product::query() ->publish() ->with('prices.currency') ->get(); foreach ($products as $product) { $price = $product->getPrice(); // No extra query, filtered from loaded relation } ``` ## Admin Components [#admin-components] ### MoneyInput [#moneyinput] For Filament forms, use the `MoneyInput` component instead of `TextInput` for monetary fields. It handles conversion between human values (form) and cents (database) automatically: ```php use Shopper\Components\Form\MoneyInput; MoneyInput::make('amount') ->currency('USD') ->suffix('USD'); ``` For zero-decimal currencies, the component adjusts the mask precision to 0 automatically. If no currency is specified, `MoneyInput` defaults to the store's configured currency via `shopper_currency()`. ### Table Columns [#table-columns] Use the `->currency()` macro on Filament `TextColumn` for displaying monetary values: ```php use Filament\Tables\Columns\TextColumn; TextColumn::make('amount') ->currency(fn ($record) => $record->currency_code) ``` This macro uses `shopper_money_format()` internally. Without an argument, it formats in the store's default currency, and an empty value stays empty. ### Publishing Components [#publishing-components] To replace the pricing Livewire components with your own classes, publish the product components config: ```bash php artisan shopper:component:publish product ``` This creates `config/shopper/components/product.php`, where the pricing components are registered. Point a key to your own class to replace it: ```php use Shopper\Livewire; use Shopper\Livewire\Components; return [ 'components' => [ 'products.pricing' => Components\Products\Pricing::class, 'slide-overs.manage-pricing' => Livewire\SlideOvers\ManagePricing::class, ], ]; ``` # Product Tags (/2.x/product-tags) Tags are simple labels you attach to products for cross-cutting organization. Unlike [categories](/2.x/categories) (hierarchical) or [collections](/2.x/collections) (manual or rule-based), tags are flat and flexible, ideal for seasonal labels ("Summer 2026"), marketing campaigns ("Flash Sale"), or storefront filtering ("New Arrival", "Best Seller"). ## Model [#model] The model used is `Shopper\Core\Models\ProductTag`, stored in the `product_tags` table (`sh_product_tags` with the default [table prefix](/2.x/configuration#database-table-prefix)). Products, categories and brands have an admin model that you can replace in `config/shopper/models.php`; tags do not. `Product::tags()` and the `product_tag` morph map entry reference `ProductTag` directly, so the tag model cannot be swapped through configuration. It uses the `HasSlug` trait, which turns the slug you give it into a unique, URL-friendly value (see [Slug Generation](#slug-generation)). ## Database Schema [#database-schema] ### Tags Table [#tags-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Tag name | | `slug` | string | yes | null | URL-friendly identifier (unique), see [Slug Generation](#slug-generation) | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Pivot Table [#pivot-table] Tags use the shared polymorphic `product_has_relations` pivot table. This is the same table used by [categories](/2.x/categories), [collections](/2.x/collections), channels, and related products. The polymorphic pattern lets all these models share a single pivot table instead of requiring a dedicated join table for each relationship type. | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `product_id` | bigint | no | Foreign key to product | | `productable_type` | string | no | Morph type (e.g. `product_tag`) | | `productable_id` | bigint | no | Foreign key to the related model | ## Slug Generation [#slug-generation] The `HasSlug` trait normalizes the slug and handles collisions. When you set the `slug` attribute, the trait runs the value through `Str::slug()` and checks for uniqueness. If a slug already exists, it appends an incrementing suffix (`-1`, `-2`, etc.) until it finds a unique one. A value with no URL-safe characters gets a random 5-character slug. The trait does not build the slug from the `name`. Always pass a `slug` when you create a tag in code: without one the column stays `null` and `findBySlug()` cannot find the tag. ```php use Shopper\Core\Models\ProductTag; $tag1 = ProductTag::query()->create(['name' => 'New Arrival', 'slug' => 'new-arrival']); $tag2 = ProductTag::query()->create(['name' => 'New Arrival 2', 'slug' => 'new-arrival']); // $tag2->slug === 'new-arrival-1' (auto-incremented to avoid collision) ``` The trait also provides a `findBySlug()` static method that looks up a tag by its slug and throws a `ModelNotFoundException` if not found (Laravel turns it into a 404 response): ```php $tag = ProductTag::findBySlug('summer-2026'); ``` ## Relationships [#relationships] ### Products [#products] `ProductTag::products()` is a `morphToMany` relationship and `Product::tags()` is its `morphedByMany` inverse, both through the `product_has_relations` table. From the tag side: ```php $tag->products; $tag->products()->count(); $tag->products()->attach([$productId1, $productId2]); $tag->products()->detach($productId); $tag->products()->sync($productIds); ``` From the product side: ```php $product->tags; $product->tags()->attach([$tagId1, $tagId2]); $product->tags()->sync($tagIds); ``` ## Creating Tags [#creating-tags] To create a tag, provide a name and a slug. The `HasSlug` trait ensures slug uniqueness automatically: ```php use Shopper\Core\Models\ProductTag; $tag = ProductTag::query()->create([ 'name' => 'Summer 2026', 'slug' => 'summer-2026', ]); $tag->products()->attach([$product1->id, $product2->id]); ``` Tags can also be created inline from the product edit form in the admin panel. The tag selection field includes a "Create" option that opens a modal form, so administrators can add new tags without leaving the product page. In the admin, both this modal and the Tags page fill the slug from the name and keep the slug field read-only. A name whose slug is already taken is rejected by validation instead of receiving a `-1` suffix. ## Retrieving Tags [#retrieving-tags] To get all tags ordered by name with their product count: ```php $tags = ProductTag::query() ->withCount('products') ->orderBy('name') ->get(); ``` To find a tag by slug with its products: ```php $tag = ProductTag::findBySlug('summer-2026'); $products = $tag->products()->publish()->paginate(12); ``` To get all tags for a specific product: ```php $tags = $product->tags; ``` ## Configuration [#configuration] ### Disabling Tags [#disabling-tags] If you don't need tags in your store, disable the feature in `config/shopper/features.php`: ```php use Shopper\Enum\FeatureState; return [ 'tag' => FeatureState::Disabled, ]; ``` When disabled, the tag menu item is hidden from the sidebar, tag-related routes are not registered, and the tag selection field is removed from product forms. The `ProductTag` model, its table and `Product::tags()` keep working in your own code. ### Permissions [#permissions] The admin panel generates five permissions for tag management, in the `products` permission group: | Permission | Description | |------------|-------------| | `browse_tags` | Open the Tags page | | `read_tags` | Created with the others; no admin screen checks it, since tags have no detail page | | `add_tags` | Create tags from the Tags page | | `edit_tags` | Edit tags from the Tags page | | `delete_tags` | Delete tags, one by one or in bulk | The permissions seeder creates them on a fresh install. An installation that started before Shopper 2.3 creates them with `Shopper\Models\Permission::generate('tags', 'products')`, then assigns them to its roles, as described in the [2.2 to 2.3 upgrade guide](/2.x/upgrade/v2-2-to-v2-3#new-permissions). ## Components [#components] Tags are managed under the product components configuration. To customize the admin UI: ```bash php artisan shopper:component:publish product ``` This creates `config/shopper/components/product.php`. The tag page is registered there under the `tag-index` key, next to the product pages. Point the key to your own Livewire component to replace the page: ```php return [ 'pages' => [ 'tag-index' => \Shopper\Livewire\Pages\Tag\Index::class, ], ]; ``` To add content above or below the tags table without replacing the page, use the `TAGS_TABLE_BEFORE` and `TAGS_TABLE_AFTER` constants of `Shopper\View\CatalogRenderHook` as [render hooks](/2.x/render-hooks#catalog-hooks). ## Storefront Example [#storefront-example] This example shows a tag listing page and a tag detail page that displays all published products for a given tag. ```php namespace App\Http\Controllers; use Shopper\Core\Models\ProductTag; use Shopper\Models\Product; class TagController extends Controller { public function index() { $tags = ProductTag::query() ->withCount('products') ->orderBy('name') ->get(); return view('tags.index', compact('tags')); } public function show(string $slug) { $tag = ProductTag::findBySlug($slug); $products = $tag->products() ->publish() ->paginate(12); return view('tags.show', compact('tag', 'products')); } } ``` ### Filtering Products by Tags [#filtering-products-by-tags] To get products that have a specific tag: ```php $products = Product::query() ->whereHas('tags', fn ($query) => $query->where('slug', 'summer-2026')) ->publish() ->get(); ``` To get products that have any of the given tags: ```php $products = Product::query() ->whereHas('tags', fn ($query) => $query->whereIn('slug', ['new-arrival', 'best-seller'])) ->publish() ->paginate(12); ``` # Product Variants (/2.x/product-variants) Product variants represent specific versions of a product based on combinations of options like size, color, or material. A "Classic T-Shirt" product might have six variants: Blue/S, Blue/M, Blue/L, Red/S, Red/M, Red/L. Each variant carries its own SKU, price, stock level, images, and shipping dimensions. ## How Variants Work [#how-variants-work] Shopper uses an **attribute-based variant system**. A product with `type = ProductType::Variant` acts as a parent that holds the shared description, categories, and brand. The parent delegates pricing and stock to its child variants. The relationship works like this: | Level | Example | What it holds | |-------|---------|---------------| | **Product** | Classic T-Shirt | Name, description, categories, brand, images | | **Option** (Attribute) | Color, Size | The axes that define variation | | **Option Value** (Attribute Value) | Blue, Red, S, M, L | The choices within each option | | **Variant** | Blue / S, Blue / M, Red / L | SKU, price, stock, dimensions, images | A variant's identity is the combination of its attribute values. The variant "Blue / Large" is defined by two values: Color = Blue and Size = Large. Shopper stores this through a pivot table that links variants to attribute values, so the system can look up which variant matches a customer's selection. Read prices and stock from the variants, not from the parent product. Shopper does not prevent a price or stock on the parent: the admin hides the parent's Pricing tab for variant products, but its Inventory tab is still there. ## Model [#model] The model used is `Shopper\Models\ProductVariant`, which extends `Shopper\Core\Models\ProductVariant`. The core model provides the business logic, relationships, stock management, and pricing. The admin model adds media collections and conversions through Spatie MediaLibrary. The core model implements `Shopper\Core\Contracts\Priceable`, `Shopper\Core\Models\Contracts\ProductVariant` and `Shopper\Core\Contracts\Media\HasMedia`, and uses the following traits: | Trait | Purpose | |-------|---------| | `HasDimensions` | Formatted `weight`, `height`, `width`, `depth` and `volume` accessors over the value and unit columns | | `HasMediaCollections` | Declares the gallery and thumbnail collections, which the admin model registers with Spatie MediaLibrary | | `HasPrices` | Multi-currency pricing through a polymorphic `prices` relationship | | `HasStock` | Inventory management through `inventory_histories` mutations | ### Extending the Model [#extending-the-model] To add custom behavior, extend the admin model and update your configuration: ```php namespace App\Models; use Shopper\Models\ProductVariant as ShopperProductVariant; class ProductVariant extends ShopperProductVariant { } ``` Update `config/shopper/models.php`: ```php return [ 'variant' => \App\Models\ProductVariant::class, ]; ``` Shopper resolves the variant class through this config key, so all internal queries and relationships use your extended model automatically. ## Database Schema [#database-schema] Table names take the `shopper.core.table_prefix` prefix (`sh_` by default), so the tables below are `sh_product_variants` and `sh_attribute_value_product_variant` on a default install. ### Product Variants Table [#product-variants-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Variant name, typically generated from attribute values (indexed) | | `sku` | string | yes | null | Stock Keeping Unit (unique per product) | | `barcode` | string | yes | null | Barcode (unique) | | `ean` | string | yes | null | European Article Number (unique) | | `upc` | string | yes | null | Universal Product Code (unique) | | `allow_backorder` | boolean | no | false | Whether customers can order when out of stock | | `position` | integer | no | 1 | Display order among siblings | | `product_id` | bigint | yes | null | Foreign key to the parent product, set to null if the product row is deleted | | `weight_unit` | string | no | kg | Weight unit enum | | `weight_value` | decimal(10,2) | yes | 0.00 | Weight value | | `height_unit` | string | no | cm | Height unit enum | | `height_value` | decimal(10,2) | yes | 0.00 | Height value | | `width_unit` | string | no | cm | Width unit enum | | `width_value` | decimal(10,2) | yes | 0.00 | Width value | | `depth_unit` | string | no | cm | Depth unit enum | | `depth_value` | decimal(10,2) | yes | 0.00 | Depth value | | `volume_unit` | string | no | l | Volume unit enum | | `volume_value` | decimal(10,2) | yes | 0.00 | Volume value | | `metadata` | json | yes | null | Additional custom data for your application | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The `sku` column uses a composite unique constraint on `[product_id, sku]`. Two variants on different products can share the same SKU, but variants within the same product must have distinct SKUs. ### Attribute Value Pivot Table [#attribute-value-pivot-table] This pivot table connects variants to their attribute values, defining which combination of options each variant represents. | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `value_id` | bigint | no | Foreign key to attribute value | | `variant_id` | bigint | no | Foreign key to variant | Both foreign keys cascade on delete: deleting a variant or an attribute value removes its pivot rows. ## Relationships [#relationships] ### Product [#product] Each variant belongs to a parent product. This is the inverse of the `Product::variants()` relationship. ```php $variant->product; ``` ### Attribute Values [#attribute-values] The `values()` relationship defines the variant's identity. A variant named "Blue / Large" has two attribute values attached: one for Color (Blue) and one for Size (Large). This is how the system matches a customer's selection to a specific variant. ```php $variant->values; ``` To attach attribute values when creating a variant: ```php $variant->values()->attach([ $colorBlueValueId, $sizeLargeValueId, ]); ``` To replace all attribute values at once: ```php $variant->values()->sync([$colorRedValueId, $sizeMediumValueId]); ``` ## Stock Management [#stock-management] Variants use the `HasStock` trait for inventory management. Stock is not stored as a column on the variant. 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`. ### Querying Stock [#querying-stock] To get the current total stock across all locations: ```php $variant->stock; ``` To get stock at a specific point in time, useful for reporting or auditing: ```php $variant->getStock('2026-01-15'); $variant->getStock(now()->subDays(7)); ``` To get stock for a specific inventory location: ```php $variant->stockInventory($warehouseId); $variant->stockInventory($warehouseId, '2026-01-15'); ``` To check whether a quantity is available (one unit by default): ```php $variant->inStock(); $variant->inStock(3); ``` ### Modifying Stock [#modifying-stock] To increase stock (for example, when receiving a shipment): ```php use Shopper\Models\ProductVariant; $variant = ProductVariant::query()->find($id); $variant->mutateStock( inventoryId: $inventory->id, quantity: 50, event: 'Shipment received', description: 'PO #12345 - Spring collection restock', ); ``` To decrease stock (for example, when fulfilling an order): ```php $variant->decreaseStock( inventoryId: $inventory->id, quantity: 2, event: 'Order fulfilled', description: 'Order #1042', ); ``` To set stock to an exact quantity (for example, after a physical inventory count), use `setStock()`. It compares `newQuantity` with the variant's total stock across all locations, records the difference as a single mutation on the given location, and returns `null` when there is nothing to change. Use it for variants stocked in one location; with several locations, use `mutateStock()` or `decreaseStock()` instead. ```php $variant->setStock( newQuantity: 75, inventoryId: $inventory->id, event: 'Inventory count', description: 'Q1 2026 physical count adjustment', ); ``` To clear the stock history and optionally record a new starting quantity on one location (the new quantity is recorded only when you pass both `inventoryId` and `newQuantity`): ```php $variant->clearStock( inventoryId: $inventory->id, newQuantity: 100, event: 'Stock reset', ); ``` `clearStock()` deletes all inventory history records for the variant, on every location, even when you pass an `inventoryId`. Use it only for resets or corrections, not for regular stock adjustments. ### Backorder [#backorder] The `allow_backorder` flag indicates whether customers can purchase this variant when it is out of stock. The `inStock()` method does not check this flag. It only checks whether quantity is available. The cart already skips its stock check for a variant with `allow_backorder` set (see [Stock Validation](/2.x/cart#stock-validation)). In your own storefront logic, combine both: ```php if ($variant->inStock() || $variant->allow_backorder) { // allow add to cart } ``` ### Avoiding N+1 Queries [#avoiding-n1-queries] When displaying a product page with multiple variants, accessing `$variant->stock` on each variant triggers an individual query. Use `loadCurrentStock()` to batch-load stock in a single query: ```php use Shopper\Models\Product; use Shopper\Models\ProductVariant; $product = Product::query()->with('variants')->find($id); ProductVariant::loadCurrentStock($product->variants); foreach ($product->variants as $variant) { echo $variant->name . ': ' . $variant->stock; } ``` To batch-load stock for a specific inventory location: ```php ProductVariant::loadStockForInventory($product->variants, $inventoryId); ``` To catch unoptimized stock access during development, enable lazy stock loading prevention. When enabled, accessing `$variant->stock` without prior batch-loading throws a `LazyStockLoadingException` with a clear message telling you to use `loadCurrentStock()`. ```php ProductVariant::preventLazyStockLoading(! app()->isProduction()); ``` For more details on the batch-loading pattern, see the [Products Stock Management](/2.x/products#avoiding-n1-queries) section. ## Pricing [#pricing] Variants use the `HasPrices` trait for multi-currency pricing. Each variant can have one price per currency, stored in the `prices` table through a polymorphic relationship. To get the price for the store's default currency: ```php $price = $variant->getPrice(); ``` To get the price for a specific currency code: ```php $price = $variant->getPrice('USD'); ``` `getPrice()` returns `null` when the variant has no price in that currency. The returned `Price` model contains three amount fields, stored as integers in cents (see [Money Storage Standard](/2.x/pricing#money-storage-standard)): ```php $price->amount; // selling price, e.g. 2999 for 29.99 $price->compare_amount; // original/compare-at price, e.g. 3999 $price->cost_amount; // cost price for margin tracking, e.g. 1500 ``` To format a price for display: ```php shopper_money_format($price->amount, $price->currency_code); ``` ## Media [#media] Variants support two media collections through [Spatie MediaLibrary](https://spatie.be/docs/laravel-medialibrary), using the same config-driven collection names as [products](/2.x/products#media). This lets you show a different photo when a customer selects "Blue" versus "Red". | Collection | Config key | Behavior | Description | |------------|-----------|----------|-------------| | Default gallery | `shopper.media.storage.collection_name` | Multiple files | Variant gallery images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | Single file | Main variant image for listings | To add a variant thumbnail: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $variant->addMedia($file)->toMediaCollection($collection); ``` To add gallery images: ```php $collection = config('shopper.media.storage.collection_name'); $variant->addMedia($file)->toMediaCollection($collection); ``` To retrieve the thumbnail URL with a specific conversion: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $url = $variant->getFirstMediaUrl($collection, 'medium'); ``` ## Dimensions [#dimensions] The `HasDimensions` trait provides physical measurements for shipping calculations. Each dimension has a value and a unit stored as an enum. ### Dimension Enums [#dimension-enums] **Weight:** ```php use Shopper\Core\Enum\Dimension\Weight; Weight::KG // kg - Kilograms Weight::G // g - Grams Weight::LBS // lbs - Pounds ``` **Length** (used for height, width, and depth): ```php use Shopper\Core\Enum\Dimension\Length; Length::M // m - Meters Length::CM // cm - Centimeters Length::MM // mm - Millimeters Length::FT // ft - Feet Length::IN // in - Inches ``` **Volume:** ```php use Shopper\Core\Enum\Dimension\Volume; Volume::L // l - Liters Volume::ML // ml - Milliliters Volume::GAL // gal - Gallons Volume::FLOZ // floz - Fluid ounces ``` Each dimension also has a formatted accessor that joins the value and the unit. It returns `null` when the value is `null`; a value left at its `0.00` default is still formatted, as `"0.00 kg"` for example: ```php $variant->weight; // "250.00 g" $variant->height; // "70.00 cm" ``` ## Creating Variants [#creating-variants] ### Single Variant [#single-variant] The simplest way to create a variant with pricing, stock, and attribute values in one transaction is the `CreateNewVariant` action: ```php use Shopper\Actions\Store\Product\CreateNewVariant; $variant = app()->call(CreateNewVariant::class, ['data' => [ 'name' => 'Blue / Large', 'sku' => 'TSHIRT-BLU-L', 'product_id' => $product->id, 'quantity' => 50, 'values' => [$colorBlueValueId, $sizeLargeValueId], 'prices' => [ $currencyId => ['amount' => 2999, 'compare_amount' => 3999], ], ]]); ``` This action wraps everything in a database transaction: it creates the variant after the product's last variant (any `position` you pass is replaced), saves one price per currency, syncs attribute values, and records `quantity` as initial stock on the [default inventory location](/2.x/locations#default-location). The `prices` array is keyed by currency ID, with amounts in cents. If no location is marked as default, the quantity is not recorded. ### Manual Creation [#manual-creation] For more control, create the variant step by step: ```php use Shopper\Models\ProductVariant; use Shopper\Core\Enum\Dimension\Weight; use Shopper\Core\Enum\Dimension\Length; $variant = ProductVariant::query()->create([ 'name' => 'Blue / Large', 'sku' => 'TSHIRT-BLU-L', 'product_id' => $product->id, 'position' => 1, 'weight_unit' => Weight::G, 'weight_value' => 250, 'height_unit' => Length::CM, 'height_value' => 70, 'width_unit' => Length::CM, 'width_value' => 50, ]); $variant->values()->attach([$colorBlueValueId, $sizeLargeValueId]); $variant->prices()->create([ 'amount' => 2999, 'currency_id' => $currencyId, ]); $variant->mutateStock( inventoryId: $inventory->id, quantity: 50, event: 'Initial stock', ); ``` ## Generating Variant Combinations [#generating-variant-combinations] When a product has multiple options, you need to generate all possible combinations. A product with 3 colors and 3 sizes produces 9 variants. Shopper provides tools to automate this. ### Permutation Helpers [#permutation-helpers] The `Shopper\Core\Macros\Arr` class (plain static methods, not a Laravel macro) generates the cartesian product of option values. `permutate()` throws an `InvalidArgumentException` when an option has no values: ```php use Shopper\Core\Macros\Arr; $options = [ 'Color' => [ ['id' => 1, 'value' => 'Blue'], ['id' => 2, 'value' => 'Red'], ], 'Size' => [ ['id' => 4, 'value' => 'Medium'], ['id' => 5, 'value' => 'Large'], ], ]; $permutations = Arr::permutate($options); // Result: 4 combinations - Blue/Medium, Blue/Large, Red/Medium, Red/Large $name = Arr::performPermutationIntoWord($permutations[0], 'value'); // "Blue / Medium" $valueIds = Arr::getPermutationIds($permutations[0]); // [1, 4] ``` ### Bulk Save with SaveProductVariantsAction [#bulk-save-with-saveproductvariantsaction] The `SaveProductVariantsAction` handles creating, updating, and deleting variants in a single transaction. Variants not present in the array are deleted, existing ones are updated, and new ones are created. Every entry needs the `variant_id`, `name`, `sku`, `price` and `values` keys; `stock` is optional. ```php use Shopper\Actions\Store\Product\SaveProductVariantsAction; $variants = [ [ 'variant_id' => null, 'name' => 'Blue / Large', 'sku' => 'TSHIRT-BLUE-LARGE', 'price' => 2999, 'stock' => 100, 'values' => [1, 5], ], [ 'variant_id' => null, 'name' => 'Blue / Medium', 'sku' => 'TSHIRT-BLUE-MEDIUM', 'price' => 2999, 'stock' => 50, 'values' => [1, 4], ], ]; $savedVariants = app()->call(SaveProductVariantsAction::class, [ 'product' => $product, 'variants' => $variants, ]); ``` The action returns the same array with each `variant_id` filled in. The `price` is an amount in cents, saved for the store's default currency, and only when it is greater than 0. Pass an existing `variant_id` to update a variant instead of creating a new one: its price, stock and attribute values are updated, but its `name` and `sku` are kept. Any variant belonging to the product that is not in the array will be deleted, so an array without any `variant_id` deletes all the product's existing variants. A `stock` greater than 0 calls `clearStock()` on the variant, which deletes its stock history on every location, then records the quantity on the default inventory location. ### MapProductOptions [#mapproductoptions] For products with existing attribute assignments, `MapProductOptions` builds the list of options and their values. Key it by option name to feed it into `Arr::permutate()`: ```php use Shopper\Core\Macros\Arr; use Shopper\Helpers\MapProductOptions; $options = collect(MapProductOptions::generate($product)) ->mapWithKeys(fn (array $option): array => [$option['name'] => $option['values']]) ->all(); $permutations = Arr::permutate($options); ``` `generate()` returns a list of options, each with its `id`, `key`, `name` and `values` (each value has an `id`, `key` and `value`), based on the attributes already assigned to the product. Attributes with a free-text type (text, number, rich text, date) are skipped. ## Retrieving Variants [#retrieving-variants] To get all variants for a product, ordered by position (the `variants()` relationship already sorts by `position`): ```php $variants = $product->variants; ``` To find a variant by its SKU: ```php use Shopper\Models\ProductVariant; $variant = ProductVariant::query() ->where('sku', 'TSHIRT-BLU-L') ->first(); ``` To load variants with their attribute values and parent attributes (for building a selection UI): ```php $variants = $product->variants() ->with('values.attribute') ->get(); ``` To find the variant matching a specific combination of attribute values (for example, when a customer selects Color = Blue and Size = Large): ```php $valueIds = [$colorBlueId, $sizeLargeId]; $variant = $product->variants() ->whereHas('values', function ($q) use ($valueIds) { $q->whereKey($valueIds); }, '=', count($valueIds)) ->first(); ``` Use `whereKey()` rather than `whereIn('id', ...)`: the query joins the pivot table, which also has an `id` column, so an unqualified `id` is ambiguous. To get the total stock across all variants for a product, batch-load the variants' stock first, otherwise `variants_stock` runs one stock query per variant: ```php use Shopper\Models\ProductVariant; ProductVariant::loadCurrentStock($product->variants); $product->variants_stock; ``` ## Observer Behavior [#observer-behavior] The `ProductVariantObserver` handles cascade cleanup when a variant is deleted. Together with Spatie MediaLibrary, which deletes the media files, it removes all associated media, prices, and inventory history records automatically. The database removes the attribute value pivot rows. ```php $variant->delete(); ``` You do not need to manually clean up related records before deleting a variant. Shopper registers the observer on the class set in `shopper.models.variant`, so an extended model keeps this behavior. An observer you register on your own model runs alongside it. ## Components [#components] You can publish the Livewire components to customize the admin UI for variant management: ```bash php artisan shopper:component:publish product ``` Variant-related components in `config/shopper/components/product.php`: ```php use Shopper\Livewire; use Shopper\Livewire\Components; return [ 'pages' => [ 'variant-edit' => Livewire\Pages\Product\Variant::class, ], 'components' => [ 'products.form.variants' => Components\Products\Form\Variants::class, 'products.variant-stock' => Components\Products\VariantStock::class, 'slide-overs.add-variant' => Livewire\SlideOvers\AddVariant::class, 'slide-overs.update-variant' => Livewire\SlideOvers\UpdateVariant::class, 'slide-overs.generate-variants' => Livewire\SlideOvers\GenerateVariants::class, 'products.pricing' => Components\Products\Pricing::class, 'slide-overs.manage-pricing' => Livewire\SlideOvers\ManagePricing::class, ], ]; ``` The variant edit page shares the `products.pricing` and `slide-overs.manage-pricing` components with products. The admin checks the [product variant permissions](/2.x/products#product-variants) before adding, editing, or deleting variants. ## Storefront Example [#storefront-example] This example shows a complete product page controller that loads variants, groups their attribute values for a selection UI, and handles AJAX variant lookups when a customer changes their selection. ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Shopper\Models\Product; use Shopper\Models\ProductVariant; class ProductController extends Controller { public function show(string $slug) { $product = Product::query() ->where('slug', $slug) ->publish() ->firstOrFail(); $variants = $product->variants() ->with(['values.attribute', 'media']) ->get(); ProductVariant::loadCurrentStock($variants); $attributes = []; foreach ($variants as $variant) { foreach ($variant->values as $value) { $attrId = $value->attribute_id; if (! isset($attributes[$attrId])) { $attributes[$attrId] = [ 'name' => $value->attribute->name, 'values' => collect(), ]; } $attributes[$attrId]['values']->push($value); } } foreach ($attributes as &$attr) { $attr['values'] = $attr['values']->unique('id'); } return view('products.show', compact('product', 'variants', 'attributes')); } public function getVariant(Request $request, Product $product) { $valueIds = $request->input('values', []); $variant = $product->variants() ->whereHas('values', function ($q) use ($valueIds) { $q->whereKey($valueIds); }, '=', count($valueIds)) ->with('media') ->first(); if (! $variant) { return response()->json(['error' => 'Variant not found'], 404); } return response()->json([ 'id' => $variant->id, 'name' => $variant->name, 'sku' => $variant->sku, 'price' => $variant->getPrice()?->amount, // in cents 'stock' => $variant->stock, 'in_stock' => $variant->inStock(), 'image' => $variant->getFirstMediaUrl(config('shopper.media.storage.thumbnail_collection')), ]); } } ``` # Products (/2.x/products) 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 [#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. | Type | Shipping | Variants | Attributes | Stock | Use case | |------|----------|----------|------------|-------|----------| | Standard | Yes | No | Yes | On the product itself | A book, a poster, a mug | | Variant | Yes | Yes | Yes | On each variant | A t-shirt with sizes and colors | | Virtual | No | No | Yes | Not tracked | An ebook, a software license, a course | | External | No | No | No | Not tracked | A 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](/2.x/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: ```php $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 [#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 [#extending-the-model] To add custom behavior, extend the admin model and update your configuration: ```php namespace App\Models; use Shopper\Models\Product as ShopperProduct; class Product extends ShopperProduct { } ``` Update `config/shopper/models.php`: ```php return [ 'product' => \App\Models\Product::class, ]; ``` ## Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Product name | | `slug` | string | yes | null | URL-friendly identifier (unique). Any value you set is slugified and suffixed (`-1`, `-2`) when taken. The admin form fills it from the name | | `sku` | string | yes | null | Stock Keeping Unit (unique) | | `barcode` | string | yes | null | Product barcode (unique) | | `description` | longtext | yes | null | Full product description (rich text) | | `summary` | text | yes | null | Short product summary | | `type` | string | yes | null | Product type enum value | | `is_visible` | boolean | no | false | Visibility on storefront | | `featured` | boolean | no | false | Featured product flag | | `allow_backorder` | boolean | no | false | Allow adding to cart when out of stock. The admin has no field for it on products, set it in code | | `security_stock` | integer | yes | 0 | Minimum stock alert threshold | | `published_at` | datetimeTz | no | migration date | Publication date (supports scheduling). The column default is the date the migration ran, so set it when you create a product | | `seo_title` | string(60) | yes | null | SEO meta title | | `seo_description` | string(160) | yes | null | SEO meta description | | `weight_unit` | string | no | kg | Weight unit (kg, g, lbs) | | `weight_value` | decimal(10,2) | yes | 0.00 | Weight value | | `height_unit` | string | no | cm | Height unit (m, cm, mm, ft, in) | | `height_value` | decimal(10,2) | yes | 0.00 | Height value | | `width_unit` | string | no | cm | Width unit | | `width_value` | decimal(10,2) | yes | 0.00 | Width value | | `depth_unit` | string | no | cm | Depth unit | | `depth_value` | decimal(10,2) | yes | 0.00 | Depth value | | `volume_unit` | string | no | l | Volume unit (l, ml, gal, floz) | | `volume_value` | decimal(10,2) | yes | 0.00 | Volume value | | `external_id` | string | yes | null | External system reference | | `metadata` | jsonb | yes | null | Additional custom data | | `brand_id` | bigint | yes | null | Foreign key to brands | | `supplier_id` | bigint | yes | null | Foreign key to suppliers | | `deleted_at` | timestamp | yes | null | Soft delete timestamp | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Relationships [#relationships] ### Brand [#brand] Each product can belong to a brand. This is a standard `BelongsTo` relationship. ```php $product->brand; ``` To query products by brand: ```php Product::query() ->whereHas('brand', fn ($q) => $q->where('slug', 'nike')) ->get(); ``` ### Categories [#categories] Products have a polymorphic many-to-many relationship with categories through the `product_has_relations` table. ```php $product->categories; $product->categories()->attach([$categoryId1, $categoryId2]); $product->categories()->sync([$categoryId1, $categoryId2]); ``` ### Collections [#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. ```php $product->collections; $product->collections()->attach($collectionId); ``` ### Channels [#channels] Products can be assigned to multiple sales channels for multi-channel publishing. ```php $product->channels; $product->channels()->attach($channelId); ``` ### Variants [#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. ```php $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](/2.x/products#avoiding-n1-queries)). ```php use Shopper\Models\ProductVariant; ProductVariant::loadCurrentStock($product->variants); $product->variants_stock; ``` See the [Product Variants](/2.x/product-variants) documentation for the full variant API. ### Tags [#tags] Products can have multiple tags for cross-cutting organization. Unlike categories (hierarchical) or collections (manual or rule-based), tags are simple flat labels. ```php $product->tags; $product->tags()->attach([$tagId1, $tagId2]); ``` See the [Product Tags](/2.x/product-tags) documentation for details. ### Supplier [#supplier] Each product can optionally be linked to a supplier. ```php $product->supplier; ``` ### Attributes (Options) [#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. ```php $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. ```php $product->options()->attach($colorAttributeId, [ 'attribute_value_id' => $navyBlueValueId, ]); $product->options()->attach($engravingAttributeId, [ 'attribute_custom_value' => 'Happy birthday, Anna', ]); ``` ### Related Products [#related-products] You can link products together as related items for cross-selling on the storefront. ```php $product->relatedProducts; $product->relatedProducts()->attach([$productId1, $productId2]); ``` ### Discounts [#discounts] Products can be associated with discounts through a polymorphic relationship. ```php $product->discounts; ``` See the [Discounts](/2.x/discounts) documentation for details on discount rules and conditions. ## Query Scopes [#query-scopes] ### Published Products [#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. ```php use Shopper\Models\Product; Product::query()->publish()->get(); ``` ### Filter by Channel [#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. ```php Product::query()->forChannel($channelId)->get(); Product::query()->forChannel([$webChannelId, $mobileChannelId])->get(); ``` ### Publication Check [#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. ```php $product->isPublished(); ``` ## Media [#media] Products support three media collections through [Spatie MediaLibrary](https://spatie.be/docs/laravel-medialibrary). The collection names for the default gallery and thumbnail are defined in `config/shopper/media.php`. | Collection | Config key | Behavior | Description | |------------|-----------|----------|-------------| | Default gallery | `shopper.media.storage.collection_name` | Multiple files | Product gallery images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | Single file | Main product image for listings | | `files` | - | Multiple files | Downloadable files for virtual products. Accepts the mime types listed in `shopper.media.accepts_file_types` | To add a product thumbnail: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $product->addMedia($file)->toMediaCollection($collection); ``` To add gallery images: ```php $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: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $url = $product->getFirstMediaUrl($collection, 'medium'); ``` ### Downloadable Files [#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. ```php $product->addMedia($pdfPath)->toMediaCollection('files'); $downloadUrl = $product->getFirstMediaUrl('files'); ``` To get all downloadable files for a product: ```php $product->getMedia('files'); ``` ## Pricing [#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: ```php $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. ```php shopper_money_format($price->amount, 'USD'); ``` See the [Pricing](/2.x/pricing) documentation for details on creating and managing prices. ## Stock Management [#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 [#querying-stock] To get the current total stock across all locations: ```php $product->stock; ``` For variant products, use `variants_stock` to get the combined stock across all variants, after batch-loading the stock of the variants: ```php 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: ```php $product->getStock('2026-01-15'); $product->getStock(now()->subDays(7)); ``` To get stock for a specific inventory location: ```php $product->stockInventory($warehouseId); ``` To check that a quantity is available (the stock is above zero and at least the requested quantity): ```php $product->inStock(3); ``` To check the stock alert threshold: ```php if ($product->stock <= $product->security_stock) { // low stock } ``` ### Modifying Stock [#modifying-stock] To increase stock (for example, when receiving a shipment from a supplier): ```php $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): ```php $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. ```php $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: ```php $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](/2.x/product-variants#stock-management) section. ### Avoiding N+1 Queries [#avoiding-n1-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: ```php 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: ```php Product::loadStockForInventory($products, $inventoryId); ``` ### Preventing Lazy Stock Loading [#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`. ```php 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 [#dimensions] The `HasDimensions` trait provides computed attributes that return formatted dimension strings combining the value and unit. ```php $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 [#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: ```php 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](/2.x/events#product-events) page. ## Creating Products [#creating-products] To create a standard product with a price and category: ```php 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: ```php $collection = config('shopper.media.storage.thumbnail_collection'); $product->addMediaFromUrl('https://example.com/tshirt.jpg') ->toMediaCollection($collection); ``` ## Retrieving Products [#retrieving-products] The `findBySlug` static method looks up a product by its slug and throws a `ModelNotFoundException` if not found: ```php $product = Product::findBySlug('classic-t-shirt'); ``` To get all published products with their relationships: ```php $products = Product::query() ->publish() ->with(['brand', 'categories', 'media']) ->get(); ``` To get featured products: ```php $featured = Product::query() ->publish() ->where('featured', true) ->take(8) ->get(); ``` To get products by category: ```php $products = Product::query() ->publish() ->whereHas('categories', fn ($q) => $q->where('slug', 'clothing')) ->get(); ``` ## Permissions [#permissions] The admin panel generates permissions for product management and its related features: ### Products [#products] | Permission | Description | |------------|-------------| | `browse_products` | View the products list | | `read_products` | View a single product | | `add_products` | Create new products | | `edit_products` | Edit existing products | | `delete_products` | Delete products | ### Product Variants [#product-variants] | Permission | Description | |------------|-------------| | `browse_product_variants` | View variants on a product | | `read_product_variants` | View a single variant | | `add_product_variants` | Create new variants | | `edit_product_variants` | Edit existing variants | | `delete_product_variants` | Delete variants | ## Components [#components] You can publish the Livewire components to customize the admin UI for products: ```bash 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. # Requirements (/2.x/requirements) Shopper is a Laravel package and shares the same server requirements as Laravel itself, plus the PHP extensions listed below. ## Server Requirements [#server-requirements] - PHP 8.3+ (the test suite runs on PHP 8.3, 8.4 and 8.5) - MySQL 8+, PostgreSQL 15+ or SQLite The test suite runs on these three databases. MariaDB is not part of it. ### PHP Extensions [#php-extensions] Shopper requires these extensions on top of the ones Laravel needs. Composer refuses to install Shopper if one of them is missing: | Extension | Purpose | |-----------|---------| | `intl` | Currency formatting, locale support, and internationalization | | `gd` | Required by `milon/barcode`, which draws the barcode on the variant page. GD is also the default image driver of Spatie Media Library, which builds the resized copies (the `large` and `medium` conversions) of product, variant, category, brand, and collection images | | `exif` | Required by Spatie Media Library, which reads the metadata of uploaded images | | `zip`, `xmlreader` | Required by OpenSpout, the spreadsheet library of Filament's actions package | | `iconv` | Required by `bacon/bacon-qr-code`, which draws the QR code a user scans to set up two-factor authentication | | `soap` | Required by `ivanmitrikeski/laravel-shipping`, the carrier library behind `shopper/shipping`. Composer refuses to install Shopper without it, even if your store uses no carrier. | Laravel Herd includes all of these extensions. On Linux servers and in the official `php` Docker images, `intl`, `gd`, `zip` and `soap` usually have to be installed separately (for example the `php8.3-intl` and `php8.3-soap` packages on Ubuntu). Run `php -m` to list the extensions your PHP has. GD stays required even if you prefer ImageMagick, because `milon/barcode` needs it. To build the image conversions with ImageMagick, install the `imagick` extension and set `IMAGE_DRIVER=imagick` in your `.env` file. Spatie Media Library reads this variable for its `image_driver` option. ## Package Requirements [#package-requirements] | Package | Version | |---------|---------| | Laravel | 11.28+ / 12.x / 13.x | | Filament | 4.12+ (not 5.x) | | Livewire | 3.8+ (not 4.x) | Composer installs Filament and Livewire as dependencies of Shopper, so you do not require them in your application. Shopper 2 stays on Filament 4, which runs on Livewire 3. The Laravel 11.28 minimum is also Filament 4's minimum. A new Laravel major version needs a Shopper release that adds it, even when Filament already supports it. ## Development Environments [#development-environments] ### Laravel Herd [#laravel-herd] [Laravel Herd](https://herd.laravel.com/) is the recommended development environment for both macOS and Windows. It provides PHP and Nginx with zero configuration, and SQLite works out of the box. MySQL and PostgreSQL run as services in Herd Pro. Herd's PHP builds include all the extensions listed above. ### Laravel Valet [#laravel-valet] [Laravel Valet](https://laravel.com/docs/valet) is a lightweight development environment for macOS. It maps all subdirectories in a directory (such as `~/Sites`) to `.test` domains. You can share your sites publicly using local tunnels. ### Docker [#docker] Any Docker setup that satisfies the PHP and database requirements will work. The [Shopper demo store](https://github.com/shopperlabs/demo.laravelshopper.dev) uses Docker with FrankenPHP (Laravel Octane) as a reference. # Reviews (/2.x/reviews) Reviews allow customers to rate and review products. Shopper provides a flexible review system with approval workflows, rating calculations, and polymorphic relationships. ## Model [#model] The model used is `Shopper\Core\Models\Review`. It implements `Shopper\Core\Models\Contracts\Review`. Unlike products or brands, the Review model is not configurable via `config/shopper/models.php` and has no admin model wrapper. Products gain review capabilities through the `Shopper\Core\Contracts\HasReviews` interface and the `Shopper\Core\Models\Traits\InteractsWithReviews` trait, which provides the interface's methods. `Shopper\Core\Models\Product` already implements and uses both, so `Shopper\Models\Product` has them too. ## Database Schema [#database-schema] Reviews are stored in the `sh_reviews` table (the `sh_` prefix comes from `table_prefix` in `config/shopper/core.php`). | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `rating` | integer | no | - | Rating value (typically 1-5) | | `title` | text | yes | null | Review title | | `content` | text | yes | null | Review content | | `is_recommended` | boolean | no | false | Customer recommends product | | `approved` | boolean | no | false | Review approval status | | `reviewrateable_id` | bigint | no | - | Polymorphic relation ID (product) | | `reviewrateable_type` | string | no | - | Polymorphic relation type | | `author_id` | bigint | no | - | Polymorphic relation ID (user) | | `author_type` | string | no | - | Polymorphic relation type | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | Shopper registers a morph map for its models, so `reviewrateable_type` stores the alias `product`, not a class name. `author_type` stores your user model's morph class (`App\Models\User` unless your application maps it). When you write or query these columns yourself, use `$model->getMorphClass()`, never `get_class($model)` or `Product::class`. ## Relationships [#relationships] ### Reviewrateable (Product) [#reviewrateable-product] ```php // Get the reviewed entity (usually a product) $review->reviewrateable; // Instance of config('shopper.models.product') ``` ### Author (User) [#author-user] ```php // Get the review author $review->author; // User model ``` ## HasReviews Contract [#hasreviews-contract] Products implement the `HasReviews` contract and use the `InteractsWithReviews` trait, which provides the contract's methods: ```php use Shopper\Core\Contracts\HasReviews; use Shopper\Core\Models\Traits\InteractsWithReviews; class Product extends Model implements HasReviews { use InteractsWithReviews; } ``` ## Rating Methods [#rating-methods] ### Getting Ratings [#getting-ratings] Each `get*Ratings()` method takes an id as its first argument (the product id, or the customer id for `getRecentUserRatings()`) and returns a collection of `Review` models ordered by creation date. ```php // Get all ratings for a product, pending ones included $product->ratings; // Collection of Review models // Get all ratings, newest first ('asc' for oldest first) $product->getAllRatings($product->id, 'desc'); // Get only approved ratings $product->getApprovedRatings($product->id); // Get pending (not approved) ratings $product->getNotApprovedRatings($product->id); // Get the 5 most recent approved ratings $product->getRecentRatings($product->id, 5); // Get a customer's 5 most recent approved ratings, across all products $product->getRecentUserRatings($userId, 5, approved: true); ``` ### Rating Counts [#rating-counts] ```php // Count all ratings, pending ones included $product->countRating(); // Returns integer // Get rating sum $product->sumRating(); // Collection with sum // Get the sum of approved ratings only $product->sumRating(onlyApproved: true); ``` ### Average Ratings [#average-ratings] `averageRating()` returns a collection holding a single value: call `first()` to read it. The value is `null` when the product has no review, and some database drivers return it as a numeric string, so cast it to `float` before using it as a number. ```php // Get average rating $product->averageRating(); // Collection with average // Get average rating rounded to 1 decimal (float) $product->averageRating(round: 1)->first(); // e.g., 4.5 // Get average rating of approved reviews only (float) $product->averageRating(round: 1, onlyApproved: true)->first(); ``` ### Rating Percentage [#rating-percentage] ```php // Get percentage of 5-star ratings, pending reviews included $product->ratingPercent(5); // e.g., 85.5 // Useful for displaying rating distribution $distribution = [ 5 => $product->ratingPercent(5), 4 => $product->ratingPercent(4), 3 => $product->ratingPercent(3), 2 => $product->ratingPercent(2), 1 => $product->ratingPercent(1), ]; ``` ## Creating Reviews [#creating-reviews] ### Via Product Model [#via-product-model] ```php use Shopper\Models\Product; $product = Product::query()->find($id); // Create a review $review = $product->rating([ 'rating' => 5, 'title' => 'Excellent product!', 'content' => 'This product exceeded my expectations.', 'is_recommended' => true, 'approved' => false, // Pending approval ], $user); ``` ### Via Review Model [#via-review-model] ```php use Shopper\Core\Models\Review; $review = new Review; $review = $review->createRating($product, [ 'rating' => 4, 'title' => 'Good quality', 'content' => 'Happy with my purchase.', 'is_recommended' => true, ], $user); ``` ### Direct Creation [#direct-creation] ```php $review = Review::query()->create([ 'rating' => 5, 'title' => 'Love it!', 'content' => 'Best purchase I made.', 'is_recommended' => true, 'approved' => false, 'reviewrateable_id' => $product->id, 'reviewrateable_type' => $product->getMorphClass(), 'author_id' => $user->id, 'author_type' => $user->getMorphClass(), ]); ``` ## Updating Reviews [#updating-reviews] ```php // Via product model $product->updateRating($reviewId, [ 'rating' => 4, 'content' => 'Updated review content.', ]); // Via review model $review = new Review; $review->updateRating($reviewId, [ 'title' => 'Updated title', 'content' => 'Updated content', ]); ``` ## Approval Management [#approval-management] ```php // Approve a review $review->updatedApproved(true); // Unapprove a review $review->updatedApproved(false); // Direct update $review->update(['approved' => true]); ``` ## Deleting Reviews [#deleting-reviews] ```php // Via product model $product->deleteRating($reviewId); // Via review model $review = new Review; $review->deleteRating($reviewId); // Direct delete Review::query()->findOrFail($reviewId)->delete(); ``` ## Retrieving Reviews [#retrieving-reviews] ```php use Shopper\Core\Models\Review; // Get all reviews $reviews = Review::query() ->with(['author', 'reviewrateable']) ->latest() ->get(); // Get pending reviews $pending = Review::query() ->where('approved', false) ->with('author') ->get(); // Get approved reviews for a product $productReviews = Review::query() ->where('reviewrateable_id', $product->id) ->where('reviewrateable_type', $product->getMorphClass()) ->where('approved', true) ->with('author') ->latest() ->paginate(10); // Get reviews by user $userReviews = Review::query() ->where('author_id', $user->id) ->where('author_type', $user->getMorphClass()) ->with('reviewrateable') ->get(); ``` ## Configuration [#configuration] ### Disabling Reviews [#disabling-reviews] If your store doesn't need product reviews, disable the feature in `config/shopper/features.php`: ```php use Shopper\Enum\FeatureState; return [ 'review' => FeatureState::Disabled, ]; ``` This removes the reviews page and its sidebar link from the admin panel. The `Review` model and the product rating methods keep working, so your storefront can still use them. ### Permissions [#permissions] The permissions seeder creates five permissions for reviews, listed in the `products` group of the role permissions screen: | Permission | Description | |------------|-------------| | `browse_reviews` | Open the reviews list and a review's detail panel | | `read_reviews` | Created with the others, not checked by the 2.x reviews pages | | `add_reviews` | Created with the others, not checked: the admin panel does not create reviews | | `edit_reviews` | Approve a review, or set an approved review back to pending | | `delete_reviews` | Delete reviews, one at a time or in bulk | ## Components [#components] To customize the admin UI for review management: ```bash php artisan shopper:component:publish review ``` Creates `config/shopper/components/review.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'review-index' => Livewire\Pages\Reviews\Index::class, ], 'components' => [ 'slide-overs.review-detail' => Livewire\SlideOvers\ReviewDetail::class, ], ]; ``` ## Storefront Example [#storefront-example] ### Review Display [#review-display] ```php namespace App\Http\Controllers; use Shopper\Models\Product; class ProductController extends Controller { public function show(string $slug) { $product = Product::findBySlug($slug); // Get approved reviews $reviews = $product->ratings() ->where('approved', true) ->with('author') ->latest() ->paginate(10); // Get rating stats $averageRating = (float) $product->averageRating(1, onlyApproved: true)->first(); $reviewCount = $product->ratings()->where('approved', true)->count(); // Rating distribution $distribution = []; for ($i = 5; $i >= 1; $i--) { $count = $product->ratings() ->where('approved', true) ->where('rating', $i) ->count(); $distribution[$i] = [ 'count' => $count, 'percentage' => $reviewCount > 0 ? ($count / $reviewCount) * 100 : 0, ]; } return view('products.show', compact( 'product', 'reviews', 'averageRating', 'reviewCount', 'distribution' )); } } ``` ### Review Submission [#review-submission] ```php namespace App\Http\Controllers; use Illuminate\Http\Request; use Shopper\Models\Product; class ReviewController extends Controller { public function store(Request $request, Product $product) { $validated = $request->validate([ 'rating' => 'required|integer|min:1|max:5', 'title' => 'nullable|string|max:255', 'content' => 'nullable|string|max:2000', 'is_recommended' => 'boolean', ]); // Check if user already reviewed this product $existingReview = $product->ratings() ->where('author_id', auth()->id()) ->where('author_type', auth()->user()->getMorphClass()) ->exists(); if ($existingReview) { return back()->with('error', 'You have already reviewed this product.'); } // Create review (pending approval) $product->rating([ ...$validated, 'approved' => false, ], auth()->user()); return back()->with('success', 'Thank you! Your review is pending approval.'); } } ``` ### Review Management (Admin) [#review-management-admin] Shopper's admin panel already lists, approves and deletes reviews. Write a controller like this one only for a back office of your own. ```php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Shopper\Core\Models\Review; class ReviewController extends Controller { public function index() { $reviews = Review::query() ->with(['author', 'reviewrateable']) ->latest() ->paginate(20); return view('admin.reviews.index', compact('reviews')); } public function approve(Review $review) { $review->updatedApproved(true); return back()->with('success', 'Review approved.'); } public function reject(Review $review) { $review->delete(); return back()->with('success', 'Review deleted.'); } } ``` ## Blade Template Example [#blade-template-example] ```blade {{-- Product rating summary --}}
{{ $averageRating ?? 0 }} /5
@for ($i = 1; $i <= 5; $i++) @endfor

Based on {{ $reviewCount }} reviews

{{-- Rating distribution --}}
@foreach ($distribution as $rating => $data)
{{ $rating }} stars
{{ $data['count'] }}
@endforeach
{{-- Reviews list --}} @foreach ($reviews as $review)
{{ $review->author->full_name }} {{ $review->rating }}/5 {{ $review->created_at->diffForHumans() }}
@if ($review->title)

{{ $review->title }}

@endif

{{ $review->content }}

@if ($review->is_recommended) Recommends this product @endif
@endforeach ``` ## Use Cases [#use-cases] | Method | Use Case | |--------|----------| | `averageRating()` | Display product rating stars | | `countRating()` | Show total review count | | `ratingPercent()` | Build rating distribution chart | | `getApprovedRatings()` | Display reviews on product page | | `getNotApprovedRatings()` | Admin review moderation queue | | `getRecentUserRatings()` | Customer review history | # Setup Store (/2.x/setup-store) After installing Shopper and creating your admin user, log in at `/cpanel/login` (`cpanel` is the default value of `shopper.admin.prefix`, set with `SHOPPER_PREFIX`). Until the store has an `email` and a `street_address` setting, every admin page redirects to the setup wizard at `/cpanel/initialize`. Only an administrator or a user with the `access_setting` permission can complete it. The wizard collects your store's basic information, address, and social links in three steps. Clicking **Next** saves the fields of the current step. Clicking **Save** on the last step saves every field, creates your first inventory location in the same database transaction, and opens the dashboard. The wizard does not create the default sales channel: the install command does, as described in [Channel](#channel). ## Settings Model [#settings-model] Store configuration is managed through key-value pairs in the `Shopper\Core\Models\Setting` model, stored in the `sh_settings` table (`sh_` is the default [table prefix](/2.x/configuration#database-table-prefix)). Each setting has a unique key, an optional display name, and a JSON value. ### Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `key` | string | no | - | Configuration key (unique) | | `display_name` | string | yes | null | Human-readable label. Shopper sets it from the key each time it saves the setting | | `value` | json | yes | null | Setting value, stored as JSON and decoded on read (`array` cast): a list of IDs comes back as an array, a store name as a string | | `locked` | boolean | no | false | Set to `true` by every admin save except the wizard's **Next** button, which saves with `false` and skips settings that are already locked. Hidden from the model's array and JSON output | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Retrieving Settings [#retrieving-settings] To retrieve the value of a key, call the `shopper_setting()` helper with the key. It returns `null` when the key does not exist: ```php shopper_setting('name'); ``` The value is cached for one day under the key `shopper-setting.{$key}`. Shopper clears that cache entry each time the admin panel saves the key. The second parameter, `withCache`, defaults to `true`. With `false`, the value read from the database is cached for one second instead of one day, but a value already in the cache is still returned: ```php shopper_setting('name', withCache: false); ``` If you change a `Setting` row in your own code, forget its cache entry so the next call reads the new value. For `default_currency_id`, also forget `shopper-setting.default_currency`, where `shopper_currency()` keeps the currency code for one hour: ```php use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Setting; Setting::query()->updateOrCreate( ['key' => 'email'], ['value' => 'orders@acme-store.com'], ); Cache::forget('shopper-setting.email'); ``` ## Store [#store] When you launch your store the first important thing to do is to fill in the information about this store. Your customers and the different services you might use need to know the information about your store. The information stored in this section is available using the following keys: - `name` the store name (required, 100 characters at most) - `email` the store email (required) - `country_id` the ID of the country where the store is based (optional) - `currencies` an array of the IDs of the currencies the store sells in (at least one). The price forms of the admin list these currencies, see [How Setup Store Currencies](/2.x/currencies#how-setup-store-currencies) - `default_currency_id` the ID of the default currency, which must be one of `currencies`. `shopper_currency()` returns its code, or `USD` when it is not set The store description (`about`) is not part of the wizard: you fill it in on the General settings page, described in [Update setting](#update-setting). ## Address [#address] Most stores keep their products in different locations around the world. When setting up this configuration you need to define an address that will be set as the default location for your products. When you submit the wizard, Shopper creates your default inventory location from this step: the location takes the store name (and its slug as the location code), the store email, the street address, postal code, city, phone number and country. When you create a product or a variant in the admin with an initial quantity, that stock is recorded at the default location. See [Default Location](/2.x/locations#default-location). The keys registered in database during this section: `street_address`, `postal_code` and `city` (required), `state` and `phone_number` (optional). ## Social Links [#social-links] If you want your customers to find you easily on social networks, you can fill in all the links directly by putting the full url. The wizard checks that each link is a valid URL. This step is completely optional The keys registered in the database during this section: `facebook_link`, `instagram_link` and `twitter_link`. The setup wizard (`Shopper\Livewire\Pages\Initialization` and its `Shopper\Livewire\Components\Initialization\InitializationWizard` form) is registered by Shopper itself and has no entry in the component configuration files, so you cannot replace it. It is a mandatory step before accessing the dashboard, see [Access Requirements](/2.x/dashboard#access-requirements). ## Channel [#channel] In today's E-commerce the shop site is no longer the only point of sale. Channels represent a single sales channel, which can be one of the following things: - Website - Mobile application - Cashier in your physical store - Facebook shop, - Instagram shop, - etc or pretty much anything similar you can imagine. When you accept the database step of `php artisan shopper:install`, the `ChannelSeeder` creates a default sales channel. The setup wizard does not create or change it, and the channel does not take your store address. The seeder runs the equivalent of: ```php use Shopper\Core\Models\Channel; Channel::query()->create([ 'name' => 'Web Store', 'slug' => 'web-store', 'url' => config('app.url'), 'is_default' => true, 'is_enabled' => true, ]); ``` The **Add product** form of the admin preselects this channel in its **Sales channels** field, and you can remove it there. A product you create in code has no channel until you attach one, see [Assigning Products to Channels](/2.x/channels#assigning-products-to-channels). The 2.x admin has no page to manage channels: create other channels in code, as shown in [Creating Channels](/2.x/channels#creating-channels). ## Update setting [#update-setting] You can update your store information when needed, edit your store images, update the complete address, the legal name of your shop, etc. To edit your shop information: - In the admin, click **Settings** at the bottom of the sidebar, then **General** (`/cpanel/setting/general`). Both require the `access_setting` permission. Besides the wizard keys, this page saves `legal_name` (required), `about` (the store description, from a rich text editor), and `logo` and `cover` (the paths of the uploaded images on the `shopper.media.storage.disk_name` disk). The component used to update store setting of the store is found in the component configuration file `config/shopper/components/setting.php` if published (run `php artisan shopper:component:publish setting`). It's the `Shopper\Livewire\Pages\Settings\General` component under the key `pages.general`. ```php use Shopper\Livewire\Components; use Shopper\Livewire\Pages; return [ 'pages' => [ 'setting-index' => Pages\Settings\Index::class, 'general' => Pages\Settings\General::class, 'location-index' => Pages\Settings\Locations\Index::class, // ... ], 'components' => [ // ... ], ]; ``` In this interface you will update your store. Don't forget that the model used is the model `Shopper\Core\Models\Setting`. Point `pages.general` to your own Livewire component to change this view and the keys it stores in the database. To save settings the way Shopper does, use the `Shopper\Traits\SaveSettings` trait in your component: its `saveSettings()` method writes the keys and clears their cache. # Suppliers (/2.x/suppliers) Suppliers represent external vendors or manufacturers who provide products for your store. This is primarily used in **dropshipping** scenarios where products are shipped directly from the supplier to the customer, without you handling inventory. The supplier feature is gated behind a feature flag and is disabled by default. It must be enabled in your `config/shopper/features.php` configuration file. ## Model [#model] The model used is `Shopper\Core\Models\Supplier`. It implements `Shopper\Core\Models\Contracts\Supplier` and uses the `HasSlug` trait: a `slug` you set is passed through `Str::slug()` and gets a numeric suffix (`-1`, `-2`) when another supplier already uses it. The trait does not create a slug from the name: the admin form fills it from the name, and in code you pass it yourself. `HasSlug` also adds `Supplier::findBySlug()`. The model is configurable via `config/shopper/models.php`. ### Extending the Model [#extending-the-model] To add custom behavior, extend the model and update your configuration: ```php namespace App\Models; use Shopper\Core\Models\Supplier as BaseSupplier; class Supplier extends BaseSupplier { } ``` Update `config/shopper/models.php`: ```php return [ 'supplier' => \App\Models\Supplier::class, ]; ``` ## Feature Flag [#feature-flag] Enable the supplier feature in `config/shopper/features.php`: ```php use Shopper\Enum\FeatureState; return [ // ... 'supplier' => FeatureState::Enabled, ]; ``` When enabled, the Suppliers page appears under Products in the admin sidebar (route `shopper.suppliers.index`), and the edit page of External products shows a required supplier select that lists only enabled suppliers. The flag only controls the admin: the `suppliers` table, the model and its relationships exist either way. ## Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Supplier name | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `email` | string | yes | null | Contact email | | `phone` | string | yes | null | Contact phone | | `contact_name` | string | yes | null | Primary contact person | | `website` | string | yes | null | Supplier website URL | | `description` | longText | yes | null | Detailed description | | `notes` | longText | yes | null | Internal notes | | `is_enabled` | boolean | no | false | Whether the supplier is active (only enabled suppliers can be picked on a product) | | `metadata` | jsonb | yes | null | Additional custom data | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Relationships [#relationships] ### Products [#products] A supplier can have many products linked to it: ```php // Get all products from a supplier $supplier->products; // Collection // Get visible products $supplier->products() ->where('is_visible', true) ->get(); // Count products per supplier $supplier->products()->count(); ``` ### Product to Supplier [#product--supplier] Each product can optionally belong to one supplier: ```php use Shopper\Models\Product; // Get a product's supplier $product->supplier; // Supplier (nullable) // Check if a product has a supplier if ($product->supplier_id) { // This is a dropshipped product } // Get all products from a specific supplier Product::query() ->where('supplier_id', $supplier->id) ->get(); ``` ## Query Scopes [#query-scopes] ```php use Shopper\Core\Models\Supplier; // Get only enabled suppliers Supplier::query()->enabled()->get(); ``` ## Creating Suppliers [#creating-suppliers] ```php use Shopper\Core\Models\Supplier; $supplier = Supplier::query()->create([ 'name' => 'TechParts Co., Ltd', 'slug' => 'techparts-co', 'email' => 'orders@techparts.com', 'phone' => '+86 755 1234 5678', 'contact_name' => 'Zhang Wei', 'website' => 'https://techparts.com', 'description' => 'Electronics components and accessories manufacturer based in Shenzhen.', 'notes' => 'Minimum order: 50 units. Lead time: 5-7 days.', 'is_enabled' => true, 'metadata' => [ 'payment_terms' => 'net_30', 'currency' => 'USD', 'minimum_order' => 50, ], ]); ``` ## Updating Status [#updating-status] `updateStatus()` takes a boolean that defaults to `true`: ```php // Enable a supplier $supplier->updateStatus(); // Disable a supplier $supplier->updateStatus(false); ``` ## Retrieving Suppliers [#retrieving-suppliers] ```php // Get all enabled suppliers $suppliers = Supplier::query() ->enabled() ->withCount('products') ->get(); // Find by slug (throws ModelNotFoundException when missing) $supplier = Supplier::findBySlug('techparts-co'); // Search enabled suppliers by name or email $results = Supplier::query() ->enabled() ->where(function ($query) use ($search): void { $query->where('name', 'like', "%{$search}%") ->orWhere('email', 'like', "%{$search}%"); }) ->get(); ``` ## Linking Products to Suppliers [#linking-products-to-suppliers] The admin shows the supplier field on products of type `External` only. The link is stored in the nullable `supplier_id` column of the products table: ```php use Shopper\Core\Enum\ProductType; use Shopper\Models\Product; // Create an external product linked to a supplier $product = Product::query()->create([ 'name' => 'Wireless Bluetooth Earbuds', 'slug' => 'wireless-bluetooth-earbuds', 'type' => ProductType::External, 'supplier_id' => $supplier->id, 'is_visible' => true, // ... other product fields ]); // Change a product's supplier $product->update(['supplier_id' => $newSupplier->id]); // Remove supplier link $product->update(['supplier_id' => null]); ``` Deleting a supplier does not delete its products: the foreign key sets their `supplier_id` to `null`. ## Dropshipping Workflow [#dropshipping-workflow] The supplier feature is designed to work with the [Fulfillment](/2.x/fulfillment) system. Here's the complete flow: ### 1. Setup [#1-setup] ```php use Shopper\Core\Models\Supplier; // Create your supplier $supplier = Supplier::query()->create([ 'name' => 'Shenzhen TechParts', 'slug' => 'shenzhen-techparts', 'email' => 'orders@techparts.com', 'is_enabled' => true, ]); // Link products to supplier $product->update(['supplier_id' => $supplier->id]); ``` ### 2. Customer Places Order [#2-customer-places-order] When a customer orders a product linked to a supplier, the order is created normally. The item's `fulfillment_status` starts as `Pending`. ### 3. Forward to Supplier [#3-forward-to-supplier] After receiving the customer's payment, you place the order with your supplier using the customer's shipping address: ```php use Shopper\Core\Enum\FulfillmentStatus; // Mark this supplier's items as forwarded $order->items() ->where('fulfillment_status', FulfillmentStatus::Pending) ->whereHasMorph( 'product', [config('shopper.models.product')], fn ($query) => $query->where('supplier_id', $supplier->id), ) ->update(['fulfillment_status' => FulfillmentStatus::ForwardedToSupplier]); ``` An order item's `product` is a polymorphic relation that points to a product or a variant, and only products have a `supplier_id` column. `whereHasMorph()` limits the check to products. Only `Variant` products have variants, so the items of an External product always point to the product itself. ### 4. Supplier Ships [#4-supplier-ships] When the supplier provides tracking information, create the shipment and attach this supplier's forwarded items to it: ```php use Shopper\Core\Actions\SyncOrderShippingStatusAction; use Shopper\Core\Enum\FulfillmentStatus; use Shopper\Core\Enum\ShipmentStatus; $shipment = $order->shippings()->create([ 'carrier_id' => $carrierId, 'status' => ShipmentStatus::PickedUp, 'tracking_number' => $supplierTracking, 'tracking_url' => $supplierTrackingUrl, 'shipped_at' => now(), ]); $order->items() ->where('fulfillment_status', FulfillmentStatus::ForwardedToSupplier) ->whereHasMorph( 'product', [config('shopper.models.product')], fn ($query) => $query->where('supplier_id', $supplier->id), ) ->update([ 'order_shipping_id' => $shipment->id, 'fulfillment_status' => FulfillmentStatus::Shipped, ]); (new SyncOrderShippingStatusAction)->execute($order); ``` The items are updated here because `RecordShipmentEventAction` only moves `Pending` items to `Shipped`. [`SyncOrderShippingStatusAction`](/2.x/fulfillment#syncordershippingstatusaction) recomputes the order's `shipping_status` and dispatches `OrderShipped` when it becomes `Shipped`. ### 5. Delivery Confirmation [#5-delivery-confirmation] ```php $shipment->update([ 'status' => ShipmentStatus::Delivered, 'received_at' => now(), ]); $shipment->items()->update([ 'fulfillment_status' => FulfillmentStatus::Delivered, ]); (new SyncOrderShippingStatusAction)->execute($order); ``` ## Querying by Supplier [#querying-by-supplier] ```php use Illuminate\Support\Facades\DB; use Shopper\Core\Enum\FulfillmentStatus; use Shopper\Core\Models\OrderItem; // Get the items still waiting on a supplier $pendingItems = OrderItem::query() ->whereIn('fulfillment_status', [ FulfillmentStatus::Pending, FulfillmentStatus::ForwardedToSupplier, ]) ->whereHasMorph( 'product', [config('shopper.models.product')], fn ($query) => $query->where('supplier_id', $supplier->id), ) ->with(['order.customer', 'order.shippingAddress']) ->get(); // Get supplier revenue in cents (delivered items, after item discounts) $revenue = OrderItem::query() ->whereHasMorph( 'product', [config('shopper.models.product')], fn ($query) => $query->where('supplier_id', $supplier->id), ) ->where('fulfillment_status', FulfillmentStatus::Delivered) ->sum(DB::raw('unit_price_amount * quantity - discount_amount')); ``` ## Permissions [#permissions] The supplier feature uses the following permissions: | Permission | Description | |-----------|-------------| | `browse_suppliers` | View the suppliers list and its sidebar entry | | `read_suppliers` | Not checked by the admin (there is no supplier detail page), available to your own code | | `add_suppliers` | Create new suppliers | | `edit_suppliers` | Update existing suppliers, enable or disable them in bulk | | `delete_suppliers` | Delete suppliers | ```php // Check permission $user->hasPermissionTo('browse_suppliers'); // Assign permission to a role $role->givePermissionTo('browse_suppliers'); ``` The installer creates these permissions in the `products` group. On a store installed before the supplier feature existed, create them before you enable the feature, then assign them to your roles: ```php use Shopper\Models\Permission; Permission::generate('suppliers', 'products'); ``` ## Components [#components] The supplier feature registers its components through the product configuration. Publish the product components to customize: ```bash php artisan shopper:component:publish product ``` This includes: ```php // In config/shopper/components/product.php use Shopper\Livewire; return [ 'pages' => [ 'supplier-index' => Livewire\Pages\Supplier\Index::class, // ... ], 'components' => [ 'slide-overs.supplier-form' => Livewire\SlideOvers\SupplierForm::class, // ... ], ]; ``` The `SupplierForm` slide-over handles both creating and editing a supplier. To add content above or below the suppliers table without publishing components, use the `SalesRenderHook::SUPPLIERS_TABLE_BEFORE` and `SalesRenderHook::SUPPLIERS_TABLE_AFTER` [render hooks](/2.x/render-hooks#sales-hooks). ## Metadata [#metadata] The `metadata` column (JSON) can store any additional supplier-specific data: ```php $supplier = Supplier::query()->create([ 'name' => 'FastShip Logistics', 'slug' => 'fastship-logistics', 'metadata' => [ 'payment_terms' => 'net_30', 'currency' => 'USD', 'minimum_order' => 100, 'lead_time_days' => 7, 'return_policy' => '30 days', 'api_endpoint' => 'https://api.fastship.com/v2', ], ]); // Access metadata $terms = $supplier->metadata['payment_terms']; ``` The supplier form in the admin edits `metadata` as key-value text pairs. Keep values flat (no nested arrays) so they stay editable there, and expect values saved from the form to come back as strings. # Taxes (/2.x/taxes) Shopper calculates taxes per line item, based on where an order is being shipped. You define geographic zones, assign percentage rates to each zone, and optionally override those rates for specific products, product types, or categories. The cart pipeline applies all of this automatically during checkout. All tax amounts are stored in **cents** as unsigned integers, consistent with the rest of the monetary system. You manage zones, rates, and overrides from **Settings > Taxes** in the admin panel (users need the `access_setting` permission), or in code with the models described below. ## How It Works [#how-it-works] The tax system has four main pieces: 1. **TaxZone**: a geographic area (country, or country + province) with a tax inclusion policy and an optional custom provider 2. **TaxRate**: a percentage rate attached to a zone; one rate per zone should be marked as the default 3. **TaxRateRule**: a targeting rule on a rate; when a cart line matches a rule, its rate takes priority over the zone's default 4. **TaxCalculationProvider**: the service responsible for receiving a taxable item and a context, and returning `TaxLine` value objects When the cart is being calculated, the `CalculateTax` pipeline step reads the shipping address, resolves the matching `TaxZone`, picks the applicable `TaxRate`, and stores a `CartLineTaxLine` record for each tax line returned for a cart line. A matching 0% rate still produces a record, with an `amount` of `0`. ## Tax Zones [#tax-zones] A tax zone defines where a tax configuration applies. It maps to a country and optionally to a specific province or state within that country. The most important setting on a zone is `is_tax_inclusive`, which determines whether prices already include tax (VAT, common in Europe) or whether tax is added on top (sales tax, common in the US). ```php use Shopper\Core\Models\Country; use Shopper\Core\Models\TaxZone; $france = Country::query()->where('cca2', 'FR')->firstOrFail(); $franceZone = TaxZone::query()->create([ 'country_id' => $france->id, 'name' => 'Standard VAT', 'is_tax_inclusive' => true, ]); ``` ```php $usa = Country::query()->where('cca2', 'US')->firstOrFail(); TaxZone::query()->create([ 'country_id' => $usa->id, 'province_code' => 'CA', 'name' => 'California Sales Tax', 'is_tax_inclusive' => false, ]); ``` When the calculator resolves a zone for a shipping address, it first tries to find a zone matching both the country and province. If none exists, it falls back to a country-level zone with no `province_code`. The country is matched on its `cca2` code, and the province with an exact string comparison against the `state` of the cart shipping address. The `display_name` accessor returns a human-readable label: the translated country name, followed by the zone name when the zone has one. ### Zone Schema [#zone-schema] | Column | Type | Description | |--------|------|-------------| | `country_id` | `nullable unsignedBigInteger` | The country this zone applies to (required by the admin form) | | `province_code` | `nullable string` | Province or state code, compared as an exact string with the cart address `state`. Use the format your checkout stores (`CA`, or the ISO 3166-2 `US-CA` the admin suggests) | | `name` | `nullable string` | Optional label to identify the zone in the admin | | `is_tax_inclusive` | `boolean` | Whether prices already include tax (VAT) or not (sales tax). Defaults to `false` | | `provider_id` | `nullable unsignedBigInteger` | Custom tax provider; falls back to the system default when null | | `parent_id` | `nullable unsignedBigInteger` | Parent zone, exposed through `parent()` and `children()`. The tax calculation does not use it in 2.x | | `metadata` | `nullable jsonb` | Arbitrary data for custom providers | The combination of `country_id` and `province_code` is unique, you cannot have two zones for the same country/province pair. Unique indexes treat `NULL` values as distinct, so this does not cover country-level zones: create only one zone without `province_code` per country, because the calculator uses the first one it finds. The TaxZone model is configurable via `config/shopper/models.php` (the `tax_zone` key). ### Zone Relationships [#zone-relationships] | Relationship | Type | Description | |---|---|---| | `country()` | `BelongsTo` | The country this zone is scoped to | | `rates()` | `HasMany` | All tax rates defined for this zone | | `provider()` | `BelongsTo` | The custom tax provider assigned to this zone | | `parent()` | `BelongsTo` | Parent zone | | `children()` | `HasMany` | Child zones | ## Tax Rates [#tax-rates] Each zone has one or more rates. Mark one rate per zone as `is_default`: it applies to every item in the zone that does not match a more specific override rule. Shopper does not enforce a single default; if several rates of a zone have the flag, the first one loaded is used. If a zone has no default rate, items that match no rule get no tax line. ```php use Shopper\Core\Models\TaxRate; TaxRate::query()->create([ 'tax_zone_id' => $franceZone->id, 'name' => 'TVA 20%', 'code' => 'FR_VAT_STANDARD', 'rate' => 20.0, 'is_default' => true, ]); ``` France has a reduced VAT rate of 5.5% on food. You can define it as a separate non-default rate on the same zone, then target it at the right product category using a rule: ```php $reducedRate = TaxRate::query()->create([ 'tax_zone_id' => $franceZone->id, 'name' => 'TVA 5.5%', 'code' => 'FR_VAT_REDUCED', 'rate' => 5.5, 'is_default' => false, ]); ``` ### Tax Rate Schema [#tax-rate-schema] | Column | Type | Description | |--------|------|-------------| | `tax_zone_id` | `unsignedBigInteger` | The zone this rate belongs to | | `name` | `string` | Display name shown on invoices (`TVA 20%`) | | `code` | `nullable string` | Machine-readable identifier (`FR_VAT_STANDARD`) | | `rate` | `decimal(8,4)` | Percentage value `20.0` means 20% | | `is_default` | `boolean` | Applied when no override rule matches the item. Defaults to `false` | | `is_combinable` | `boolean` | Shown as "Combinable" in the admin. The tax calculation does not read it in 2.x: an item always gets a single rate | | `metadata` | `nullable jsonb` | Arbitrary data for external providers | The TaxRate model is configurable via `config/shopper/models.php` (the `tax_rate` key). ### Rate Relationships [#rate-relationships] | Relationship | Type | Description | |---|---|---| | `taxZone()` | `BelongsTo` | The zone this rate is attached to | | `rules()` | `HasMany` | Override rules that activate this rate for specific items | ## Tax Rate Rules [#tax-rate-rules] Rules let you override the default rate for specific items. The calculator goes through the zone's rates that have at least one rule, in the order the database returns them, and uses the first rate with a rule that matches the line. If no rule matches, the zone's default rate is used. In the admin, an override (**Create Override** on a zone) is a non-default rate with its rules. A rule has two fields: `reference_type` identifies what kind of entity to match, and `reference_id` holds the specific value to match against. ```php use Shopper\Core\Models\TaxRateRule; TaxRateRule::query()->create([ 'tax_rate_id' => $reducedRate->id, 'reference_type' => 'category', 'reference_id' => (string) $foodCategory->id, ]); ``` This rule tells the calculator: "whenever a cart line belongs to the food category, use the 5.5% rate instead of the default 20%." You can also target a specific product: ```php TaxRateRule::query()->create([ 'tax_rate_id' => $zeroVatRate->id, 'reference_type' => 'product', 'reference_id' => (string) $childrenBook->id, ]); ``` Or an entire product type, which is useful for applying different rules to virtual goods versus physical ones: ```php TaxRateRule::query()->create([ 'tax_rate_id' => $digitalRate->id, 'reference_type' => 'product_type', 'reference_id' => 'virtual', ]); ``` ### Rule Reference Types [#rule-reference-types] | `reference_type` | `reference_id` | Matches when | |---|---|---| | `product_type` | A `ProductType` enum value (`standard`, `variant`, `virtual`, `external`; the admin offers all but `variant`) | The item's product type equals the value. For a variant, the parent product's type is used | | `product` | A product primary key, as a string | The item's product ID matches. For a variant in the cart, the parent product ID is used | | `category` | A category primary key, as a string | The item's product is attached to that category directly (parent categories do not match) | ### Rule Schema [#rule-schema] | Column | Type | Description | |--------|------|-------------| | `id` | bigint | Primary key | | `tax_rate_id` | bigint | FK to tax rate | | `reference_type` | string | Entity type to match (`product_type`, `product`, `category`) | | `reference_id` | string | Entity value or ID to match against | The combination of `tax_rate_id`, `reference_type`, and `reference_id` is unique. You cannot attach the same rule twice to the same rate. ## Inclusive vs Exclusive Taxes [#inclusive-vs-exclusive-taxes] The `is_tax_inclusive` flag on the zone controls the math behind the tax amount. **Tax-exclusive** (sales tax): tax is added on top of the price. The customer pays more than the listed price: ``` tax = line_total * rate / 100 total = line_total + tax ``` A $100 product with a 10% exclusive tax costs **$110** at checkout. **Tax-inclusive** (VAT): tax is already embedded in the listed price. The customer pays exactly the listed price, but the tax authority receives a portion: ``` tax = line_total - (line_total / (1 + rate / 100)) total = line_total (unchanged) ``` A €100 product with 20% VAT inclusive: tax = €100 - (€100 / 1.2) = **€16.67**, amount before tax = **€83.33**. Shopper handles both formulas automatically in `SystemTaxProvider`. The tax is computed on the whole line total (not per unit) and rounded to the nearest cent. The zone's `is_tax_inclusive` value is also propagated to the `taxInclusive` property of the cart pipeline context, so storefronts can show "VAT included" or display tax as an addition at checkout. ## Cart Integration [#cart-integration] Tax calculation is part of the cart pipeline (the `shopper.cart.pipelines.cart` config key) and runs automatically whenever you call `CartManager::calculate()`. The `CalculateTax` step runs after discounts are applied, ensuring taxes are computed on the post-discount amount. The step reads the country (`cca2`) and `state` of the cart's shipping address and builds a `TaxCalculationContext` from those values and the cart's `customer_id`. Then, for each cart line whose taxable amount (line subtotal minus its discount adjustments) is above zero, it: 1. Passes a `CartLineTaxAdapter` for the line to `TaxCalculator::calculate()` 2. Deletes any existing `CartLineTaxLine` records for that line 3. Creates new `CartLineTaxLine` records with the resulting tax lines 4. Adds the line's tax to `taxTotal` on the pipeline context Finally, it sets `taxInclusive` on the context from the resolved zone. Each `CartLineTaxLine` stores the `code`, `name`, `rate`, `amount` (in cents), and `tax_rate_id` of a tax line. ```php use Shopper\Cart\CartManager; $context = resolve(CartManager::class)->calculate($cart); $context->taxTotal; $context->taxInclusive; $cart->load('lines.taxLines'); foreach ($cart->lines as $line) { foreach ($line->taxLines as $taxLine) { $taxLine->name; $taxLine->amount; } } ``` The pipeline loads `lines.taxLines` before `CalculateTax` replaces the records, so reload the relation (as above) to read the new tax lines. If the cart has no shipping address with a country, the `CalculateTax` step is skipped. If no tax zone matches the address, no tax lines are created and `taxTotal` stays `0`. ## Persisting Tax Lines on Orders [#persisting-tax-lines-on-orders] When `CreateOrderFromCartAction` converts a cart into an order, it calls `CreateOrderTaxLinesAction`, which stores the tax lines of each order item. Each line copies the rate code, name, and percentage, so future changes to zones or rates have no impact on historical orders. ```php use Shopper\Core\Actions\CreateOrderTaxLinesAction; app(CreateOrderTaxLinesAction::class)->execute($order); ``` The action resolves the shipping address country (from the address `country_name`), runs `TaxCalculator::calculate()` for each order item, creates an `OrderTaxLine` record for each result, and updates `tax_amount` on both the order item and the order itself. It does not delete existing tax lines, so run it only once per order. The action recalculates taxes from the order items instead of copying the cart tax lines. Its context has no province, so only country-level zones apply, and each item is taxed on `unit_price_amount` times `quantity`, before its `discount_amount`. When the cart used a province zone or a discount, the order's `tax_amount` can differ from the cart's `taxTotal`. ### OrderTaxLine Schema [#ordertaxline-schema] | Column | Type | Description | |--------|------|-------------| | `taxable_type` | `string` | Polymorphic type. `CreateOrderTaxLinesAction` writes `OrderItem` lines; `OrderShipping` also has a `taxLines()` relationship | | `taxable_id` | `unsignedBigInteger` | Polymorphic ID | | `tax_rate_id` | `nullable unsignedBigInteger` | Reference to the rate used at time of purchase | | `code` | `string` | Rate code snapshot | | `name` | `string` | Rate name snapshot | | `rate` | `decimal(8,4)` | Rate percentage snapshot | | `amount` | `unsignedInteger` | Tax amount in cents | The `Shopper\Core\Models\OrderTaxLine` model has a `taxable()` morph relationship and a `taxRate()` relationship. ### Accessing Tax Lines on an Order [#accessing-tax-lines-on-an-order] The order itself has no `taxLines()` relationship: load the tax lines through its items, and read the order total from `tax_amount`. ```php use Shopper\Core\Models\Contracts\Order; $order = resolve(Order::class)::query() ->with('items.taxLines') ->find($orderId); $order->tax_amount; foreach ($order->items as $item) { $item->tax_amount; foreach ($item->taxLines as $taxLine) { $taxLine->name; $taxLine->rate; $taxLine->amount; } } ``` ## Tax Providers [#tax-providers] A `TaxProvider` record links a zone to a custom tax calculation service. When a zone has an enabled provider, the calculator uses that provider instead of the built-in system. ### Provider Schema [#provider-schema] | Column | Type | Description | |--------|------|-------------| | `id` | bigint | Primary key | | `identifier` | string | Unique provider code (e.g., `avalara`, `taxjar`) | | `is_enabled` | boolean | Whether the provider is active. Defaults to `true` | The `Shopper\Core\Models\TaxProvider` model has a `taxZones()` relationship and an `isEnabled()` method. The admin has no screen to manage providers: create the records in code or in a seeder. The tax zone form then lists the enabled ones in its **Tax provider** select. ### Custom Tax Providers [#custom-tax-providers] The built-in `SystemTaxProvider` handles most use cases. For regions that require an external API like Avalara, TaxJar, or a homegrown tax service, you can implement the `TaxCalculationProvider` contract and assign it to specific zones. The contract is simple: ```php namespace Shopper\Core\Contracts; use Shopper\Core\Taxes\TaxCalculationContext; use Shopper\Core\Taxes\TaxLine; interface TaxCalculationProvider { public function identifier(): string; /** @return array */ public function getTaxLines(TaxableItem $item, TaxCalculationContext $context): array; } ``` Here is a complete implementation that calls a fictional external tax API: ```php use Shopper\Core\Contracts\TaxCalculationProvider; use Shopper\Core\Contracts\TaxableItem; use Shopper\Core\Taxes\TaxCalculationContext; use Shopper\Core\Taxes\TaxLine; final class AvalaraTaxProvider implements TaxCalculationProvider { public function __construct( private readonly AvalaraClient $client, ) {} public function identifier(): string { return 'avalara'; } public function getTaxLines(TaxableItem $item, TaxCalculationContext $context): array { $defaultRate = $context->resolvedZone->rates() ->where('is_default', true) ->firstOrFail(); $response = $this->client->calculate( amount: $item->getTaxableTotal(), countryCode: $context->countryCode, provinceCode: $context->provinceCode, ); return [ new TaxLine( taxRateId: $defaultRate->id, name: $response->description, code: $response->jurisdictionCode, rate: $response->rate, amount: $response->taxAmountInCents, ), ]; } } ``` `taxRateId` must be the ID of an existing tax rate: cart and order tax lines store it in a `tax_rate_id` foreign key. The example uses the zone's default rate, so the zone needs one. `TaxCalculator` gets its providers from the container under the `TaxCalculationProvider` contract. It resolves its default provider once, without parameters. For a zone linked to an enabled `TaxProvider`, it resolves the contract again and passes the record's `identifier` as a `provider` parameter. Bind the contract to a closure that reads that parameter, in the `register()` method of a service provider: ```php use Shopper\Core\Contracts\TaxCalculationProvider; use Shopper\Core\Taxes\SystemTaxProvider; $this->app->bind( TaxCalculationProvider::class, fn ($app, array $parameters): TaxCalculationProvider => match ($parameters['provider'] ?? null) { 'avalara' => $app->make(AvalaraTaxProvider::class), default => $app->make(SystemTaxProvider::class), }, ); ``` The `identifier()` method of your class does not select it: the match on the `provider` parameter does. Binding the contract directly to your class (`bind(TaxCalculationProvider::class, AvalaraTaxProvider::class)`) would replace `SystemTaxProvider` for every zone, including zones without a provider. Then create a `TaxProvider` record and link it to the zone that should use it: ```php use Shopper\Core\Models\TaxProvider; $provider = TaxProvider::query()->create([ 'identifier' => 'avalara', 'is_enabled' => true, ]); $usZone->update(['provider_id' => $provider->id]); ``` When the calculator resolves a zone that has an enabled provider, it resolves that provider from the container instead of using the system default. Zones without a provider, or with a disabled one, use `SystemTaxProvider`. `TaxCalculator` is a singleton that caches the zone and the provider for each country/province combination, so each combination is resolved once per request. In a queue worker, these caches (and the rates `SystemTaxProvider` caches per zone) last until the worker restarts. ### The TaxCalculationContext [#the-taxcalculationcontext] The `TaxCalculationContext` is a read-only value object that carries the geographic information needed to resolve the correct zone and provider: | Property | Type | Description | |---|---|---| | `countryCode` | `string` | ISO 3166-1 alpha-2 country code (`FR`, `US`, `DE`) | | `provinceCode` | `?string` | Province or state code, matched exactly against the zone `province_code` (`CA`, `NY`) | | `customerId` | `?int` | The authenticated customer's ID, for future customer-level tax rules | | `resolvedZone` | `?TaxZone` | Pre-resolved zone; set internally by the calculator to avoid redundant queries | ### The TaxableItem Contract [#the-taxableitem-contract] Any object you pass to `TaxCalculator::calculate()` must implement `Shopper\Core\Contracts\TaxableItem`: | Method | Return | Description | |--------|--------|-------------| | `getTaxableTotal()` | `int` | The line total to tax, in cents (see the adapters below for what each one includes) | | `getProductType()` | `?string` | Product type value (`standard`, `variant`, `virtual`, `external`) | | `getProductId()` | `?int` | The product's primary key | | `getCategoryIds()` | `array` | Primary keys of the categories the product is attached to | The contract exposes a single `getTaxableTotal()` rather than a separate unit amount and quantity. The provider taxes that total in one pass, so a line whose total is not evenly divisible by its quantity is never rounded per unit. This keeps exclusive zones from overcharging by a cent and keeps inclusive VAT breakdowns balanced (net plus tax always equals gross). Shopper ships two ready-made adapters: - `Shopper\Cart\Taxes\CartLineTaxAdapter` wraps a `CartLine` for use during cart calculation; the taxable total is the post-discount line total in cents, and a variant line uses its parent product's ID - `Shopper\Core\Taxes\OrderItemTaxAdapter` wraps an `OrderItem` for use in `CreateOrderTaxLinesAction`; the taxable total is `unit_price_amount` times `quantity` in cents (the item's `discount_amount` is not subtracted), and the product ID is the item's `product_id` (the variant ID for a variant line, so `product` rules do not match it) If you are building a custom checkout flow or need to calculate taxes outside of a cart, you can implement `TaxableItem` directly on any of your objects and call `TaxCalculator::calculate()` with a manually constructed `TaxCalculationContext`. `TaxCalculator` is registered as a singleton, so resolve it from the container: ```php use Shopper\Core\Taxes\TaxCalculationContext; use Shopper\Core\Taxes\TaxCalculator; $calculator = resolve(TaxCalculator::class); $taxLines = $calculator->calculate( $item, new TaxCalculationContext(countryCode: 'US', provinceCode: 'CA'), ); foreach ($taxLines as $taxLine) { $taxLine->name; $taxLine->rate; $taxLine->amount; } ``` `calculateMany(array $items, TaxCalculationContext $context)` returns the tax lines of several items at once, keyed like the input array, and `resolveZone(TaxCalculationContext $context)` returns the matching `TaxZone`, or `null`. # Two Factor Authentication (/2.x/two-factor) Secure your account with two-step authentication. Two-step authentication (also known as two-factor authentication or multifactor authentication) provides a more secure login process. When you attempt to sign in, you need to complete two separate steps: - Enter your email and password. - Enter the code shown by an authenticator app on your mobile device. These two steps make it much more difficult for an unauthorized person to access your account. Even if they are able to find your password, they will not be able to connect without the second step. Authentication in two steps combines two factors among something you know (such as your email and password), something you have (such as a one-time code from an authenticator app) and something you are (biometric authentication, such as a fingerprint). Shopper uses the first two: your password and a code from an authenticator app. Every admin user can turn on two-step authentication, but only for their own account: the store owner cannot turn it on for staff members. If several employees manage your store, each of them turns it on from their own profile. ## Configuration [#configuration] Two-factor authentication must be enabled in your configuration before the feature becomes available in the UI. In the `config/shopper/auth.php` file, the `2fa_enabled` option reads the `SHOPPER_ENABLED_TWO_FACTOR` environment variable and is `false` by default: ```php title="config/shopper/auth.php" '2fa_enabled' => env('SHOPPER_ENABLED_TWO_FACTOR', false), ``` Turn it on in your `.env` file: ```dotenv SHOPPER_ENABLED_TWO_FACTOR=true ``` When this option is `false`, the two-factor authentication section does not appear on the account page and the login flow does not prompt for a second factor, even if a user has previously configured it. Your user model must also implement the contracts described in [Interfaces and Traits](/2.x/two-factor#interfaces-and-traits). Without `HasStoreAuthentication`, the section stays hidden and the login never asks for a code, whatever the value of `2fa_enabled`. ## Enabling Two-Factor Authentication [#enabling-two-factor-authentication] To enable two-step authentication, you'll need first to download an authenticator app to your mobile device. The app will be able to scan QR codes and retrieve authentication data for you. Recommended authenticator apps: - [Google Authenticator](https://support.google.com/accounts/answer/1066447) - [Duo Mobile](https://guide.duo.com/third-party-accounts) - [Amazon AWS MFA](https://aws.amazon.com/iam/details/mfa) - [Authenticator](https://www.microsoft.com/store/p/microsoft-authenticator/9nblgggzmcj6) In addition, you should store the listed recovery codes in a secure password manager such as [1Password](https://1password.com). When you install an authenticator app, make sure that you follow its instructions carefully. After your app is successfully downloaded and set up, you can activate the feature in Shopper. From your administrator interface, click your profile picture in the upper right corner, then click **Personal Account**. Scroll to the **Two Factor Authentication** section and click **Enable Two Factor**. A modal asks you to confirm your password. Enter your current password and click **Confirm**. If you confirmed your password recently, within the `password_timeout` delay set in `config/auth.php`, Shopper skips the modal. Shopper turns two-factor authentication on as soon as you confirm, and shows a QR code and eight recovery codes. Scan the QR code with your authenticator app right away: the section shows it only this once, and your next login asks for a code from the app. Store the recovery codes in your password manager. If the user loses access to their mobile device, the login page will allow them to authenticate using one of their recovery codes instead of the temporary token provided by their mobile device's authenticator application. Later, **Show Recovery Codes** displays your current recovery codes again and **Regenerate Recovery Codes** replaces all eight with new ones. Both ask for your password, like **Enable Two Factor**. Now when you try to log in, two-factor authentication will require your mobile device. ## Logging in with Two-Factor Authentication [#logging-in-with-two-factor-authentication] Go to the Shopper administration login page and enter your email address and password. Click the **Login** button. The login form will switch to a two-factor challenge, prompting you to enter your authentication code. If you used a two-factor authentication app, open it and enter the code displayed, then click **Login**. If you can't access your authenticator app, click **Use a recovery code** and enter one of your saved recovery codes to authenticate. Each recovery code works once. After you use one, Shopper replaces it with a new code: click **Show Recovery Codes** on your profile to see the updated list. After a password reset, a user with two-factor authentication is sent back to the login page and goes through the challenge, instead of being signed in directly. ## Disable Two-Factor Authentication [#disable-two-factor-authentication] From your administrator interface, click your profile picture in the upper right corner, then click **Personal Account**. In the **Two Factor Authentication** section, click **Disable**. Enter your password in the confirmation modal and click **Confirm**. Shopper deletes your secret and your recovery codes: to turn two-factor authentication back on later, you scan a new QR code. ## Developer Integration [#developer-integration] ### Interfaces and Traits [#interfaces-and-traits] Two-factor authentication is implemented through two focused interfaces (following the Interface Segregation Principle): **`Shopper\Contracts\HasStoreAuthentication`** manages the TOTP secret and QR code: - `getStoreAuthenticationSecret(): ?string` - `saveStoreAuthenticationSecret(?string $secret): void` - `getStoreAuthenticationHolderName(): string` - `getStoreAuthenticationQrCodeSvg(): string` - `getStoreAuthenticationQrCodeUrl(): string` **`Shopper\Contracts\HasStoreAuthenticationRecovery`** manages recovery codes: - `getStoreAuthenticationRecoveryCodes(): ?array` - `saveStoreAuthenticationRecoveryCodes(?array $codes): void` - `replaceStoreAuthenticationRecoveryCode(string $code): void` The default implementation is provided by two traits. The account page uses both interfaces, so add both to the user model from [Prepare Your User Model](/2.x/installation#prepare-your-user-model): ```php title="app/Models/User.php" use Illuminate\Foundation\Auth\User as Authenticatable; use Shopper\Contracts\HasStoreAuthentication; use Shopper\Contracts\HasStoreAuthenticationRecovery; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; use Shopper\Traits\InteractsWithStoreAuthentication; use Shopper\Traits\InteractsWithStoreAuthenticationRecovery; class User extends Authenticatable implements ShopperUser, HasStoreAuthentication, HasStoreAuthenticationRecovery { use InteractsWithShopper; use InteractsWithStoreAuthentication; use InteractsWithStoreAuthenticationRecovery; } ``` The traits encrypt the secret and the recovery codes before saving them. `getStoreAuthenticationHolderName()` returns the user's email: the authenticator app lists the account under `config('app.name')` and that email. Override the method to show another name. Shopper generates the secret, builds the QR code URL and checks the codes through `Shopper\Contracts\TwoFactorAuthenticationProvider`, bound in the container to an implementation based on `pragmarx/google2fa`. Bind your own class to this contract in a service provider to use another TOTP library. Enabling two-factor authentication dispatches the `Shopper\Events\TwoFactor\TwoFactorAuthenticationEnabled` event, with the user in its `$user` property. ### Database Columns [#database-columns] The following columns are added to the `users` table by Shopper's migrations: | Column | Type | Description | |---|---|---| | `store_two_factor_secret` | text (nullable) | Encrypted TOTP secret | | `store_two_factor_recovery_codes` | text (nullable) | Encrypted JSON array of recovery codes | There is no confirmation column: two-factor authentication is on as soon as the secret is saved. A database that still has the older `two_factor_secret` and `two_factor_recovery_codes` columns gets them renamed by the `rename_two_factor_columns_on_users_table` migration when you run `php artisan migrate`. # Upgrade Guide (/2.x/upgrade) Shopper documentation always reflects the latest release of the current major version. When a new minor version ships, the docs are updated to match. Upgrade guides document every breaking change, new feature, and migration step between versions. ## Before You Start [#before-you-start] Before upgrading, take these precautions: 1. **Back up your database.** E-commerce data (orders, customers, prices) is difficult to recover if a migration fails. 2. **Run the upgrade on a staging environment first.** Verify everything works before touching production. 3. **If upgrading across multiple versions** (e.g., v2.2 to v2.5), follow each guide in sequence. Do not skip versions. ## Upgrade Guides [#upgrade-guides] | From | To | Summary | |------|-----|---------| | [v2.9](/2.x/upgrade/v2-9-to-v2-10) | v2.10 | Security release: admin authorization audit, slide-over IDOR fix, exact tax on discounted totals (`TaxableItem` contract change), atomic stock reservation (`StockReserver` contract, `Stockable::tracksInventory()`), guest per-user discount block. No database migrations | | [v2.8](/2.x/upgrade/v2-8-to-v2-9) | v2.9 | Laravel 13 support, onboarding wizard rebuilt on Filament Schema, cache stores scalars instead of models, Stripe SDK upgraded to v19. No database migrations | | [v2.7](/2.x/upgrade/v2-7-to-v2-8) | v2.8 | Security release: authorization guards across admin Livewire components, atomic discount reservation, `orders` discount snapshot columns | | [v2.6](/2.x/upgrade/v2-6-to-v2-7) | v2.7 | Money values stored in smallest currency unit (cents), slide-over components replaced, 2FA split into SOLID interfaces | | [v2.5](/2.x/upgrade/v2-5-to-v2-6) | v2.6 | Cart package, tax system, auth models moved to admin package, event renaming, render hooks | | [v2.4](/2.x/upgrade/v2-4-to-v2-5) | v2.5 | Order system split into three independent statuses (order, payment, shipping), payment drivers, shipment tracking | | [v2.2](/2.x/upgrade/v2-2-to-v2-3) | v2.3 | Product Tags feature with new permissions and feature flag | | [v2.1](/2.x/upgrade/v2-1-to-v2-2) | v2.2 | Repository pattern removed, Model Contracts system, Filament v4, ShopperUser trait, sidebar redesign | There is no upgrade guide for v2.3 to v2.4. That release only added Spanish translations and internal render hooks with no breaking changes. ## Getting Help [#getting-help] If you encounter issues during an upgrade: - Check the [GitHub Issues](https://github.com/shopperlabs/shopper/issues) - Join the [Discord community](https://laravelshopper.dev/discord) - Review the [changelog](https://github.com/shopperlabs/shopper/releases) # From v2.1 to v2.2 (/2.x/upgrade/v2-1-to-v2-2) **Estimated Upgrade Time:** 15-30 minutes for most applications. ## Requirements [#requirements] Shopper 2.2 requires: | Dependency | Version | |------------|---------| | PHP | ^8.3 | | Laravel | ^11.0 \| ^12.0 | | Filament | ^4.5 | | Livewire | ^3.6 | | Tailwind CSS | ^4.1 | **Laravel 10 is no longer supported.** You must upgrade to Laravel 11 or 12 before upgrading to Shopper 2.2. ## Updating Dependencies [#updating-dependencies] Update your `composer.json` file to require Shopper 2.2: ```json "require": { "php": "^8.3", "laravel/framework": "^11.0|^12.0", "shopper/framework": "^2.2" } ``` Then run: ```bash composer update -W ``` After updating Composer dependencies, run the migrations: ```bash php artisan migrate ``` --- ## High Impact Changes [#high-impact-changes] ### Repository Pattern Removed [#repository-pattern-removed] **Likelihood of Impact: High** The Repository pattern has been completely removed in favor of a configurable Model Contract system. This is a **breaking change** if you were using repositories directly. #### Before (v2.1) [#before-v21] ```php use Shopper\Core\Repositories\ProductRepository; use Shopper\Core\Repositories\UserRepository; // Using repositories $products = (new ProductRepository)->all(); $user = (new UserRepository)->create([...]); // Dependency injection public function __construct( private ProductRepository $productRepository ) {} ``` #### After (v2.2) [#after-v22] ```php use Shopper\Models\Product; use Shopper\Core\Models\Contracts\Product as ProductContract; // Using models directly with Model $products = Product::query()->get(); // Or via the contract for configured model $products = resolve(ProductContract::class)::query()->get(); // Type-hint the contract public function __construct( public ProductContract $product ) {} ``` The `query()` method automatically uses the configured model class from `config/shopper/models.php`. ### Configuration: `users` Key Renamed to `roles` [#configuration-users-key-renamed-to-roles] **Likelihood of Impact: High** The `users` configuration key in `config/shopper/core.php` has been renamed to `roles` with updated sub-keys. #### Before (v2.1) [#before-v21-1] ```php // config/shopper/core.php 'users' => [ 'admin_role' => 'administrator', 'manager_role' => 'manager', 'default_role' => 'user', ], ``` #### After (v2.2) [#after-v22-1] ```php // config/shopper/core.php 'roles' => [ 'admin' => 'administrator', 'manager' => 'manager', 'user' => 'user', ], ``` **Update your code references:** ```php // Before config('shopper.core.users.admin_role') config('shopper.core.users.default_role') // After config('shopper.core.roles.admin') config('shopper.core.roles.user') ``` ### ShopperUser Interface & Trait [#shopperuser-interface--trait] **Likelihood of Impact: High** The `Shopper\Core\Models\User` model has been removed. Your User model must now implement the `ShopperUser` interface and use the `ShopperUser` trait. #### Before (v2.1) [#before-v21-2] ```php namespace App\Models; use Shopper\Core\Models\User as ShopperUser; class User extends ShopperUser { // ... } ``` #### After (v2.2) [#after-v22-2] ```php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Shopper\Core\Models\Contracts\ShopperUser as ShopperUserContract; use Shopper\Core\Traits\ShopperUser; class User extends Authenticatable implements ShopperUserContract { use ShopperUser; protected $fillable = [ 'first_name', 'last_name', 'email', 'password', 'phone_number', 'birth_date', 'gender', 'avatar_type', 'avatar_location', 'timezone', 'opt_in', ]; protected $hidden = [ 'password', 'remember_token', 'two_factor_recovery_codes', 'two_factor_secret', ]; } ``` The `ShopperUser` trait provides all the necessary methods: `isAdmin()`, `isManager()`, `isVerified()`, `addresses()`, `orders()`, and the `customers`/`administrators` scopes. ### Filament v4 Upgrade [#filament-v4-upgrade] **Likelihood of Impact: High** **Shopper v2.2** requires **Filament v4.5**. If you have customized any Filament components or forms, review the [Filament v4 upgrade guide](https://filamentphp.com/docs/4.x/upgrade-guide). Key changes affecting Shopper users: - Form schema syntax has been updated - Modal components have been replaced with Filament Actions - Table syntax has been updated --- ## Medium Impact Changes [#medium-impact-changes] ### New Models in Configuration [#new-models-in-configuration] **Likelihood of Impact: Medium** New models have been added to `config/shopper/models.php`: `address`, `inventory`, `order`, and `supplier`. If you have a published `config/shopper/models.php`, add these entries: ```php return [ 'address' => \Shopper\Core\Models\Address::class, // ... existing models ... 'inventory' => \Shopper\Core\Models\Inventory::class, 'order' => \Shopper\Core\Models\Order::class, 'supplier' => \Shopper\Core\Models\Supplier::class, ]; ``` ### New Permissions [#new-permissions] **Likelihood of Impact: Medium** New permissions have been added for **reviews**, **product variants**, and **suppliers**. These must be created in your database for existing installations. Create the permissions and assign them to your admin role: ```php use Shopper\Core\Models\Permission; use Spatie\Permission\Models\Role; Permission::generate('reviews', 'products'); Permission::generate('product_variants', 'products'); Permission::generate('suppliers', 'products'); $admin = Role::findByName('administrator'); $admin->givePermissionTo([ 'browse_reviews', 'read_reviews', 'edit_reviews', 'add_reviews', 'delete_reviews', 'browse_product_variants', 'read_product_variants', 'edit_product_variants', 'add_product_variants', 'delete_product_variants', 'browse_suppliers', 'read_suppliers', 'edit_suppliers', 'add_suppliers', 'delete_suppliers', ]); ``` You can run this code in a migration, a tinker session, or create the permissions directly from the admin UI in the Roles & Permissions settings page. If you don't create these permissions, users attempting to access Reviews, Product Variants, or Suppliers pages will encounter authorization errors. ### Order Number Generator Configuration [#order-number-generator-configuration] **Likelihood of Impact: Medium** The order number generator configuration in `config/shopper/orders.php` has been updated with new options for more flexible number formatting. #### Before (v2.1) [#before-v21-3] ```php 'generator' => [ 'start_sequence_from' => 1, 'prefix' => 'SH_', 'pad_length' => 1, 'pad_string' => '0', ], ``` #### After (v2.2) [#after-v22-3] ```php 'generator' => [ 'prefix' => 'ORD', 'separator' => '-', 'date_format' => 'Ymd', 'start_sequence_from' => 1, 'pad_length' => 6, 'pad_string' => '0', ], ``` New options: - `separator`: character between each part of the number - `date_format`: PHP date format included in the number (set to `null` to disable) - `prefix` can now be set to `null` to disable Examples of generated numbers depending on configuration: - Default (`prefix => null`) → `20250123-000001` - With prefix (`prefix => 'ORD'`) → `ORD-20250123-000001` - Without date (`date_format => null`) → `000001` ### Custom Modal Components Removed [#custom-modal-components-removed] **Likelihood of Impact: Medium** Several custom modal components have been removed and replaced with Filament Actions or slide-overs: | Removed Component | Replacement | |-------------------|-------------| | `Modals\CreatePermission` | Integrated into parent component | | `Modals\CreateRole` | Integrated into parent component | | `Modals\ConfirmPassword` | Filament Action | | `Modals\LogoutOthersBrowser` | Filament Action | | `Modals\PaymentMethodForm` | Slide-over | | `Modals\CollectionProductsList` | `SlideOvers\CollectionProductsList` | | `Modals\RelatedProductsList` | `SlideOvers\RelatedProductsList` | If you have overridden these components, update your `config/shopper/components/setting.php`: ```php // The modals section has been removed // Modal functionality is now built into parent components 'components' => [ 'settings.locations.form' => Components\Settings\Locations\InventoryForm::class, 'settings.legal.privacy' => Components\Settings\Legal\Privacy::class, // ... other components 'slide-overs.create-team-member' => Livewire\SlideOvers\CreateTeamMember::class, // ... slide-overs ], ``` ### Custom Button Components Removed [#custom-button-components-removed] **Likelihood of Impact: Medium** Custom button Blade components have been removed in favor of Filament's button components: | Removed Component | Replacement | |-------------------|-------------| | `` | `` | | `` | `` | | `` | `` | #### Before (v2.1) [#before-v21-4] ```blade Save Changes ``` #### After (v2.2) [#after-v22-4] ```blade Save Changes ``` ### Card with Gray Heading Removed [#card-with-gray-heading-removed] **Likelihood of Impact: Medium** The `` component has been removed. Use the standard `` component or Filament's Section component instead. --- ## Low Impact Changes [#low-impact-changes] ### Tailwind CSS v4 [#tailwind-css-v4] **Likelihood of Impact: Low** Shopper 2.2 uses Tailwind CSS v4. If you have custom CSS that extends Shopper's styles, review the [Tailwind v4 upgrade guide](https://tailwindcss.com/docs/v4-beta). The CSS architecture has been updated - if you've customized styles, you may need to update your imports. ### PostgreSQL Support [#postgresql-support] **Likelihood of Impact: Low** Shopper 2.2 adds official PostgreSQL support. No action required for MySQL/MariaDB users. ### Sidebar Redesign [#sidebar-redesign] **Likelihood of Impact: Low** The admin sidebar has been redesigned with Alpine.js state management: - Collapsible sidebar with persistent state via localStorage - New submenu support with arrow indicators - Improved mobile responsiveness If you have customized sidebar views, update them to use the new structure in `resources/views/components/layouts/app/sidebar/`. ### SKU Uniqueness for Variants [#sku-uniqueness-for-variants] **Likelihood of Impact: Low** Product variant SKUs now have a composite unique constraint scoped to `product_id`. This means: - SKUs must be unique within a product (not globally) - Auto-generated SKUs now use format: `{PRODUCT_SKU}-{VARIANT_SLUG}` If you have custom variant creation logic, ensure SKUs are unique per product. ### HasPrices Trait: New `getPrice()` Method [#hasprices-trait-new-getprice-method] **Likelihood of Impact: Low** A new `getPrice()` method has been added to the `HasPrices` trait: ```php // Get price for default currency $variant->getPrice(); // ?Price // Get price for specific currency $variant->getPrice('USD'); // ?Price ``` This method is now part of the `Priceable` contract. --- ## Deprecations [#deprecations] The following features are deprecated and will be removed in v3.0: | Deprecated | Replacement | |------------|-------------| | Repository classes | Model contracts with `resolvedQuery()` | | `config('shopper.core.users.*')` | `config('shopper.core.roles.*')` | --- ## Migration Checklist [#migration-checklist] Ensure your environment runs PHP ^8.3 and Laravel ^11.0 or ^12.0 before proceeding. Update `shopper/framework` to `^2.2` in `composer.json`, then run `composer update -W`. Run `php artisan migrate` to apply all new migrations. In `config/shopper/core.php`, rename the `users` key to `roles` and update its sub-keys (`admin_role` → `admin`, `default_role` → `user`). In `config/shopper/models.php`, add the `address`, `inventory`, `order`, and `supplier` entries if you have a published config file. Run `Permission::generate()` for `reviews`, `product_variants`, and `suppliers`, then assign the generated permissions to the `administrator` role. In `config/shopper/orders.php`, update the generator array to include the new `separator` and `date_format` keys. Replace `extends ShopperUser` with `implements ShopperUserContract` and add `use ShopperUser` in your `App\Models\User` class. Replace all direct repository class usage with model contracts resolved via `resolve(ContractClass::class)` or direct model queries. Replace `` with the equivalent `` variants. Update any overridden modal components to their slide-over replacements. Run `php artisan optimize:clear`. # From v2.2 to v2.3 (/2.x/upgrade/v2-2-to-v2-3) **Estimated Upgrade Time:** 5-10 minutes for most applications. ## Updating Dependencies [#updating-dependencies] Update your `composer.json` file to require Shopper 2.3: ```json "require": { "shopper/framework": "^2.3" } ``` Then run: ```bash composer update -W ``` After updating Composer dependencies, run the migrations: ```bash php artisan migrate ``` --- ## New Features [#new-features] ### Product Tags [#product-tags] Shopper 2.3 introduces **Product Tags**, simple flat labels you can attach to products for cross-cutting organization. Unlike categories (hierarchical) or collections (rule-based), tags are flexible and ideal for seasonal labels, marketing campaigns, or storefront filtering. See the [Product Tags documentation](/2.x/product-tags) for full details. #### New Permissions [#new-permissions] New permissions have been added for **tags**. For existing installations, create them and assign to your admin role: ```php use Shopper\Core\Models\Permission; use Spatie\Permission\Models\Role; Permission::generate('tags', 'products'); $admin = Role::findByName('administrator'); $admin->givePermissionTo([ 'browse_tags', 'read_tags', 'edit_tags', 'add_tags', 'delete_tags', ]); ``` If you don't create these permissions, users will not be able to access the Tags page or manage tags from the product form. #### New Feature Flag [#new-feature-flag] A new `tag` feature flag has been added to `config/shopper/features.php`. If you have a published config file, add: ```php use Shopper\Enum\FeatureState; return [ // ... existing features 'tag' => FeatureState::Enabled, ]; ``` Set to `FeatureState::Disabled` if you don't need tags in your store. #### Published Components [#published-components] If you have published product components via `php artisan shopper:component:publish product`, add the new tag page to your `config/shopper/components/product.php`: ```php 'pages' => [ // ... existing pages 'tag-index' => \Shopper\Livewire\Pages\Tag\Index::class, ], ``` --- ## Migration Checklist [#migration-checklist] Update `shopper/framework` to `^2.3` in `composer.json`, then run `composer update -W`. Run `php artisan migrate` to create the `product_tags` table. Run `Permission::generate('tags', 'products')` and assign the five generated permissions (`browse_tags`, `read_tags`, `edit_tags`, `add_tags`, `delete_tags`) to the `administrator` role. If you have published `config/shopper/features.php`, add the `tag` feature flag. If you have published `config/shopper/components/product.php`, add the `tag-index` component entry. Run `php artisan optimize:clear`. # From v2.4 to v2.5 (/2.x/upgrade/v2-4-to-v2-5) **Estimated Upgrade Time:** 15-30 minutes for most applications. ## Updating Dependencies [#updating-dependencies] Update your `composer.json` file to require Shopper 2.5: ```json "require": { "shopper/framework": "^2.5" } ``` Then run: ```bash composer update -W ``` After updating Composer dependencies, run the migrations: ```bash php artisan migrate ``` The `shopper/payment` package is now a dependency of `shopper/framework` and is installed automatically. It provides the payment driver system, transaction tracking, and the `PaymentProcessingService`. For Stripe support, install the driver addon separately: `composer require shopper/stripe`. See the [Stripe addon documentation](/2.x/addons/stripe) for setup instructions. --- ## High Impact Changes [#high-impact-changes] ### Three-Status Order System [#three-status-order-system] **Likelihood of Impact: High** The monolithic `OrderStatus` enum has been split into three independent enums, each tracking a different concern: | Concern | Enum | Values | |---------|------|--------| | Order lifecycle | `OrderStatus` | `New`, `Processing`, `Completed`, `Cancelled`, `Archived` | | Payment | `PaymentStatus` | `Pending`, `Authorized`, `Paid`, `PartiallyRefunded`, `Refunded`, `Voided` | | Shipping | `ShippingStatus` | `Unfulfilled`, `PartiallyShipped`, `Shipped`, `PartiallyDelivered`, `Delivered`, `PartiallyReturned`, `Returned` | The old `OrderStatus` values `Pending`, `Registered`, `Paid`, `Shipped`, `Delivered`, and `Returned` have been removed. You must update any code that references these values. #### Before (v2.4) [#before-v24] ```php use Shopper\Core\Enum\OrderStatus; // Check payment if ($order->status === OrderStatus::Paid) { // ... } // Check shipping if ($order->status === OrderStatus::Shipped) { // ... } // Check delivery if ($order->status === OrderStatus::Delivered) { // ... } ``` #### After (v2.5) [#after-v25] ```php use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Enum\PaymentStatus; use Shopper\Core\Enum\ShippingStatus; // Check payment if ($order->payment_status === PaymentStatus::Paid) { // ... } // Check shipping if ($order->shipping_status === ShippingStatus::Shipped) { // ... } // Check delivery if ($order->shipping_status === ShippingStatus::Delivered) { // ... } ``` The Order model now provides convenience methods for common status checks: `isNew()`, `isProcessing()`, `isCompleted()`, `isArchived()`, `isPaid()`, `isPaymentAuthorized()`, `isRefunded()`, `isShipped()`, `isShippingPending()`. #### Automatic Data Migration [#automatic-data-migration] The migration automatically maps your existing order statuses to the new three-status system. No manual data migration is needed. | Old `status` value | New `status` | New `payment_status` | New `shipping_status` | |---|---|---|---| | `pending` | `new` | `pending` | `unfulfilled` | | `registered` | `processing` | `pending` | `unfulfilled` | | `paid` | `processing` | `paid` | `unfulfilled` | | `shipped` | `processing` | `paid` | `shipped` | | `delivered` | `processing` | `paid` | `delivered` | | `completed` | `completed` | `paid` | *(unchanged)* | | `cancelled` | `cancelled` | *(unchanged)* | *(unchanged)* | If you have custom order status values beyond the ones listed above, they will **not** be migrated automatically. You must handle them manually before or after running `php artisan migrate`. ### PaymentMethod & Carrier Logo Handling [#paymentmethod--carrier-logo-handling] **Likelihood of Impact: High** The `logo` column has been removed from both the `payment_methods` and `carriers` tables. Logos are now managed through [Spatie Media Library](https://spatie.be/docs/laravel-medialibrary). A new `driver` column has been added to both tables. #### Before (v2.4) [#before-v24-1] ```php // Accessing logos $paymentMethod->logo; // string|null, file path $carrier->logo; // string|null, file path ``` #### After (v2.5) [#after-v25-1] ```php // Accessing logos via Media Library $paymentMethod->logoUrl(); // ?string, full URL or null $carrier->logoUrl(); // ?string, full URL or null ``` Both models now implement `Spatie\MediaLibrary\HasMedia` and use the `HasMedia` trait. If you stored logos using the old `logo` column, you need to manually re-upload them through the admin panel or migrate the files to the media library programmatically. The old column data is removed by the migration. ### Payment System [#payment-system] **Likelihood of Impact: High** Shopper 2.5 introduces a complete payment driver system through the new `shopper/payment` package, which is included as a dependency of `shopper/framework`. Key components: - **`PaymentProcessingService`**. Orchestrates payment operations (initiate, authorize, capture, refund, cancel) through drivers - **`PaymentTransaction`** model. Records every payment operation with driver, type, status, amount, and provider reference - **`PaymentDriver`** contract. Interface for implementing payment providers - **`PaymentManager`**. Resolves and manages payment drivers (a manual driver is included by default) New enums in `Shopper\Payment\Enum`: | Enum | Values | |------|--------| | `TransactionType` | `Initiate`, `Authorize`, `Capture`, `Refund`, `Cancel` | | `TransactionStatus` | `Pending`, `Success`, `Failed` | The admin panel now includes a **Capture payment** button on the order detail page for orders with `PaymentStatus::Authorized`. For Stripe payments, install the addon: `composer require shopper/stripe`. See the [Payments documentation](/2.x/payments) for the full API reference. --- ## Medium Impact Changes [#medium-impact-changes] ### Order Contract Interface [#order-contract-interface] **Likelihood of Impact: Medium** If you implement a custom Order model through the `Shopper\Core\Models\Contracts\Order` interface, you must add the following methods: ```php public function setDefaultOrderStatus(): void; public function canBeCancelled(): bool; public function isNotCancelled(): bool; public function isNew(): bool; public function isProcessing(): bool; public function isCompleted(): bool; public function isArchived(): bool; public function isPaid(): bool; public function isPaymentPending(): bool; public function isPaymentAuthorized(): bool; public function isRefunded(): bool; public function isShipped(): bool; public function isShippingPending(): bool; ``` Use `Shopper\Core\Models\Order` as a reference implementation. The model sets default statuses automatically via `setDefaultOrderStatus()` in its `booted()` method. ### Column Renamed: `canceled_at` to `cancelled_at` [#column-renamed-canceled_at-to-cancelled_at] **Likelihood of Impact: Medium** The `canceled_at` column on the orders table has been renamed to `cancelled_at` (double-L British spelling) for consistency. #### Before (v2.4) [#before-v24-2] ```php $order->canceled_at; ``` #### After (v2.5) [#after-v25-2] ```php $order->cancelled_at; ``` Update any code, queries, or Blade templates that reference the old column name. ### OrderItem Fulfillment Tracking [#orderitem-fulfillment-tracking] **Likelihood of Impact: Medium** Two new columns have been added to the `order_items` table: - `fulfillment_status`. Tracks per-item fulfillment using the new `FulfillmentStatus` enum (`Pending`, `ForwardedToSupplier`, `Processing`, `Shipped`, `Delivered`, `Cancelled`) - `order_shipping_id`. Links each item to a specific shipment This enables partial fulfillment: different items in the same order can be at different fulfillment stages and shipped in different packages. If you query or manipulate order items directly, be aware of these new columns. No action is required unless you have custom logic that conflicts. ### Order Detail Page Decomposed into Components [#order-detail-page-decomposed-into-components] **Likelihood of Impact: Medium** The order detail page has been restructured from a single monolithic page into independent, overridable Livewire components. Each section of the page is now its own component, registered in `config/shopper/components/order.php`. Components marked **New** were added in v2.5. Components marked **Existing** were already present but have been refactored. | Component | Alias | Type | Description | |-----------|-------|------|-------------| | `Index` | `shopper-order-index` | Existing | Order listing with filters and tabs | | `Detail` | `shopper-order-detail` | Existing | Order detail page (refactored, now uses sub-components) | | **`Shipments`** | `shopper-order-shipments` | **New** | Centralized shipment list with filters and tab navigation | | **`Fulfillment`** | `shopper-order-fulfillment` | **New** | Fulfillment progress stepper, shipping address, create shipment button | | **`OrderCustomer`** | `shopper-order-customer` | **New** | Customer info, shipping and billing addresses | | **`OrderItems`** | `shopper-order-items` | **New** | Paginated order items with fulfillment status badges | | **`OrderNotes`** | `shopper-order-notes` | **New** | Notes editor with save action | | **`OrderSummary`** | `shopper-order-summary` | **New** | Financial summary, shipping method, payment method | | **`ShipmentTimeline`** | `shopper-order-shipment-timeline` | **New** | Shipment event timeline with "Add event" action | | **`CreateShippingLabel`** | `shopper-slide-overs.create-shipping-label` | **New** | Slide-over form to create a shipment and assign unfulfilled items | | **`ShipmentDetail`** | `shopper-slide-overs.shipment-detail` | **New** | Slide-over with shipment detail, event timeline, and delivery actions | If you have published order components via `php artisan shopper:component:publish order`, update your `config/shopper/components/order.php` to include the new entries: ```php 'pages' => [ 'order-index' => \Shopper\Livewire\Pages\Order\Index::class, 'order-detail' => \Shopper\Livewire\Pages\Order\Detail::class, 'order-shipments' => \Shopper\Livewire\Pages\Order\Shipments::class, // [!code ++] ], 'components' => [ 'order-customer' => \Shopper\Livewire\Components\Orders\OrderCustomer::class, // [!code ++] 'order-fulfillment' => \Shopper\Livewire\Components\Orders\Fulfillment::class, // [!code ++] 'order-items' => \Shopper\Livewire\Components\Orders\OrderItems::class, // [!code ++] 'order-notes' => \Shopper\Livewire\Components\Orders\OrderNotes::class, // [!code ++] 'order-shipment-timeline' => \Shopper\Livewire\Components\Orders\ShipmentTimeline::class, // [!code ++] 'order-summary' => \Shopper\Livewire\Components\Orders\OrderSummary::class, // [!code ++] 'slide-overs.create-shipping-label' => \Shopper\Livewire\SlideOvers\CreateShippingLabel::class, // [!code ++] 'slide-overs.shipment-detail' => \Shopper\Livewire\SlideOvers\ShipmentDetail::class, // [!code ++] ], ``` You can override any component by pointing the config key to your own class. For example, to customize how order items are displayed, create your own component extending `Shopper\Livewire\Components\Orders\OrderItems` and update the config entry. ### OrderShipping: Status Column & Events [#ordershipping-status-column--events] **Likelihood of Impact: Medium** The `order_shipping` table has a new `status` column (using the `ShipmentStatus` enum with 8 values) and the `shipped_at` column is now nullable. A new `order_shipping_events` table tracks the complete delivery timeline for each shipment. The `OrderShipping` model now uses the `HasFulfillmentTransitions` trait, which provides a state machine for valid status transitions: ```php use Shopper\Core\Enum\ShipmentStatus; // Check allowed transitions $shipment->canTransitionTo(ShipmentStatus::InTransit); // bool // Execute a transition (logs an event automatically) $shipment->transitionTo(ShipmentStatus::InTransit, [ 'location' => 'Distribution Center', 'description' => 'Package picked up by carrier', ]); ``` See the [Fulfillment documentation](/2.x/fulfillment) for the full transition map. --- ## Low Impact Changes [#low-impact-changes] ### New Events [#new-events] **Likelihood of Impact: Low** Three new events have been added in `Shopper\Core\Events\Orders`: | Event | When it fires | |-------|---------------| | `OrderArchived` | An order is archived | | `OrderShipmentCreated` | A new shipment is created for an order | | `OrderShipmentDelivered` | A shipment is marked as delivered | The `SyncOrderShippingStatusListener` automatically listens to `OrderShipmentCreated` and syncs the order's `shipping_status` based on all items' fulfillment states. ### New Enums [#new-enums] **Likelihood of Impact: Low** Four new enums have been added to `Shopper\Core\Enum`: | Enum | Values | |------|--------| | `PaymentStatus` | `Pending`, `Authorized`, `Paid`, `PartiallyRefunded`, `Refunded`, `Voided` | | `ShippingStatus` | `Unfulfilled`, `PartiallyShipped`, `Shipped`, `PartiallyDelivered`, `Delivered`, `PartiallyReturned`, `Returned` | | `ShipmentStatus` | `Pending`, `PickedUp`, `InTransit`, `AtSortingCenter`, `OutForDelivery`, `Delivered`, `DeliveryFailed`, `Returned` | | `FulfillmentStatus` | `Pending`, `ForwardedToSupplier`, `Processing`, `Shipped`, `Delivered`, `Cancelled` | All follow the same pattern as existing enums: backed string enums implementing `HasColor`, `HasIcon`, and `HasLabel`. ### Translation Keys [#translation-keys] **Likelihood of Impact: Low** New translation keys have been added under `shopper-core::status.*` for the new enums. If you have published and customized the Shopper core translations, add the new keys from the `packages/core/resources/lang/en/status.php` file. The old `OrderStatus` translation keys for removed values (`pending`, `registered`, `paid`, `shipped`, `delivered`, `returned`) are no longer used. --- ## New Features [#new-features] ### Payment Driver System [#payment-driver-system] The new `shopper/payment` package provides a driver-based payment architecture. Drivers handle payment operations while Shopper manages the order's `payment_status` automatically. A manual driver is included for offline payments, and [Stripe](/2.x/addons/stripe) is available as an addon. ### Capture Payment in Admin [#capture-payment-in-admin] Orders with `PaymentStatus::Authorized` now display a **Capture payment** button on the order detail page. Clicking it calls the payment driver's `capturePayment()` method, records a transaction, and updates the payment status to `Paid`. ### Shipment Tracking [#shipment-tracking] Each shipment now tracks its delivery progress through a `ShipmentStatus` state machine with automatic event logging. The `OrderShippingEvent` model records status changes with timestamps, location data, and optional GPS coordinates. ### Shipments Management [#shipments-management] A new Shipments page in the admin panel provides a centralized view of all shipments with filtering by status, order, and carrier. --- ## Migration Checklist [#migration-checklist] Update `shopper/framework` to `^2.5` in `composer.json`, then run `composer update -W`. Run `php artisan migrate` to apply all new migrations, including the three-status order system and the media library columns for payment methods and carriers. Replace all references to the removed `OrderStatus` values (`Pending`, `Registered`, `Paid`, `Shipped`, `Delivered`, `Returned`) with the equivalent `PaymentStatus` and `ShippingStatus` values. Update any code, queries, or Blade templates that reference `$order->canceled_at` to use `$order->cancelled_at`. Replace `$paymentMethod->logo` and `$carrier->logo` with `$paymentMethod->logoUrl()` and `$carrier->logoUrl()`. Re-upload existing logos through the admin panel if needed. If you use a custom Order model implementing `Shopper\Core\Models\Contracts\Order`, add the new contract methods (`isNew()`, `isPaid()`, `isShipped()`, etc.). If you have published `config/shopper/components/order.php`, add the new page and component entries for shipments, fulfillment, customer, items, notes, summary, and the two new slide-overs. Run `composer require shopper/stripe` if you want Stripe payment support. See the [Stripe addon documentation](/2.x/addons/stripe) for setup. Run `php artisan optimize:clear`. # From v2.5 to v2.6 (/2.x/upgrade/v2-5-to-v2-6) **Estimated Upgrade Time:** 15 to 45 minutes depending on how much you customized auth models and event listeners. ## Updating Dependencies [#updating-dependencies] You should update the following dependencies in your application's `composer.json` file: `shopper/framework` to `^2.6` `shopper/stripe` to `^2.6` (If installed) Then run: ```bash composer update -W ``` After updating, run the migrations: ```bash php artisan migrate ``` v2.6 ships one new package: `shopper/cart`. The tax system is built into `shopper/core`. Both are included in `shopper/framework` and installed automatically. Their migrations run with the standard `php artisan migrate` command. --- ## High Impact Changes [#high-impact-changes] ### Auth Models and Traits Moved from Core to Admin [#auth-models-and-traits-moved-from-core-to-admin] **Likelihood of Impact: High** *Affects applications that import Role, Permission, ShopperUser, or HasProfilePhoto directly.* The `Role` and `Permission` models, the `ShopperUser` and `HasProfilePhoto` traits, and the `spatie/laravel-permission` dependency have all moved from `shopper/core` to `shopper/admin`. If you import any of these directly in your application code, update the namespaces: | Before (v2.5) | After (v2.6) | |---|---| | `Shopper\Core\Models\Role` | `Shopper\Models\Role` | | `Shopper\Core\Models\Permission` | `Shopper\Models\Permission` | | `Shopper\Core\Models\Contracts\ShopperUser` | `Shopper\Models\Contracts\ShopperUser` | | `Shopper\Core\Traits\ShopperUser` | `Shopper\Traits\InteractsWithShopper` | | `Shopper\Core\Models\Traits\HasProfilePhoto` | `Shopper\Traits\HasProfilePhoto` | The old namespaces are still present in `shopper/core` as deprecated aliases and will continue to work until v3.0, but you should migrate at your earliest convenience. The role configuration has also moved. If you referenced the admin role from `config/shopper/core.php`, update to `config/shopper/admin.php`: #### Before (v2.5) [#before-v25] ```php config('shopper.core.roles.admin') ``` #### After (v2.6) [#after-v26] ```php config('shopper.admin.roles.admin') ``` --- ## Medium Impact Changes [#medium-impact-changes] ### New Migrations [#new-migrations] v2.6 adds 15 new migrations across two packages. Run `php artisan migrate` after updating. **Tax system (shopper/core):** | Migration | Description | |-----------|-------------| | `2026_02_24_000001_create_tax_providers_table` | Tax provider registry | | `2026_02_24_000002_create_tax_zones_table` | Geographic tax zones | | `2026_02_24_000003_create_tax_rates_table` | Rates and override rules | | `2026_02_25_000001_add_tax_amount_to_orders_table` | `tax_amount` column on orders | | `2026_02_25_000002_add_tax_columns_to_order_items_table` | `tax_amount` and `tax_rate_id` on order items | | `2026_02_25_000003_create_order_tax_lines_table` | Tax line snapshots | | `2026_02_25_000004_add_allow_backorder_to_products_table` | `allow_backorder` column on products | | `2026_02_25_000005_make_user_id_nullable_on_inventory_histories_table` | `user_id` becomes nullable | **Cart package (shopper/cart):** | Migration | Description | |-----------|-------------| | `2026_03_01_000001_create_carts_table` | Cart model | | `2026_03_01_000002_create_cart_lines_table` | Cart line items | | `2026_03_01_000003_create_cart_addresses_table` | Billing and shipping addresses | | `2026_03_01_000004_create_cart_line_adjustments_table` | Discount adjustments per line | | `2026_03_01_000005_create_cart_line_tax_lines_table` | Tax lines per cart line | **Performance (shopper/admin):** | Migration | Description | |-----------|-------------| | `2026_02_26_000001_add_status_indexes_to_orders_table` | Indexes on order status columns | ### Order and Product Event Renaming [#order-and-product-event-renaming] **Likelihood of Impact: Medium** *Affects applications with listeners registered for `OrderCancel` or `AddNoteToOrder` events.* Two events have been renamed for consistency. If you registered listeners for either of these events, update your `EventServiceProvider`: | Before (v2.5) | After (v2.6) | |---|---| | `Shopper\Core\Events\Orders\OrderCancel` | `Shopper\Core\Events\Orders\OrderCancelled` | | `Shopper\Core\Events\Orders\AddNoteToOrder` | `Shopper\Core\Events\Orders\OrderNoteAdded` | #### Before (v2.5) [#before-v25-1] ```php use Shopper\Core\Events\Orders\OrderCancel; use Shopper\Core\Events\Orders\AddNoteToOrder; protected $listen = [ OrderCancel::class => [CancelOrderHandler::class], AddNoteToOrder::class => [NotifyTeam::class], ]; ``` #### After (v2.6) [#after-v26-1] ```php use Shopper\Core\Events\Orders\OrderCancelled; use Shopper\Core\Events\Orders\OrderNoteAdded; protected $listen = [ OrderCancelled::class => [CancelOrderHandler::class], OrderNoteAdded::class => [NotifyTeam::class], ]; ``` ### Render Hooks: Enum Replaced by Scoped Classes [#render-hooks-enum-replaced-by-scoped-classes] **Likelihood of Impact: Medium** *Affects applications that registered render hooks using the `RenderHook` enum in v2.5.* The `RenderHook` enum (`Shopper\Enum\RenderHook`) from v2.5 had 6 layout-level hooks. It has been replaced by seven scoped classes organized by business domain. If you used any of these hooks, update to `LayoutRenderHook`: | Before (v2.5) | After (v2.6) | |---|---| | `RenderHook::HeadStart` | `LayoutRenderHook::HEAD_START` | | `RenderHook::HeadEnd` | `LayoutRenderHook::HEAD_END` | | `RenderHook::BodyStart` | `LayoutRenderHook::BODY_START` | | `RenderHook::BodyEnd` | `LayoutRenderHook::BODY_END` | | `RenderHook::ContentStart` | `LayoutRenderHook::CONTENT_START` | | `RenderHook::ContentEnd` | `LayoutRenderHook::CONTENT_END` | The new classes are in the `Shopper\View` namespace. See the [Render Hooks](/2.x/render-hooks) documentation for the complete list of available hooks across all 7 scoped classes. #### Before (v2.5) [#before-v25-2] ```php use Shopper\Enum\RenderHook; Shopper::renderHook(RenderHook::HeadEnd, fn () => '...'); ``` #### After (v2.6) [#after-v26-2] ```php use Shopper\View\LayoutRenderHook; Shopper::renderHook(LayoutRenderHook::HEAD_END, fn () => '...'); ``` --- ## Low Impact Changes [#low-impact-changes] ### `allow_backorder` Column Added to Products [#allow_backorder-column-added-to-products] A new boolean column `allow_backorder` has been added to the products table. It defaults to `false`. No action is required, the migration handles it automatically. When `allow_backorder` is `true` on a product or variant, the cart's `add()` and `update()` methods skip the stock availability check entirely, allowing the item to be added regardless of inventory level. ### `user_id` Nullable on Inventory Histories [#user_id-nullable-on-inventory-histories] The `user_id` foreign key on the `inventory_histories` table is now nullable. This accommodates stock changes triggered by automated processes rather than an admin action. No action is required. ### System Permissions Cleanup [#system-permissions-cleanup] Three system permissions have been removed from the seeder and are no longer created on fresh installations: | Removed permission | Reason | |---|---| | `manage_mail` | No longer used by any component | | `impersonate` | No longer used by any component | | `setting_analytics` | No longer used by any component | For existing installations these permissions remain in your database but have no effect. You can delete them manually if you want to keep your permissions table clean: ```php use Shopper\Models\Permission; Permission::query()->whereIn('name', ['manage_mail', 'impersonate', 'setting_analytics'])->delete(); ``` ### Server-Side Authorization Enforced Across Admin Components [#server-side-authorization-enforced-across-admin-components] **Likelihood of Impact: Medium** *Affects applications with custom roles beyond the default administrator role.* All admin Livewire pages and slide-overs now enforce permissions server-side via `$this->authorize()`. Previously, many components relied only on sidebar visibility to restrict access, so a direct URL or Livewire call was enough to bypass the check. The following table lists every area that is now protected and the permission required: | Area | Permission | |---|---| | Settings pages (General, Carriers, Payment Methods, Taxes, Tax Zones, Legal) | `access_setting` | | Tax rate overrides slide-over | `access_setting` | | Shipping zone and rate slide-overs | `access_setting` | | Team management pages and slide-overs | `view_users` | | Product attributes slide-over | `edit_attributes` | | Product pricing slide-over | `edit_products` | | Choose product attributes slide-over | `edit_products` | | Related products slide-over | `edit_products` | | Generate variants slide-over | `edit_product_variants` | | Update variant slide-over | `edit_product_variants` | | Collection products and rules slide-overs | `edit_collections` | | Re-order categories slide-over | `edit_categories` | | Create shipping label slide-over | `edit_orders` | | Reviews index page and detail slide-over | `browse_reviews` | | Tags index page | `browse_tags` | The `administrator` role is not affected as it holds all permissions by default. For custom roles, assign the relevant permissions before upgrading: ```php use Spatie\Permission\Models\Role; $role = Role::findByName('manager'); $role->givePermissionTo([ 'access_setting', 'view_users', 'edit_attributes', 'edit_products', 'edit_product_variants', 'edit_collections', 'edit_categories', 'edit_orders', 'browse_reviews', 'browse_tags', ]); ``` Review all custom roles in your installation and assign the permissions appropriate to their scope before upgrading. Users with insufficient permissions will receive a 403 response. ### Shopper Enums Now Implement `Shopper\Core\Contracts` [#shopper-enums-now-implement-shoppercorecontracts] Shopper's internal enums (`OrderStatus`, `ProductType`, etc.) now implement `HasLabel`, `HasIcon`, `HasColor`, and `HasDescription` from `Shopper\Core\Contracts` instead of `Filament\Support\Contracts`. This removes the Filament dependency from `shopper/core` and keeps the core package framework-agnostic. This has no impact on your application. Since Shopper runs on top of Filament, your own custom enums can continue to implement either `Filament\Support\Contracts` or `Shopper\Core\Contracts`. The method signatures are identical. --- ## New Features [#new-features] ### Cart Package [#cart-package] `shopper/cart` is now bundled with Shopper. It provides a full cart management system with pipeline-based calculation, discount validation, tax integration, and order conversion. See the [Cart documentation](/2.x/cart) for setup and usage. ### Tax System [#tax-system] A built-in tax system is now available. Configure tax zones per country (or country + province), assign rates, and define override rules for specific products, product types, or categories. Taxes are calculated automatically in the cart pipeline. See the [Taxes documentation](/2.x/taxes) for full details. ### Dashboard Analytics [#dashboard-analytics] The dashboard now includes five new Livewire components: a 12-month revenue bar chart, stat cards with month-over-month trends, a recent orders table, a top-selling products table, and an interactive setup guide. All data is cached with stale-while-revalidate semantics. See the [Dashboard documentation](/2.x/dashboard). ### Abandoned Carts [#abandoned-carts] A new admin page at **Orders → Abandoned Carts** lists carts that have been inactive for longer than the configured threshold (default: 60 minutes). The threshold is configurable in `config/shopper/cart.php`: ```php 'abandoned_after_minutes' => 60, ``` ### Addon System [#addon-system] Shopper now has a first-class addon API for packaging extensions. An addon can register routes, Livewire components, sidebar entries, views, settings items, and permissions as a single unit. See the [Addons documentation](/2.x/addons). ### Render Hooks [#render-hooks] 62 named render hooks are now available across all admin pages. Use them to inject content into specific positions without modifying any Shopper views. See the [Render Hooks documentation](/2.x/render-hooks). --- ## Migration Checklist [#migration-checklist] Run `composer update -W` after updating `shopper/framework` to `^2.6`. Run `php artisan migrate` to apply all 15 new migrations. Replace `Shopper\Core\Models\Role` → `Shopper\Models\Role` and `Shopper\Core\Models\Permission` → `Shopper\Models\Permission` wherever you import them. Replace `Shopper\Core\Traits\ShopperUser` → `Shopper\Traits\InteractsWithShopper` and `Shopper\Core\Models\Traits\HasProfilePhoto` → `Shopper\Traits\HasProfilePhoto`. Replace `OrderCancel` → `OrderCancelled` and `AddNoteToOrder` → `OrderNoteAdded` in your event listeners. Replace the old `RenderHook` enum constants with the new scoped class constants if you used render hooks in v2.5. Replace `config('shopper.core.users.admin_role')` with `config('shopper.admin.roles.admin')` if you referenced it directly. Assign `access_setting`, `view_users`, `edit_attributes`, `edit_products`, `edit_product_variants`, `edit_collections`, `edit_categories`, `edit_orders`, `browse_reviews`, and `browse_tags` to any custom role that should access the corresponding areas. Optionally delete the unused `manage_mail`, `impersonate`, and `setting_analytics` permissions from your database. # From v2.6 to v2.7 (/2.x/upgrade/v2-6-to-v2-7) **Estimated Upgrade Time:** 30 to 90 minutes depending on how much storefront code interacts with monetary values. v2.7 ships with an AI-assisted upgrade package. Install it before upgrading to get guided migration prompts. ## AI-Assisted Upgrade (Recommended) [#ai-assisted-upgrade-recommended] Shopper v2.7 includes `shopper/upgrade`, a temporary package with [Laravel Boost](https://github.com/laravel/boost) skills that guide your AI assistant through each breaking change. ```bash composer require shopper/upgrade:^2.7 --dev php artisan boost:install ``` This registers 4 upgrade skills in your AI assistant: | Skill | What it does | |---|---| | `shopper-upgrade-money-storage` | Migrates storefront code to smallest currency unit | | `shopper-upgrade-slide-overs` | Migrates custom slide-over components | | `shopper-upgrade-two-factor-auth` | Migrates 2FA traits to SOLID interfaces | | `shopper-upgrade-filament-schemas` | Migrates InteractsWithForms to InteractsWithSchemas | Each skill checks if the migration applies to your project before suggesting changes. After completing the upgrade, remove the package: ```bash composer remove shopper/upgrade --dev ``` ## Updating Dependencies [#updating-dependencies] Update the following dependencies in your application's `composer.json` file: `shopper/framework` to `^2.7` `shopper/stripe` to `^2.7` (If installed) Then run: ```bash composer update -W ``` v2.7 requires **Laravel 11.28+** or **Laravel 12.x**. If you are on an earlier Laravel 11 version, update Laravel first. Filament minimum version is now **4.9**. --- ## High Impact Changes [#high-impact-changes] ### Money Storage: Smallest Currency Unit [#money-storage-smallest-currency-unit] **Likelihood of Impact: High** *Affects all applications that read or write monetary values (prices, orders, cart totals, payment gateway calls).* This is the most critical change in v2.7. All monetary values are now stored and returned in the **smallest currency unit** (cents for USD/EUR/GBP, raw value for zero-decimal currencies like XAF/JPY). This follows the Stripe/Shopify standard. **What changed:** All Eloquent price accessors (get/set) have been removed from `Order`, `OrderItem`, `Price`, `CarrierOption`, `CartLine`, `CartLineTaxLine`, `CartLineAdjustment`, and `Discount`. #### Reading prices [#reading-prices] Model properties now return the raw database value (smallest unit) instead of human-readable values: ```php $order->price_amount; $price->amount; ``` These return `1200` and `16300` respectively, not `12.00` and `163.00`. For display, use `shopper_money_format()`: ```php shopper_money_format($order->price_amount, $order->currency_code); ``` #### Writing prices [#writing-prices] Pass the value in cents directly. The setter no longer multiplies by 100: ```php Order::create(['price_amount' => 12.00]); // [!code --] Order::create(['price_amount' => 1200]); // [!code ++] Price::create(['amount' => 163]); // [!code --] Price::create(['amount' => 16300]); // [!code ++] ``` #### Cart pipeline [#cart-pipeline] `CartPipelineRunner` no longer divides results by 100. All values are in cents: ```php $context = $cartManager->calculate($cart); $context->subtotal; // 25.00 // [!code --] $context->subtotal; // 2500 // [!code ++] ``` #### Payment gateways [#payment-gateways] Values are already in cents. Remove any manual multiplication: ```php Stripe::charge($order->price_amount * 100); // [!code --] Stripe::charge($order->price_amount); // [!code ++] ``` #### Zero-decimal currencies [#zero-decimal-currencies] If you use zero-decimal currencies (XAF, JPY, KRW, etc.), existing data was incorrectly multiplied by 100. Run the fix command: ```bash # Preview what will change php artisan shopper:upgrade:fix-zero-decimal-currencies --dry-run # Apply the fix php artisan shopper:upgrade:fix-zero-decimal-currencies ``` Put your site in maintenance mode before running this command. It modifies prices, orders, order items, carrier options, cart lines, and discounts. #### New helpers [#new-helpers] Two new helpers are available: | Helper | Purpose | |---|---| | `zero_decimal_currencies()` | Returns the list of zero-decimal currency codes | | `is_no_division_currency($code)` | Checks if a currency code is zero-decimal | #### MoneyInput component [#moneyinput-component] A new Filament form component handles the conversion between human values (form display) and smallest unit (database) automatically: ```php use Shopper\Components\Form\MoneyInput; MoneyInput::make('price') ->currency('USD') ->suffix('USD'); ``` If no currency is specified, it defaults to the shop's configured currency. For zero-decimal currencies, the mask precision adjusts to 0 automatically. #### Filament table columns [#filament-table-columns] Replace `->money()` with the `->currency()` macro: ```php TextColumn::make('amount')->money(fn ($record) => $record->currencyCode) // [!code --] TextColumn::make('amount')->currency(fn ($record) => $record->currencyCode) // [!code ++] ``` **Existing database data for standard currencies (USD, EUR, GBP) is already correct**. The old setters stored values in cents. No migration needed for these currencies. --- ### Slide-Over Components Replaced [#slide-over-components-replaced] **Likelihood of Impact: High** *Affects applications with custom slide-over components extending Shopper's base class.* Shopper's internal `SlideOverComponent` and `SlideOverPanel` classes have been removed and replaced by the [`laravelcm/livewire-slide-overs`](https://github.com/laravelcm/livewire-slide-overs) package. If you created custom slide-over components that extend Shopper's base class, update the import: ```php use Shopper\Livewire\Components\SlideOverComponent; // [!code --] use Laravelcm\LivewireSlideOvers\SlideOverComponent; // [!code ++] ``` The `closePanelWithEvents()` method no longer exists: ```php $this->closePanelWithEvents(['eventName']); // [!code --] $this->dispatch('eventName'); // [!code ++] $this->closePanel(); // [!code ++] ``` --- ## Medium Impact Changes [#medium-impact-changes] ### Two-Factor Authentication: SOLID Interfaces [#two-factor-authentication-solid-interfaces] **Likelihood of Impact: Medium** *Affects applications that override the User model and use two-factor authentication.* The monolithic `TwoFactorAuthenticatable` trait has been split into focused interfaces and traits: ```php use Shopper\Traits\TwoFactorAuthenticatable; // [!code --] use Shopper\Contracts\HasStoreAuthentication; // [!code ++] use Shopper\Contracts\HasStoreAuthenticationRecovery; // [!code ++] use Shopper\Traits\InteractsWithStoreAuthentication; // [!code ++] use Shopper\Traits\InteractsWithStoreAuthenticationRecovery; // [!code ++] class User extends Authenticatable // [!code --] class User extends Authenticatable implements HasStoreAuthentication, HasStoreAuthenticationRecovery // [!code ++] { use TwoFactorAuthenticatable; // [!code --] use InteractsWithStoreAuthentication; // [!code ++] use InteractsWithStoreAuthenticationRecovery; // [!code ++] } ``` The two-factor columns on the users table have been renamed to avoid conflicts with Laravel Fortify's own 2FA columns. Update the `$hidden` array on your User model: ```php protected $hidden = [ 'password', 'remember_token', 'two_factor_secret', // [!code --] 'two_factor_recovery_codes', // [!code --] 'store_two_factor_secret', // [!code ++] 'store_two_factor_recovery_codes', // [!code ++] ]; ``` ### Filament HasForms to HasSchemas [#filament-hasforms-to-hasschemas] **Likelihood of Impact: Medium** *Affects applications with custom Filament components that use `InteractsWithForms`.* Shopper now uses `InteractsWithSchemas` instead of `InteractsWithForms`. If you have custom components in `app/Shopper/` or `app/Livewire/`: ```php use Filament\Forms\Concerns\InteractsWithForms; // [!code --] use Filament\Forms\Contracts\HasForms; // [!code --] use Filament\Schemas\Concerns\InteractsWithSchemas; // [!code ++] use Filament\Schemas\Contracts\HasSchemas; // [!code ++] ``` `InteractsWithForms` still works in Filament 4.x. This migration is recommended but not urgent. ### Dependency Version Bumps [#dependency-version-bumps] **Likelihood of Impact: Medium** *Affects all applications.* | Dependency | Before | After | |---|---|---| | `laravel/framework` | `^11.0\|^12.0` | `^11.28\|^12.0` | | `filament/filament` | `^4.7` | `^4.9` | | `spatie/laravel-permission` | `^6.24` | `^6.24\|^7.0` | --- ## Low Impact Changes [#low-impact-changes] ### InteractsWithSlideOverForm Trait [#interactswithslideoverform-trait] 10 slide-over form components now use the shared `InteractsWithSlideOverForm` trait and a generic Blade view. Their dedicated Blade views have been removed: `add-collection-form.blade.php`, `attribute-form.blade.php`, `brand-form.blade.php`, `category-form.blade.php`, `create-team-member.blade.php`, `discount-form.blade.php`, `supplier-form.blade.php`, `update-variant.blade.php` If you published and customized any of these views, you'll need to adapt to the new generic view or override the component's `render()` method. ### Shipment Event Date Validation [#shipment-event-date-validation] Shipment events now enforce chronological ordering. You cannot create an event with a date earlier than the previous event. The `RecordShipmentEventAction` validates this server-side. ### Nested Sortable Categories [#nested-sortable-categories] Categories can now be reordered with drag & drop in the admin panel. No code changes required. ### Collection Price Rules [#collection-price-rules] Automatic collection price rules now filter by the shop's default currency when evaluating products. --- ## New Features [#new-features] ### Upgrade Package [#upgrade-package] `shopper/upgrade` is a new temporary package with Laravel Boost skills for AI-assisted upgrades and an artisan command for zero-decimal currency data fixes. Install it before upgrading, remove it after. ### MoneyInput Component [#moneyinput-component-1] A new `MoneyInput` Filament form component that handles currency-aware conversion between human values and smallest unit storage. --- ## Migration Checklist [#migration-checklist] Run `composer require shopper/upgrade:^2.7 --dev` and `php artisan boost:install` to get AI-assisted migration prompts. Replace direct price property access with `shopper_money_format()` for display. Use raw values for calculations. Pass values in smallest currency unit to all `create()` / `update()` calls on monetary fields. Remove any `* 100` multiplication before sending to Stripe or other providers. Run `php artisan shopper:upgrade:fix-zero-decimal-currencies` if you use XAF, JPY, or other zero-decimal currencies. Replace `Shopper\Livewire\Components\SlideOverComponent` with `Laravelcm\LivewireSlideOvers\SlideOverComponent` in any custom slide-overs. Replace `TwoFactorAuthenticatable` with the new interfaces and traits if you override the User model. Update your `$hidden` array to use `store_two_factor_secret` and `store_two_factor_recovery_codes` instead of the old column names. Run `composer update -W` after setting `shopper/framework` to `^2.7`. Run `php artisan test` and fix assertions that expect human-readable price values instead of cents. Run `composer remove shopper/upgrade --dev` when done. # From v2.7 to v2.8 (/2.x/upgrade/v2-7-to-v2-8) **Estimated Upgrade Time:** 5 to 15 minutes. v2.8 is a pure security release with no breaking API changes. v2.8.0 patches two security advisories disclosed responsibly by [@baradika](https://github.com/baradika): - Authorization bypass in admin Livewire components (CWE-862 / CWE-285) - Race condition on `Discount.usage_limit` allows silent over-redemption (CWE-362 / CWE-840) Upgrade as soon as possible. Both advisories are public on the [Shopper GitHub Security Advisories](https://github.com/shopperlabs/shopper/security/advisories) page. ## Updating Dependencies [#updating-dependencies] Update the following dependency in your application's `composer.json` file: `shopper/framework` to `^2.8` Then run: ```bash composer update -W php artisan migrate ``` ## Database Migration [#database-migration] v2.8 ships one additive migration. It adds five nullable columns to the `orders` table to snapshot the discount that was redeemed at order placement time: | Column | Type | Purpose | |---|---|---| | `discount_id` | bigint FK (nullOnDelete) | Link to the discount that was redeemed | | `discount_code` | string | Snapshot of the code used (kept even if the discount is later edited or deleted) | | `discount_type` | string(32) | Snapshot of the discount type (`percentage` / `fixed_amount`) | | `discount_value_at_apply` | unsigned int | Snapshot of the discount value at apply time | | `discount_currency_code` | char(3) | Currency the discount was applied in | Existing rows are left untouched. The snapshot follows the Shopify pattern: an order keeps the discount it was placed with, even after the originating discount is edited or deleted. ## High Impact Changes [#high-impact-changes] ### Discount Limit Enforcement [#discount-limit-enforcement] **Likelihood of Impact: High if you call `CreateOrderFromCartAction` directly.** *Affects any storefront code that converts carts to orders outside the default checkout flow.* Two production bugs around `Discount.usage_limit` are fixed in v2.8. Both can now throw a new exception from `CreateOrderFromCartAction::execute()`. The global usage counter (`total_use`) is now incremented atomically inside the order-creation transaction. The discount row is locked with `lockForUpdate`, then a conditional `UPDATE` increments `total_use` **only if** it is still below `usage_limit`. If zero rows are affected, the limit was reached between cart validation and commit and `DiscountLimitReachedException::global()` is thrown. The order is **not** created and the transaction rolls back. The per-user limit (`usage_limit_per_user`) previously read from `DiscountDetail.total_use`, a counter that was never incremented. It now counts prior orders on the new `orders.discount_id` column. The check runs in two places: `DiscountValidator` rejects the code at cart-apply time (so the customer is not surprised at checkout), and `CreateOrderFromCartAction` re-checks at commit and throws `DiscountLimitReachedException::perUser()` if the customer redeemed it between cart apply and commit. Update your checkout controller to catch the new exception: ```php use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Exceptions\DiscountLimitReachedException; use Shopper\Cart\Facades\Cart; try { $order = resolve(CreateOrderFromCartAction::class)->execute(Cart::current()); } catch (DiscountLimitReachedException $e) { return back()->with('error', 'This discount can no longer be used. Please remove the code and try again.'); } ``` For full details on both limits, see the [Discounts page](/2.x/discounts#usage-limit-enforcement). ## Medium Impact Changes [#medium-impact-changes] ### Custom Livewire Admin Components [#custom-livewire-admin-components] **Likelihood of Impact: Medium** *Affects applications with custom Livewire components extending Shopper's admin surfaces.* v2.8 tightens authorization across every Shopper admin Livewire component. If you have custom components that extend or mimic Shopper's order, product, customer, or settings surfaces, audit them against the new patterns. Skipping this audit leaves the same bypass surface that v2.8 closed in Shopper itself. #### Chain `authorize()` on Filament actions [#chain-authorize-on-filament-actions] Filament `Action` handlers should declare their ability on the action itself, not inside the closure. This hides the button when the user lacks the ability, instead of throwing a 403 on click: ```php Action::make('cancel') // [!code --] ->action(function () { // [!code --] $this->authorize('edit_orders'); // [!code --] // ... // [!code --] }); // [!code --] Action::make('cancel') // [!code ++] ->authorize('edit_orders') // [!code ++] ->action(function () { // [!code ++] // ... // [!code ++] }); // [!code ++] ``` #### Authorize Livewire methods on the first line [#authorize-livewire-methods-on-the-first-line] Every public method that mutates state must call `$this->authorize()` first: ```php public function leaveNotes(): void { $this->authorize('edit_orders'); // ... } ``` #### Lock public Eloquent properties [#lock-public-eloquent-properties] Any `public Model $x` property on a Livewire component must be marked `#[Locked]` so it cannot be rebound from the browser. This is the pattern Shopper now applies to `Order`, `OrderShipping`, `Discount`, `Review`, `ShopperUser`, `Role`, `Inventory`, `Legal`, and `Product`: ```php use Livewire\Attributes\Locked; use Shopper\Models\Order; #[Locked] public Order $order; ``` #### Allow-list input on `store()` methods [#allow-list-input-on-store-methods] When persisting user input from the browser, use an explicit `Arr::only(...)` allow-list instead of `Arr::except(...)`. The latter is what allowed the `_password` hidden-field leak that v2.8 closed in `Customers/Create::store()`: ```php $data = Arr::except($payload, ['_token']); // [!code --] $data = Arr::only($payload, ['first_name', 'last_name', 'email']); // [!code ++] ``` ### Settings Permissions Tightened [#settings-permissions-tightened] **Likelihood of Impact: Medium** *Affects custom roles that previously relied on the loose permission scope.* Five settings surfaces moved from `view_users` to `access_setting`. If you have custom roles, audit them to make sure the right people retain access: | Surface | Before | After | |---|---|---| | `Settings/Team/Index::createRole` | `view_users` | `access_setting` | | `Settings/Team/Index` DeleteAction | `view_users` | `access_setting` | | `Settings/Team/RolePermission` save/generate/create | `view_users` | `access_setting` | | `PaymentMethods` / `Currencies` / `Carriers` `ToggleColumn`, record actions, bulk actions | `view_users` | `access_setting` | | `Settings/Team/Permissions::togglePermission` / `removePermission` | `view_users` | `access_setting` (and guards against null lookups) | Roles that managed payment methods, currencies, carriers, team, or permissions must now have `access_setting` granted. ## Low Impact Changes [#low-impact-changes] ### Product Barcode Validation [#product-barcode-validation] Product barcodes are now validated against `^[A-Za-z0-9\-]*$` server-side. This closes a stored XSS surface on the admin barcode renderer. If you have existing products with non-alphanumeric barcodes, they will fail re-validation on next save, so clean them up before upgrading. ### Discount Snapshot on Orders [#discount-snapshot-on-orders] Orders now snapshot the discount at placement time. If you have storefront pages or admin extensions that read the discount tied to an order, prefer the new snapshot columns over `Order::discount` for historical accuracy. The relationship is still there but will return `null` if the originating discount has been deleted. ```php $order->discount_code; $order->discount_type; $order->discount_value_at_apply; $order->discount_currency_code; ``` ## Migration Checklist [#migration-checklist] Set `shopper/framework` to `^2.8` and run `composer update -W`. Run `php artisan migrate` to add the five `orders.discount_*` columns. Wrap `CreateOrderFromCartAction::execute()` calls in your checkout controller to surface a friendly message to the customer when a discount limit is hit at commit time. For every custom Livewire admin component, chain `->authorize()` on Filament actions, call `$this->authorize()` on Livewire method handlers, and mark `public Model $x` properties with `#[Locked]`. Grant `access_setting` to roles that need to manage payment methods, currencies, carriers, team members, or permissions. Find products with non-alphanumeric barcodes and clean them up before saving. Run `php artisan test`. The new authorization guards may reveal tests that were using under-privileged users. # From v2.8 to v2.9 (/2.x/upgrade/v2-8-to-v2-9) **Estimated Upgrade Time:** 5 to 20 minutes. Most applications only need to update dependencies and clear the cache. The longer end applies if you customized the onboarding wizard or run custom Stripe SDK code. v2.9 adds Laravel 13 support, rebuilds the store onboarding wizard on Filament's native Schema, and hardens how settings and dashboard data are cached. It contains no database migrations. The breaking changes below only affect applications that extended internal admin surfaces or pinned the Stripe SDK. ## Updating Dependencies [#updating-dependencies] Update the following dependency in your application's `composer.json` file: `shopper/framework` to `^2.9` Then run: ```bash composer update -W php artisan cache:clear ``` The `cache:clear` step matters during this upgrade. v2.9 changes what Shopper stores in the cache for settings, the default currency, and two dashboard widgets. A cache warmed by v2.8 holds serialized Eloquent models; if those entries survive the upgrade, the v2.9 code that expects scalar values can surface a `__PHP_Incomplete_Class` error until the keys expire. Clearing the cache once after deploying removes that window. ## Laravel 13 Support [#laravel-13-support] v2.9 adds `laravel/framework ^13.0` to the supported range. The supported matrix is now Laravel 11.28+, 12.x, and 13.x on PHP 8.3 and 8.4. The only blocker for Laravel 13 was `spatie/laravel-livewire-wizard`, which capped `illuminate/support` at `^12`. That package powered the onboarding wizard and has been removed (see below). Several supporting dependencies were also bumped: `filament/filament` to `^4.11`, `stripe/stripe-php` to `^19.0`, and a handful of smaller packages. If you want to move to Laravel 13, follow the [official Laravel upgrade guide](https://laravel.com/docs/upgrade) for your application code. Shopper itself requires no changes on your part beyond the dependency update. ## High Impact Changes [#high-impact-changes] ### Stripe SDK Upgraded to v19 [#stripe-sdk-upgraded-to-v19] **Likelihood of Impact: High if you use the Stripe SDK directly.** *Affects applications with custom Stripe code built on `stripe/stripe-php`.* The root `stripe/stripe-php` constraint moved from `^16.0` to `^19.0`, a three-major-version jump that aligns the framework with the `shopper/stripe` package. Shopper's own `StripeDriver` only received PHPStan annotations and behaves identically, but the SDK upgrade applies to your entire application. If you call the Stripe SDK directly anywhere, review the changelogs for [v17](https://github.com/stripe/stripe-php/releases), [v18](https://github.com/stripe/stripe-php/releases), and [v19](https://github.com/stripe/stripe-php/releases) before deploying. Major versions of the SDK track Stripe API changes and can alter resource constructors and pagination behavior. Test every Stripe integration point after upgrading. If you only use the `shopper/stripe` package through Shopper's payment system, no action is required. ## Medium Impact Changes [#medium-impact-changes] ### Onboarding Wizard Rebuilt on Filament Schema [#onboarding-wizard-rebuilt-on-filament-schema] **Likelihood of Impact: Medium** *Affects applications that customized or embedded the store initialization wizard.* The store initialization wizard was rewritten. It previously used `spatie/laravel-livewire-wizard` with one wizard component and three step components. It is now a single Livewire component, `InitializationWizard`, backed by Filament's native `Wizard` schema, with a new `Shopper\Components\OnboardingWizard` class that preserves the horizontal stepper layout. As a result, `spatie/laravel-livewire-wizard` is no longer a dependency of Shopper. If your application relied on it being pulled in transitively, require it explicitly: ```bash composer require spatie/laravel-livewire-wizard ``` The three step components and their registered Livewire aliases were removed: ```blade ``` If you embedded any of these aliases in your own views, remove them. The onboarding flow is now driven entirely by the single `initialize-wizard` component, and the merchant-facing experience is unchanged. ### Settings Trait Method Is Now Protected [#settings-trait-method-is-now-protected] **Likelihood of Impact: Medium** *Affects custom Livewire components that use the `SaveSettings` trait.* `SaveSettings::saveSettings()` changed from `public` to `protected` and gained a second parameter: ```php public function saveSettings(array $keys): void // [!code --] protected function saveSettings(array $keys, bool $locked = true): void // [!code ++] ``` Making the method `protected` prevents Livewire from exposing it as a directly callable wire action, which was the bypass surface this release closes. If you used the trait in a custom component and called `saveSettings()` from outside the class (for example from a test, or via `wire:click="saveSettings"`), wrap it in a public action you control: ```php public function save(): void { $this->saveSettings($this->form->getState()); } ``` The method now also wraps all writes in a database transaction and batches the locked-attribute check, so a single call performs fewer queries than before. Pass `false` as the second argument when you need to store unlocked settings. ## Low Impact Changes [#low-impact-changes] ### Cache Stores Scalars, Not Models [#cache-stores-scalars-not-models] Three helpers and two dashboard widgets now cache primitive values and rehydrate on read, instead of serializing Eloquent models into the cache. | Location | Before | After | |---|---|---| | `shopper_setting()` | cached the `Setting` model | caches the resolved value | | `shopper_currency()` | cached the `Currency` model | caches the currency `code` string | | `RecentOrders` widget | cached an Eloquent collection | caches order IDs, re-queries with eager loads | | `TopSellingProducts` widget | cached an Eloquent collection | caches scalar stats, re-queries products | The return value of `shopper_setting()` and `shopper_currency()` is unchanged, so application code that calls these helpers needs no edits. The only thing to do is the one-time `php artisan cache:clear` from the dependency step. If you read these cache keys directly (for example `Cache::get('shopper-setting.name')`), note that they now hold the scalar value rather than a model instance. ### Extended `TextInputSelect` Component [#extended-textinputselect-component] If you extended `Shopper\Components\Form\TextInputSelect` and overrode `hydrateState()`, update the override to match the new Filament signature: ```php public function hydrateState(?array &$hydratedDefaultState, bool $andCallHydrationHooks = true): void // [!code --] public function hydrateState(?array &$hydratedDefaultState, bool $shouldCallHydrationHooks = true, bool $shouldApplyStateCasts = true, array &$appliedStateCastPaths = []): void // [!code ++] ``` This is a required sync with the parent Filament `TextInput` and only affects you if you subclassed the component. ### TypeScript Types Are Now ESM [#typescript-types-are-now-esm] The `@shopperlabs/shopper-types` package migrated from CommonJS to ECMAScript Modules. The `package.json` now declares `"type": "module"` and ships an `exports` map. ESM-first projects are unaffected. If you consumed the package through CommonJS `require()`, switch to `import`: ```typescript import type { Product, Order } from '@shopperlabs/shopper-types' ``` Two type definitions were also corrected: `Discount.min_required` narrowed from `string` to the `DiscountRequirement` enum, and `TaxRateRule.reference_id` widened from `string` to `string | number`. See the [TypeScript types reference](/2.x/reference/typescript-types) for the full list. ## Migration Checklist [#migration-checklist] Set `shopper/framework` to `^2.9` and run `composer update -W`. Run `php artisan cache:clear` to drop v2.8 cache entries that held serialized models. If you call `stripe/stripe-php` directly, review the v17, v18, and v19 changelogs and test every Stripe integration point. Remove any usage of the `initialize-store-information`, `initialize-store-address`, or `initialize-store-social-link` aliases. Require `spatie/laravel-livewire-wizard` directly if you still depend on it. If you used the `SaveSettings` trait and called `saveSettings()` externally, wrap it in a public action since the method is now protected. If you extended `TextInputSelect` and overrode `hydrateState()`, update the signature to match Filament. If you consumed `@shopperlabs/shopper-types` via CommonJS, switch to ESM imports. Run `php artisan test` to confirm the upgrade is clean. # From v2.9 to v2.10 (/2.x/upgrade/v2-9-to-v2-10) **Estimated Upgrade Time:** 5 to 15 minutes. Most applications only need to update the dependency and clear the cache. The longer end applies if you implemented the `TaxableItem` contract, built a custom product model against `Stockable`, or registered the stock reservation listener yourself. v2.10 is a security and correctness release. It closes authorization gaps across the admin panel, fixes an IDOR on the pricing and variant slide-overs, taxes the discounted line total exactly, and reserves stock atomically during checkout. The breaking changes below only affect applications that extended the tax, stock, or checkout internals. Storefronts that consume Shopper through its public models and actions need no code changes. It contains no database migrations. ## Updating Dependencies [#updating-dependencies] Update the following dependency in your application's `composer.json` file: `shopper/framework` to `^2.10` Then run: ```bash composer update -W php artisan optimize:clear ``` ## High Impact Changes [#high-impact-changes] ### TaxableItem Contract Replaces Two Methods With One [#taxableitem-contract-replaces-two-methods-with-one] **Likelihood of Impact: High if you implemented `TaxableItem` directly.** *Affects applications with a custom tax adapter or a custom tax calculation provider that builds its own taxable items.* The `Shopper\Core\Contracts\TaxableItem` contract previously exposed the taxable amount as a unit price plus a quantity. Tax was then calculated per unit and multiplied back, which overcharged exclusive zones by a cent and unbalanced inclusive VAT breakdowns whenever a line total was not evenly divisible by its quantity. The contract now exposes a single line total and the provider taxes it in one pass. The `getTaxableAmount()` and `getQuantity()` methods are removed and replaced by `getTaxableTotal()`: ```php // Before public function getTaxableAmount(): int { ... } public function getQuantity(): int { ... } // After public function getTaxableTotal(): int { return $this->amount * $this->quantity; } ``` If you wrote a custom `TaxCalculationProvider` that read `$item->getTaxableAmount() * $item->getQuantity()`, replace that expression with `$item->getTaxableTotal()`. The built-in `CartLineTaxAdapter` and `OrderItemTaxAdapter` are already updated. ### Stockable Contract Adds tracksInventory() [#stockable-contract-adds-tracksinventory] **Likelihood of Impact: High if you swapped the product or variant model.** *Affects applications that bound a custom model against the `Product`, `ProductVariant`, or `Stockable` contract.* Stock reservation now skips products that do not track inventory, such as virtual and external products. To decide this, the `Shopper\Core\Models\Contracts\Stockable` contract gained a `tracksInventory(): bool` method. Because `Stockable` is the base of both the product and variant contracts, any custom model that implements one of them must add the method, or it will fail to satisfy the interface at runtime. Mirror the logic from the built-in `Product` model: ```php public function tracksInventory(): bool { return $this->isStandard() || $this->isVariant(); } ``` If your model always carries inventory, return `true` unconditionally. ## Medium Impact Changes [#medium-impact-changes] ### Stock Reservation Moved Into the Checkout Transaction [#stock-reservation-moved-into-the-checkout-transaction] **Likelihood of Impact: Medium** *Affects applications that registered the old reservation listener or instantiate `CreateOrderFromCartAction` manually.* Stock was previously reserved by a queued `ReserveOrderItemStockListener` that fired after the order transaction committed, with no row lock. Two concurrent checkouts reading the same last unit could both succeed and oversell. Reservation now happens synchronously inside `CreateOrderFromCartAction`, under a `lockForUpdate` row lock, through the new `Shopper\Core\Contracts\StockReserver` contract. If the available quantity falls short, `InsufficientStockException` is thrown and the whole order rolls back. The `Shopper\Core\Listeners\Orders\ReserveOrderItemStockListener` class is removed. If you registered it in your application's `EventServiceProvider`, drop that entry: ```php // Remove any mapping like this from your $listen array: OrderItemCreated::class => [ ReserveOrderItemStockListener::class, // class no longer exists ], ``` `CreateOrderFromCartAction` also gained a `StockReserver` constructor dependency. Always resolve it from the container so the dependency is injected for you, and never instantiate it with `new`: ```php $order = resolve(CreateOrderFromCartAction::class)->execute($cart); ``` To customize reservation, for example against an external warehouse, bind your own implementation: ```php use Shopper\Core\Contracts\StockReserver; $this->app->bind(StockReserver::class, WarehouseStockReserver::class); ``` ### Guest Carts Cannot Apply Per-User Discounts [#guest-carts-cannot-apply-per-user-discounts] **Likelihood of Impact: Medium** *Affects storefronts that let anonymous visitors apply coupons.* A coupon with `usage_limit_per_user` set was only checked when the cart had a `customer_id`, so a guest could redeem a once-per-customer code on every anonymous checkout. Both `DiscountValidator` and `CreateOrderFromCartAction` now reject these coupons for guest carts with the `discount.requires_login` error. If your storefront surfaces validation messages, handle this case by prompting the visitor to sign in before applying the coupon. Carts that already have an authenticated `customer_id` are unaffected. ## Low Impact Changes [#low-impact-changes] ### Admin Authorization Tightened [#admin-authorization-tightened] **Likelihood of Impact: Low** *Affects applications with custom roles that granted coarse permissions.* A full audit added explicit `authorize()` calls to every mutating Filament action and Livewire method across the admin panel, and locked previously public model properties on the pricing and variant slide-overs. Standard role setups are unaffected. If you built custom roles that relied on a coarse permission to reach a finer operation, for example granting `add_products` to manage variants, grant the specific permission instead, such as `add_product_variants`. ## Migration Checklist [#migration-checklist] Set `shopper/framework` to `^2.10` and run `composer update -W`. Replace `getTaxableAmount()` and `getQuantity()` with `getTaxableTotal()` on any class that implements `TaxableItem`. If you swapped the product or variant model, add `tracksInventory(): bool` to satisfy the `Stockable` contract. Drop any reference to `ReserveOrderItemStockListener` from your `EventServiceProvider`. Replace any `new CreateOrderFromCartAction(...)` with `resolve(CreateOrderFromCartAction::class)`. If anonymous visitors can apply coupons, handle the `discount.requires_login` error for per-user discounts. Run `php artisan test` to confirm the upgrade is clean. # Version Support Policy (/2.x/version-support-policy) Shopper follows [Semantic Versioning](https://semver.org/). Minor and patch releases never contain breaking changes. Major releases are aligned with Filament's major versions, though a Filament major bump does not automatically trigger a Shopper major if the upgrade requires minimal changes for users. ## Support Policy [#support-policy] | Version | Filament | New features | Bug fixes | Security fixes | |---------|----------|----------------------------|-------------------------------------|---------------------------------------| | 1.x | 2.x | Ended Jul 2023 | Ended Jul 2023 | Ended Jul 2023 | | 2.x | 4.x | Until October 2026 | Until April 2027 | Until October 2027 | | 3.x | 5.x | Until Shopper 4.x stable release | ~1 year after Shopper 4.x stable release | ~2 years after Shopper 4.x stable release | ## New Features [#new-features] Pull requests for new features are only accepted for the latest major version. Once a new major version is released, the Shopper team will no longer accept pull requests for new features in previous versions. Any open pull requests will either be redirected to target the latest major version or closed, depending on conflicts with the new target branch. ## Bug Fixes [#bug-fixes] After a major version is released, the Shopper team will continue to merge pull requests for bug fixes in the previous major version for one year. After this period, pull requests for that version will no longer be accepted. The Shopper team processes bug reports for supported versions in chronological order, though critical bugs may be prioritized. Bug fixes are typically developed only for the latest major version. However, contributors can backport fixes to other supported versions by submitting pull requests. ## Security Fixes [#security-fixes] The Shopper team currently plans to continue providing security fixes for major versions for at least two years. If you discover a security vulnerability in Shopper, please report it through [GitHub](https://github.com/shopperlabs/shopper/security). All security vulnerabilities will be addressed promptly. Please note that while a Shopper version may receive security fixes, its underlying dependencies (PHP, Laravel, Filament, and Livewire) may no longer be supported. Therefore, applications using older versions of Shopper could still be vulnerable to security issues in these dependencies. # Zones (/2.x/zones) Zones define geographic regions for your store. Each zone groups countries together and associates them with a [currency](/2.x/currencies), [carriers](/2.x/carriers) and [payment methods](/2.x/payment-methods). At checkout, your storefront finds the zone that contains the shipping address country, stores it on the cart, and passes it to the shipping and payment services to list the shipping options and payment methods available to the customer. Taxes do not use these zones. [Tax rules](/2.x/taxes) live on separate tax zones (`Shopper\Core\Models\TaxZone`), which Shopper resolves from the shipping address when it calculates the cart. ## Model [#model] The model used is `Shopper\Core\Models\Zone`. The model is not configurable via `config/shopper/models.php`. It uses the `HasSlug` trait. When you set `slug`, the trait converts the value with `Str::slug()` and appends `-1`, `-2` and so on if another zone already uses it. The slug is not generated from the name when you leave it out, and the admin zones list uses it to identify each zone, so set one when you create zones in code. `Zone::findBySlug('europe')` returns the matching zone or throws a `ModelNotFoundException`. `$zone->isEnabled()` returns the value of `is_enabled`. ## Database Schema [#database-schema] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | - | Zone name (unique) | | `slug` | string | yes | null | URL-friendly identifier (unique) | | `code` | string | yes | null | Short code identifier (unique) | | `is_enabled` | boolean | no | false | Zone visibility | | `currency_id` | bigint | no | - | FK to currencies table (deleting the currency deletes the zone) | | `metadata` | jsonb | yes | null | Additional custom data | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Pivot Table [#pivot-table] The `zone_has_relations` pivot table connects zones to countries, carriers, payment methods, and collections through a polymorphic relationship. | Column | Type | Description | |--------|------|-------------| | `zone_id` | bigint | FK to zone | | `zonable_type` | string | Morph type (Country, Carrier, PaymentMethod, Collection) | | `zonable_id` | bigint | FK to the related model | `zonable_type` holds the class name for countries, carriers and payment methods (for example `Shopper\Core\Models\Country`) and the `collection` morph alias for collections. Deleting a zone deletes its rows in this table. ## Relationships [#relationships] Discounts, orders and carts also have a nullable `zone_id` column and a `zone()` relation. Deleting a zone sets their `zone_id` to `null`. ### Currency [#currency] Each zone belongs to one currency, and `currency_id` is required. Shipping option prices in the zone and the amounts of discounts limited to the zone are in this currency. The cart does not take its currency from the zone: you set `currency_code` when you create the cart (see the [cart session helper](/2.x/cart#cart-session-helper)). ```php $zone->currency; // Currency model $zone->currency_code; // "EUR" (computed accessor) $currency->zone; // a zone that uses this currency (HasOne) ``` The `Currency` model has a global scope that hides disabled currencies. If you disable the currency of a zone, `$zone->currency` returns `null` and `$zone->currency_code` throws an error, so keep the currencies used by your zones enabled. ### Countries [#countries] Zones group multiple countries together. Shopper does not pick a zone on its own: your storefront matches the shipping address country to a zone (see [Retrieving Zones](/2.x/zones#retrieving-zones)). ```php $zone->countries; $zone->countries()->attach([$franceId, $germanyId, $belgiumId]); ``` The zone form in the admin disables the countries that already belong to another zone, so each country belongs to one zone. The database does not enforce this rule: when you attach countries in code, keep each country in a single zone. ### Carriers [#carriers] Carriers (shipping providers) are scoped to zones. A carrier available in Europe may not be available in North America. ```php $zone->carriers; $zone->carriers()->attach([$colissimoId, $dhlId]); ``` `CarrierRateService::getRatesForZone()` returns the rates of the enabled carriers of a zone (see [Getting Rates for a Zone](/2.x/carriers#getting-rates-for-a-zone)). ### Payment Methods [#payment-methods] Payment methods are scoped to zones. For example, iDEAL is only available in the Netherlands zone. ```php $zone->paymentMethods; $zone->paymentMethods()->attach([$stripeId, $idealId]); ``` `PaymentProcessingService::getMethodsForZone()` returns the enabled payment methods of a zone whose driver is configured (see [Getting Available Payment Methods for a Zone](/2.x/payments#getting-available-payment-methods-for-a-zone)). ### Shipping Options [#shipping-options] Each zone has shipping options (`CarrierOption` records, each with a carrier and a price in cents) available at checkout: ```php $zone->shippingOptions; ``` Delete the shipping options of a zone before you delete the zone: the `zone_id` foreign key on `carrier_options` has no cascade, so the database refuses to delete a zone that still has options. ### Collections [#collections] [Collections](/2.x/collections) can be scoped to specific zones for region-specific merchandising: ```php $zone->collections; ``` ## Query Scopes [#query-scopes] The `enabled` scope filters zones that are active: ```php use Shopper\Core\Models\Zone; Zone::query()->enabled()->get(); ``` ## Computed Attributes [#computed-attributes] The Zone model provides computed attributes that return comma-separated names for related entities: ```php $zone->countries_name; // "France, Germany, Belgium" $zone->carriers_name; // "Colissimo, DHL" $zone->payments_name; // "Stripe, PayPal" $zone->currency_code; // "EUR" ``` Country names come from the translation of the current locale. Each name goes through `ucwords()`, and an empty relation returns `N/A`. The three name attributes load their relation when you read them, so eager load `countries`, `carriers` and `paymentMethods` when you display them for a list of zones. ## HasZones Trait [#haszones-trait] Models that can be scoped to zones use the `HasZones` trait. This is already applied to the `Country`, `Carrier` and `PaymentMethod` models. The `Collection` model defines the same `zones()` relation itself. ```php use Shopper\Core\Models\Traits\HasZones; $carrier->zones; $carrier->zones()->attach([$europeZoneId, $northAmericaZoneId]); ``` ## Creating Zones [#creating-zones] To create a zone for the European market: ```php use Shopper\Core\Models\Country; use Shopper\Core\Models\Currency; use Shopper\Core\Models\Zone; $euro = Currency::query()->where('code', 'EUR')->firstOrFail(); $zone = Zone::query()->create([ 'name' => 'Europe', 'slug' => 'europe', 'code' => 'EU', 'is_enabled' => true, 'currency_id' => $euro->id, ]); $countries = Country::query() ->whereIn('cca2', ['FR', 'DE', 'BE', 'NL', 'ES', 'IT']) ->pluck('id'); $zone->countries()->attach($countries); $zone->carriers()->attach([$colissimoId, $dhlId]); $zone->paymentMethods()->attach([$stripeId]); ``` ## Retrieving Zones [#retrieving-zones] To find the zone for the country of a customer's shipping address, then store it on the cart: ```php $countryId = $cart->shippingAddress()?->country_id; $zone = Zone::query() ->enabled() ->whereHas('countries', fn ($q) => $q->where('id', $countryId)) ->first(); $cart->update(['zone_id' => $zone?->id]); ``` To get all enabled zones with their currencies: ```php $zones = Zone::query() ->enabled() ->with('currency') ->get(); ``` ## Components [#components] The zone management components are part of the settings configuration. To customize: ```bash php artisan shopper:component:publish setting ``` Zone-related components in `config/shopper/components/setting.php`: ```php use Shopper\Livewire; return [ 'pages' => [ 'zones' => Livewire\Pages\Settings\Zones::class, ], 'components' => [ 'settings.zones.detail' => Livewire\Components\Settings\Zones\Detail::class, 'settings.zones.shipping-options' => Livewire\Components\Settings\Zones\ZoneShippingOptions::class, 'slide-overs.shipping-option-form' => Livewire\SlideOvers\ShippingOptionForm::class, 'slide-overs.zone-form' => Livewire\SlideOvers\ZoneForm::class, ], ]; ``` The zones page, the zone form and the shipping option actions require the `access_setting` permission. # Alert (/2.x/extending/components/alert) The Alert component displays colored feedback messages to users. It supports different colors for various contexts like warnings, errors, success messages, and general information. ## Preview [#preview] ## Usage [#usage] ```blade ``` ## Props [#props] The main alert message content. The alert color theme. Options: `info`, `danger`, `success`, `warning`. Optional title displayed above the message. Optional Filament icon name to display. Size of the icon. Options: `Small`, `Medium`, `Large`. ## Color Variants [#color-variants] ### Info [#info] ```blade ``` ### Success [#success] ```blade ``` ### Warning [#warning] ```blade ``` ### Danger [#danger] ```blade ``` ## Examples [#examples] ### Alert Without Title [#alert-without-title] ```blade ``` ### Alert Without Icon [#alert-without-icon] ```blade ``` ### Using in Forms [#using-in-forms] Alerts are commonly used to display validation summaries or important notices in forms: ```blade
``` ## Blade Component Source [#blade-component-source] The Alert component is located at `packages/admin/resources/views/components/alert.blade.php`: ```blade @php use Filament\Support\Enums\IconSize; @endphp @props([ 'message', 'color' => 'warning', 'title' => null, 'icon' => null, 'iconSize' => IconSize::Medium, ]) @php if (! $iconSize instanceof IconSize) { $iconSize = filled($iconSize) ? IconSize::tryFrom($iconSize) ?? $iconSize : null; } $containerClass = \Illuminate\Support\Arr::toCssClasses([ 'rounded-lg p-4 ring-1', match ($color) { 'info' => 'bg-info-50 ring-info-200 dark:ring-info-400/20 dark:bg-info-800/30', 'danger' => 'bg-danger-50 ring-danger-200 dark:ring-danger-400/20 dark:bg-danger-800/30', 'success' => 'bg-success-50 ring-success-200 dark:ring-success-400/20 dark:bg-success-800/30', 'warning' => 'bg-warning-50 ring-warning-200 dark:ring-warning-400/20 dark:bg-warning-800/30', default => 'bg-custom-50 ring-custom-200 dark:ring-custom-400/20 dark:bg-custom-800/30', }, ]); $iconClasses = \Illuminate\Support\Arr::toCssClasses([ 'sh-icon size-4', match ($iconSize) { IconSize::Small => 'size-4', IconSize::Medium => 'size-5', IconSize::Large => 'size-6', default => $iconSize, }, match ($color) { 'info' => 'text-info-400 dark:text-info-500', 'danger' => 'text-danger-400 dark:text-danger-500', 'success' => 'text-success-400 dark:text-success-500', 'warning' => 'text-warning-400 dark:text-warning-500', default => 'text-custom-400 dark:text-custom-500', }, ]); $titleClasses = \Illuminate\Support\Arr::toCssClasses([ 'text-sm/5 font-medium', match ($color) { 'info' => 'text-info-600 dark:text-info-500', 'danger' => 'text-danger-600 dark:text-danger-500', 'success' => 'text-success-600 dark:text-success-500', 'warning' => 'text-warning-600 dark:text-warning-500', default => 'text-custom-600 dark:text-custom-500', }, ]); $messageClasses = \Illuminate\Support\Arr::toCssClasses([ 'text-sm/5', 'mt-2' => $title, match ($color) { 'info' => 'text-info-500 dark:text-info-400', 'danger' => 'text-danger-500 dark:text-danger-400', 'success' => 'text-success-500 dark:text-success-400', 'warning' => 'text-warning-500 dark:text-warning-400', default => 'text-custom-500 dark:text-custom-400', }, ]); @endphp
twMerge(['class' => $containerClass]) }}>
@if ($icon)
@endif
@if ($title)

{{ $title }}

@endif

{{ $message }}

``` # Card (/2.x/extending/components/card) The Card component is the primary container used throughout Shopper to group related content. It provides a consistent visual treatment with a subtle border and background. ## Preview [#preview]

Your content goes here. This could be forms, tables, or any other content.

## Usage [#usage] ```blade

Your content goes here

``` ## Props [#props] The card header title. Can be a string or a slot for custom content. Optional description text displayed below the title. ## Examples [#examples] ### Basic Card [#basic-card]

A simple card without title or description.

```blade

A simple card without title or description.

``` ### Card with Title Only [#card-with-title-only]

Display product details in an organized manner.

```blade

Display product details in an organized manner.

``` ### Card with Custom Title Slot [#card-with-custom-title-slot] You can pass a custom slot for the title to include additional elements: ```blade

Custom Title

Action

Card content with custom header.

``` ### Card with Form Content [#card-with-form-content]
```blade
Name
Email
``` ## Blade Component Source [#blade-component-source] The Card component is located at `packages/admin/resources/views/components/card.blade.php`: ```blade @blaze @props([ 'title' => null, 'description' => null, ])
twMerge(['class' => 'sh-card p-1 bg-gray-50 dark:bg-gray-950 rounded-xl ring-1 ring-gray-200 dark:ring-white/10 overflow-hidden']) }} > @if ($title)
@if ($title instanceof \Illuminate\View\ComponentSlot) {{ $title }} @else @endif
@endif
{{ $slot }}
``` # Empty Card (/2.x/extending/components/empty-card) The Empty Card component displays a centered empty state within card or panel areas. It's more compact than the full Empty State component. ## Preview [#preview] ## Usage [#usage] ```blade ``` ## Props [#props] The main heading text. Optional description text below the heading. Icon name to display above the heading (uses Blade Icons). Optional slot for action buttons. ## Examples [#examples] ### With Action Button [#with-action-button] Add Product} /> ```blade Add Product ``` ### Without Icon [#without-icon] ```blade ``` ## Blade Component Source [#blade-component-source] ```blade @blaze @props([ 'heading', 'description' => null, 'icon' => null, 'action' => null, ])
twMerge(['class' => 'flex flex-col items-center justify-center px-8 py-10 text-center']) }} > @if ($icon)
@svg($icon, 'size-5', ['aria-hidden' => 'true'])
@endif

$icon])> {{ $heading }}

@if ($description)

{{ $description }}

@endif @if ($action)
{{ $action }}
@endif
``` # Empty State (/2.x/extending/components/empty-state) The Empty State component is used to display a helpful message when there's no data to show. It combines an illustration, title, description, and an optional call-to-action button. ## Preview [#preview] ## Usage [#usage] ```blade ``` ## Props [#props] The main heading text for the empty state. Descriptive text explaining the empty state and what action can be taken. Text for the call-to-action button. The button only shows when `permission` is set, the user has that permission, and `url` or `panel` is set. Permission name required to show the button. Uses Laravel's `@can` directive. URL for the button link. Use this for navigation to a create page. Arguments of the `openPanel` event that opens a slide-over, written as a JavaScript object such as `{ component: 'shopper-slide-overs.brand-form' }`. Alternative to `url`. ## Examples [#examples] ### Basic Empty State [#basic-empty-state] ```blade ``` ### With URL Action [#with-url-action] ```blade ``` ### With Panel Action [#with-panel-action] Use a panel action to open a slide-over instead of navigating: ```blade ``` ### Without Button [#without-button] When you don't want to show an action button: ```blade ``` ### Custom Slot Content [#custom-slot-content] The default slot is used for the illustration on the left side: ```blade {{-- Custom SVG or image --}} ``` ## Usage in Livewire Components [#usage-in-livewire-components] Empty states are typically rendered conditionally when a collection is empty: ```blade @if ($products->isEmpty()) @else {{-- Product list/table --}} @endif ``` ## Blade Component Source [#blade-component-source] The Empty State component is located at `packages/admin/resources/views/components/empty-state.blade.php`: ```blade @props([ 'title', 'content', 'button' => false, 'permission' => false, 'url' => false, 'panel' => null, ])
twMerge(['class' => 'relative w-full lg:flex lg:items-center py-8 lg:py-12']) }} >
{{ $slot }}

{{ $title }}

{{ $content }}

@if ($permission) @can($permission) @if ($url) {{ $button }} @elseif ($panel) {{ $button }} @endif @endcan @endif
``` # Heading (/2.x/extending/components/heading) The Heading component is used for main page titles. It displays a large, bold heading with an optional action slot for buttons or other controls. ## Preview [#preview] Add Product ## Usage [#usage] ```blade Products Add Product ``` ## Slots [#slots] The heading title. Can be plain text or a custom slot with additional elements. Optional slot for action buttons or controls aligned to the right. ## Examples [#examples] ### Simple Heading [#simple-heading] ```blade Dashboard ``` ### Heading with Action Button [#heading-with-action-button] New Category ```blade Categories New Category ``` ### Heading with Multiple Actions [#heading-with-multiple-actions]
Export Create Order
```blade Orders
Export Create Order
``` ### Custom Title Slot [#custom-title-slot] For more complex titles, you can use the title as a slot: ```blade
Product: iPhone 15 Published
Unpublish
``` ## Blade Component Source [#blade-component-source] The Heading component is located at `packages/admin/resources/views/components/heading.blade.php`: ```blade @blaze
twMerge(['class' => 'space-y-3 sm:flex sm:items-center sm:justify-between sm:space-x-4 sm:space-y-0']) }} > @if ($title instanceof \Illuminate\View\ComponentSlot) {{ $title }} @else

{{ $title }}

@endif @isset($action) {{ $action }} @endisset
``` # Label (/2.x/extending/components/label) The Label component provides a styled label for form fields with an optional required indicator. ## Preview [#preview]
## Usage [#usage] ```blade ``` ## Props [#props] The label text. Can also use the slot instead. Shows a red asterisk (*) after the label text. ## Examples [#examples] ### Basic Label [#basic-label] ```blade ``` ### Required Field [#required-field] ```blade ``` ### Using Slot [#using-slot] ```blade Full Name ``` ### With Form Input [#with-form-input] ```blade
``` ## Blade Component Source [#blade-component-source] ```blade @blaze @props([ 'value', 'isRequired' => false, ]) ``` # Loader (/2.x/extending/components/loader) The Loader component displays an animated spinning indicator for loading states. ## Preview [#preview] ## Usage [#usage] ```blade ``` ## Attributes [#attributes] The loader accepts standard HTML attributes that are merged with Tailwind classes: CSS classes to customize size and animation. Common sizes: `size-4`, `size-5`, `size-6`. ## Examples [#examples] ### Different Sizes [#different-sizes]
```blade ``` ### With Color [#with-color] ```blade ``` ### In a Button [#in-a-button] ```blade Save Saving... ``` ### Loading State [#loading-state] ```blade
``` ## Blade Component Source [#blade-component-source] ```blade @blaze(memo: true) twMerge(['class' => 'size-5 animate-spin']) }} fill="none" viewBox="0 0 24 24" aria-hidden="true" > ``` # Overview (/2.x/extending/components/overview) Shopper provides a set of Blade components that you can use when extending the admin panel. These components are designed to maintain visual consistency across your custom features. ## Available Components [#available-components] The component library includes: Container component with optional title and description for content grouping. Colored alert boxes for displaying messages with different severity levels. Page-level heading with optional action slot for buttons. Section titles with optional descriptions for content organization. Placeholder component for empty data states with call-to-action. ## Usage [#usage] All Shopper components are prefixed with `x-shopper::` and can be used in any Blade view within the admin panel context: ```blade

Card content goes here

``` ## Styling [#styling] Components use Tailwind CSS and support both light and dark modes out of the box. They follow the Shopper design system with consistent spacing, colors, and typography. ## Customization [#customization] You can customize components by: 1. **Passing attributes**: Most components accept standard HTML attributes via `$attributes` 2. **Using slots**: Many components support named slots for flexible content placement 3. **Overriding views**: Copy a component view to `resources/views/vendor/shopper/components/` in your application. Laravel loads your copy instead of the package view ```bash mkdir -p resources/views/vendor/shopper/components cp vendor/shopper/framework/resources/views/components/card.blade.php resources/views/vendor/shopper/components/card.blade.php ``` When overriding components, be careful to maintain the expected structure to avoid breaking the admin panel UI. # Section Heading (/2.x/extending/components/section-heading) The Section Heading component is used to introduce sections within a page. It displays a title with an optional description, providing context for the content that follows. ## Preview [#preview] ## Usage [#usage] ```blade ``` ## Props [#props] The section title text. Optional description text displayed below the title. ## Examples [#examples] ### Title Only [#title-only] ```blade ``` ### With Description [#with-description] ```blade ``` ### Inside a Card [#inside-a-card] The Section Heading is automatically used by the Card component when you pass a title prop:
Drop files here
```blade
``` ### Standalone Usage [#standalone-usage] You can also use the section heading independently for custom layouts: ```blade
``` ## Blade Component Source [#blade-component-source] The Section Heading component is located at `packages/admin/resources/views/components/section-heading.blade.php`: ```blade @blaze @props([ 'title', 'description' => null, ])
{{ $title }} @if ($description) {{ $description }} @endif
``` # Stock Badge (/2.x/extending/components/stock-badge) The Stock Badge component displays a colored badge indicating stock levels. It automatically changes color based on the stock quantity threshold. ## Preview [#preview]
## Usage [#usage] ```blade ``` ## Props [#props] The stock quantity to display. Values below 10 show as red (low stock), 10 or above show as green. ## Behavior [#behavior] | Stock Value | Color | Meaning | |------------|-------|---------| | `< 10` | Red | Low stock warning | | `>= 10` | Green | Stock OK | ## Examples [#examples] ### Low Stock [#low-stock] ```blade ``` ### Normal Stock [#normal-stock] ```blade ``` ### In a Table [#in-a-table] ```blade
Product Name
``` ## Blade Component Source [#blade-component-source] ```blade @blaze(memo: true) @props([ 'stock', ]) $stock < 10, 'bg-success-100 text-success-800' => $stock >= 10, ]) > {{ $stock }} ``` # User Avatar (/2.x/extending/components/user-avatar) The User Avatar component displays a user's profile picture with an optional name. Commonly used in Filament tables and user-related interfaces. ## Preview [#preview]
## Usage [#usage] ```blade ``` ## Props [#props] The user model instance. Must have `picture` and `full_name` attributes. Whether to display the user's name next to the avatar. ## Examples [#examples] ### With Name [#with-name] ```blade ``` ### Avatar Only [#avatar-only] ```blade ``` ### In a Filament Table [#in-a-filament-table] The view needs a `user` variable, so render it from `formatStateUsing()` and pass the related user: ```php use Filament\Tables\Columns\TextColumn; use Illuminate\Contracts\View\View; use Shopper\Core\Models\Order; TextColumn::make('customer.first_name') ->label(__('Customer')) ->formatStateUsing(fn (Order $record): View => view( 'shopper::components.user-avatar', ['user' => $record->customer] )), ``` ## User Model Requirements [#user-model-requirements] The user model must have `picture` and `full_name` attributes. The `Shopper\Traits\InteractsWithShopper` trait on your `User` model provides both: `full_name` joins the first and last name, and `picture` returns the uploaded avatar URL or a generated one. ## Blade Component Source [#blade-component-source] ```blade @props([ 'user', 'showName' => true, ])
{{ $user->full_name }} @if ($showName) {{ $user->full_name }} @endif
``` # Utility Components (/2.x/extending/components/utilities) These components provide structural and utility functionality. They don't require visual previews as they are primarily wrappers or functional elements. ## Container [#container] Page content wrapper with responsive horizontal padding. ```blade ``` **Source:** ```blade @blaze
twMerge(['class' => 'px-4 lg:px-6']) }}> {{ $slot }}
``` --- ## Link [#link] Internal navigation link with Livewire `wire:navigate.hover` for SPA-like navigation. ```blade Products ``` **Source:** ```blade @blaze {{ $slot }} ``` --- ## Separator [#separator] Visual divider between content sections. ```blade ``` **Source:** ```blade @blaze(fold: true)
``` --- ## Breadcrumb [#breadcrumb] Navigation breadcrumb with mobile back link support. ```blade ``` ### Props [#props] URL for mobile back link Current page title ### Breadcrumb Link [#breadcrumb-link] The `link` prop sets the URL and the `title` prop sets the text: ```blade ``` --- ## Validation Errors [#validation-errors] Displays Laravel validation errors in a styled error box. ```blade ``` Automatically displays all validation errors from `$errors->all()`. **Source:** ```blade @if ($errors->count() > 0)

{{ __('shopper::forms.error') }}

    @foreach ($errors->all() as $message)
  • {{ $message }}
  • @endforeach
@endif ``` --- ## Dropdown Link [#dropdown-link] Menu item for dropdown menus. ```blade Profile ``` --- ## Form Slide-over [#form-slide-over] Wrapper for forms displayed in slide-over panels. Use it in the view of a slide-over component: ```blade {{ $this->form }} ``` ### Props [#props-1] Livewire method to call on submit Slide-over header title Text below the title ### Slots [#slots] Form content The footer always shows a Cancel button, which dispatches `closePanel`, and a Save button that submits the form. # Control Panel (/2.x/extending/control-panel) The control panel may be customized in a number of different ways. You may add new pages, menus, a stylesheet, or maybe you just want to add some arbitrary JavaScript. When you need to add features to your Shopper administration, you can first set up some configurations. ## Adding CSS and JS Assets [#adding-css-and-js-assets] Shopper can load extra stylesheets and JavaScript files in the admin panel. Register them from a service provider using the `Shopper` facade: ```php use Shopper\Facades\Shopper; public function boot(): void { Shopper::styles([ '/css/admin.css', 'https://cdn.example.com/library.min.css', ])->scripts([ 'https://cdn.example.com/library.min.js', '/js/admin.js', ]); } ``` Local paths (starting with `/`) are resolved from the `public/` directory. CDN URLs are loaded directly. ## Customize Shopper theme [#customize-shopper-theme] Shopper ships with a pre-compiled CSS file (`dist/shopper.css`) that works out of the box. However, if you want to customize the admin panel styles using Tailwind CSS, you can build your own theme by importing Shopper's `theme.css` file. Shopper provides a dedicated `theme.css` entry point that handles all internal imports (Tailwind, Filament, Shopper base styles, source detection, and plugins) so you don't have to wire them up manually. ### Setting up Tailwind CSS for your project [#setting-up-tailwind-css-for-your-project] Install Tailwind CSS v4 with the Vite plugin and the required plugins: ```bash npm install -D tailwindcss @tailwindcss/vite @tailwindcss/forms @tailwindcss/typography ``` Add the `@tailwindcss/vite` plugin to your `vite.config.js`: ```js import tailwindcss from '@tailwindcss/vite'; export default defineConfig({ plugins: [ tailwindcss(), laravel({ input: [ 'resources/css/app.css', 'resources/css/shopper.css', // [!code highlight] ], }), ], }); ``` ### Creating the theme file [#creating-the-theme-file] Create a `resources/css/shopper.css` file and import Shopper's theme entry point: ```css @import '../../vendor/shopper/framework/resources/css/theme.css'; ``` The `theme.css` file already includes Tailwind, Filament CSS, Shopper base styles and components, source detection for all required Blade views, and the `@tailwindcss/forms` and `@tailwindcss/typography` plugins. You don't need to configure any of that yourself. To add your own source paths (custom Livewire components, app modules, etc.) or custom styles, add them after the import: ```css @import '../../vendor/shopper/framework/resources/css/theme.css'; /* Additional source paths for your project */ @source '../../resources/views/**/*.blade.php'; @source '../../app-modules/**/resources/views/**/*.blade.php'; /* Your custom styles */ ``` ### Load theme [#load-theme] In your `AppServiceProvider` or any other provider, register the Vite theme in the `boot` method: ```php use Shopper\Facades\Shopper; public function boot(): void { Shopper::registerViteTheme('resources/css/shopper.css'); } ``` ### Branding Logo [#branding-logo] By default, the Shopper logo is used on the login page and in the sidebar header. You have several options to replace it with your own brand. #### Via configuration [#via-configuration] The simplest approach is to set the `brand` key in your `config/shopper/admin.php` configuration file with a path to your logo image: ```php /* |-------------------------------------------------------------------------- | Brand Logo |-------------------------------------------------------------------------- | | This will be displayed on the login page and in the sidebar's header. | This is your site's logo. It will be loaded directly from the public folder | Ex: '/images/logo.svg' | */ 'brand' => 'images/logo.svg', ``` This will load the image using the Laravel `asset()` helper function, so the file should be in your `public/` directory. In the sidebar header, the logo shows next to the name of the store: #### Via service provider [#via-service-provider] For more control, use the `brandLogo()` method on the Shopper facade. You can pass an HTML string, a closure that returns a string, or a closure that returns a `View` instance: ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; public function boot(): void { // Simple image tag Shopper::brandLogo('My Store'); // With a Blade component Shopper::brandLogo(fn (): string => Blade::render('')); // With a Blade view Shopper::brandLogo(fn (): \Illuminate\Contracts\View\View => view('brand.logo')); } ``` This takes priority over the config value, giving you full flexibility to render any HTML, such as an inline SVG, a Blade component, a dedicated view, or anything else. The priority order is: `Shopper::brandLogo()` > `config('shopper.admin.brand')` > default Shopper logo. ## Render hooks [#render-hooks] Shopper allows you to render Blade content at specific points in the admin panel. This is useful for integrating third-party packages that require Blade components in the layout, such as [Flux UI](https://fluxui.dev), [Wire Elements Modal](https://github.com/wire-elements/modal), or [Laravel Notify](https://github.com/mckenziearts/laravel-notify), and for addons that need to inject content into specific pages. If you are familiar with [Filament's render hooks](https://filamentphp.com/docs/4.x/advanced/render-hooks), you already know how this works. Shopper's render hooks follow the same concept. Render hooks are organized into scoped classes by business domain under the `Shopper\View` namespace: | Class | Scope | |-------|-------| | `LayoutRenderHook` | Head, body, header, content, dashboard, account, settings | | `ProductRenderHook` | Product index, edit, variant | | `OrderRenderHook` | Order index, detail, shipments, abandoned carts | | `CustomerRenderHook` | Customer index, create, show | | `CollectionRenderHook` | Collection index, edit | | `CatalogRenderHook` | Categories, brands, tags, attributes, reviews | | `SalesRenderHook` | Discounts, suppliers | ### Registering a render hook [#registering-a-render-hook] To register a render hook, call the `Shopper::renderHook()` method from a service provider's `boot` method. The first argument is the hook constant, and the second is a closure that returns HTML: ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; public function boot(): void { Shopper::renderHook( LayoutRenderHook::BODY_END, fn (): string => Blade::render('@livewire("wire-elements-modal")'), ); } ``` Since all methods return the `ShopperPanel` instance, you can chain multiple calls: ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; public function boot(): void { Shopper::renderHook(LayoutRenderHook::HEAD_END, fn (): string => Blade::render('@fluxStyles')) ->renderHook(LayoutRenderHook::BODY_END, fn (): string => Blade::render('')) ->renderHook(LayoutRenderHook::BODY_END, fn (): string => Blade::render('')) ->registerViteTheme('resources/css/shopper.css') ->styles(['vendor/custom/lib.css']) ->scripts(['vendor/custom/lib.js']); } ``` You can also use hooks from different scoped classes to inject content into specific pages: ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\ProductRenderHook; Shopper::renderHook( ProductRenderHook::EDIT_HEADER_AFTER, fn (): string => Blade::render(''), ); ``` ### Available render hooks [#available-render-hooks] #### Layout [#layout] | Constant | Class | Description | |----------|-------|-------------| | `HEAD_START` | `LayoutRenderHook` | After the meta tags, before Filament styles and Shopper theme | | `HEAD_END` | `LayoutRenderHook` | In ``, after the Shopper theme, scripts, and extra stylesheets | | `BODY_START` | `LayoutRenderHook` | Start of ``, before any content | | `BODY_END` | `LayoutRenderHook` | End of ``, after Filament scripts | | `HEADER_START` | `LayoutRenderHook` | Start of the header bar content area | | `HEADER_END` | `LayoutRenderHook` | End of the header bar, before the site link and account dropdown | | `CONTENT_START` | `LayoutRenderHook` | Start of the main content area, after the sidebar | | `CONTENT_END` | `LayoutRenderHook` | End of the main content area | | `DASHBOARD_START` | `LayoutRenderHook` | Start of the dashboard page | | `DASHBOARD_END` | `LayoutRenderHook` | End of the dashboard page | | `ACCOUNT_START` | `LayoutRenderHook` | Before the account page content | | `ACCOUNT_END` | `LayoutRenderHook` | After the account page content | | `SETTINGS_INDEX_START` | `LayoutRenderHook` | Before the settings grid | | `SETTINGS_INDEX_END` | `LayoutRenderHook` | After the settings grid | #### Products [#products] | Constant | Class | Description | |----------|-------|-------------| | `INDEX_TABLE_BEFORE` | `ProductRenderHook` | Before the products table | | `INDEX_TABLE_AFTER` | `ProductRenderHook` | After the products table | | `EDIT_HEADER_AFTER` | `ProductRenderHook` | After the product edit page heading | | `EDIT_TABS_BEFORE` | `ProductRenderHook` | Before the product edit tabs | | `EDIT_TABS_END` | `ProductRenderHook` | Before the closing of the product edit tabs | | `EDIT_CONTENT_BEFORE` | `ProductRenderHook` | Before the product edit tab content | | `EDIT_CONTENT_AFTER` | `ProductRenderHook` | After the product edit tab content | | `VARIANT_HEADER_AFTER` | `ProductRenderHook` | After the variant page heading | | `VARIANT_MAIN_AFTER` | `ProductRenderHook` | After the variant main column | | `VARIANT_SIDEBAR_AFTER` | `ProductRenderHook` | After the variant sidebar column | #### Orders [#orders] | Constant | Class | Description | |----------|-------|-------------| | `INDEX_TABLE_BEFORE` | `OrderRenderHook` | Before the orders table | | `INDEX_TABLE_AFTER` | `OrderRenderHook` | After the orders table | | `DETAIL_HEADER_AFTER` | `OrderRenderHook` | After the order detail sticky header | | `DETAIL_MAIN_BEFORE` | `OrderRenderHook` | Before the order detail main content | | `DETAIL_MAIN_AFTER` | `OrderRenderHook` | After the order detail main column | | `DETAIL_SIDEBAR_BEFORE` | `OrderRenderHook` | Before the order detail sidebar | | `DETAIL_SIDEBAR_AFTER` | `OrderRenderHook` | After the order detail sidebar | | `SHIPMENTS_TABLE_BEFORE` | `OrderRenderHook` | Before the shipments table | | `SHIPMENTS_TABLE_AFTER` | `OrderRenderHook` | After the shipments table | | `ABANDONED_CARTS_TABLE_BEFORE` | `OrderRenderHook` | Before the abandoned carts table | | `ABANDONED_CARTS_TABLE_AFTER` | `OrderRenderHook` | After the abandoned carts table | #### Customers [#customers] | Constant | Class | Description | |----------|-------|-------------| | `INDEX_TABLE_BEFORE` | `CustomerRenderHook` | Before the customers table | | `INDEX_TABLE_AFTER` | `CustomerRenderHook` | After the customers table | | `CREATE_FORM_BEFORE` | `CustomerRenderHook` | Before the create customer form | | `CREATE_FORM_AFTER` | `CustomerRenderHook` | After the create customer form | | `SHOW_HEADER_AFTER` | `CustomerRenderHook` | After the customer show page header | | `SHOW_TABS_BEFORE` | `CustomerRenderHook` | Before the customer show tabs | | `SHOW_TABS_END` | `CustomerRenderHook` | Before the closing of the customer show tabs | | `SHOW_CONTENT_BEFORE` | `CustomerRenderHook` | Before the customer show tab content | | `SHOW_CONTENT_AFTER` | `CustomerRenderHook` | After the customer show tab content | #### Collections [#collections] | Constant | Class | Description | |----------|-------|-------------| | `INDEX_TABLE_BEFORE` | `CollectionRenderHook` | Before the collections table | | `INDEX_TABLE_AFTER` | `CollectionRenderHook` | After the collections table | | `EDIT_FORM_BEFORE` | `CollectionRenderHook` | Before the collection edit form | | `EDIT_FORM_AFTER` | `CollectionRenderHook` | After the collection edit form | #### Catalog [#catalog] | Constant | Class | Description | |----------|-------|-------------| | `CATEGORIES_TABLE_BEFORE` | `CatalogRenderHook` | Before the categories table | | `CATEGORIES_TABLE_AFTER` | `CatalogRenderHook` | After the categories table | | `BRANDS_TABLE_BEFORE` | `CatalogRenderHook` | Before the brands table | | `BRANDS_TABLE_AFTER` | `CatalogRenderHook` | After the brands table | | `TAGS_TABLE_BEFORE` | `CatalogRenderHook` | Before the tags table | | `TAGS_TABLE_AFTER` | `CatalogRenderHook` | After the tags table | | `ATTRIBUTES_TABLE_BEFORE` | `CatalogRenderHook` | Before the attributes table | | `ATTRIBUTES_TABLE_AFTER` | `CatalogRenderHook` | After the attributes table | | `REVIEWS_TABLE_BEFORE` | `CatalogRenderHook` | Before the reviews table | | `REVIEWS_TABLE_AFTER` | `CatalogRenderHook` | After the reviews table | #### Sales [#sales] | Constant | Class | Description | |----------|-------|-------------| | `DISCOUNTS_TABLE_BEFORE` | `SalesRenderHook` | Before the discounts table | | `DISCOUNTS_TABLE_AFTER` | `SalesRenderHook` | After the discounts table | | `SUPPLIERS_TABLE_BEFORE` | `SalesRenderHook` | Before the suppliers table | | `SUPPLIERS_TABLE_AFTER` | `SalesRenderHook` | After the suppliers table | ### Example: Wire Elements Modal [#example-wire-elements-modal] ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; Shopper::renderHook( LayoutRenderHook::BODY_END, fn (): string => Blade::render('@livewire("wire-elements-modal")'), ); ``` ### Example: Flux UI [#example-flux-ui] ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; Shopper::renderHook(LayoutRenderHook::HEAD_END, fn (): string => Blade::render('@fluxStyles')) ->renderHook(LayoutRenderHook::BODY_END, fn (): string => Blade::render('@fluxScripts')); ``` ### Example: Laravel Notify [#example-laravel-notify] ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; Shopper::renderHook( LayoutRenderHook::BODY_END, fn (): string => Blade::render(''), ); ``` ## Adding control panel routes [#adding-control-panel-routes] If you need to have custom routes for the control panel: 1. Create a routes file. Name it whatever you want, for example: `routes/shopper.php` 2. Then add this to your `shopper/routes.php` file so that all routes are dynamically loaded: ```php 'custom_file' => base_path('routes/shopper.php'), ``` 3. If you want to add middleware to further control access to the routes available in this file you can add in the key `middleware` of the `shopper/routes.php` file ```php 'middleware' => [ 'my-custom-middleware', 'permission:can-access', ], ``` # Controllers (/2.x/extending/controllers) You can add custom pages to the Shopper admin panel using either traditional Laravel controllers or Livewire components. Both approaches share the same authentication middleware and can be integrated into the admin sidebar navigation. ## Custom Routes [#custom-routes] To add custom routes inside the admin panel, set the `custom_file` key in `config/shopper/routes.php` to point to a dedicated route file: ```php // config/shopper/routes.php 'custom_file' => base_path('routes/shopper.php'), ``` Routes defined in this file are automatically loaded with the admin panel's middleware stack (authentication, authorization), under the admin URL prefix. Shopper also prefixes their names with `shopper.`, so a route you name `posts.index` is called with `route('shopper.posts.index')`. ## Using Controllers [#using-controllers] You can use standard Laravel controllers with Shopper. Create a controller in any namespace you prefer: ```bash php artisan make:controller Shopper/PostController ``` This creates a controller in `app/Http/Controllers/Shopper/PostController.php`: ```php namespace App\Http\Controllers\Shopper; use App\Http\Controllers\Controller; use App\Models\Post; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class PostController extends Controller { public function index(): View { $posts = Post::query()->latest()->paginate(20); return view('shopper.posts.index', compact('posts')); } public function create(): View { return view('shopper.posts.create'); } public function store(Request $request): RedirectResponse { // Handle form submission return redirect()->route('shopper.posts.index'); } } ``` Register the routes in your custom route file: ```php // routes/shopper.php use App\Http\Controllers\Shopper\PostController; use Illuminate\Support\Facades\Route; Route::get('/posts', [PostController::class, 'index'])->name('posts.index'); Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create'); Route::post('/posts', [PostController::class, 'store'])->name('posts.store'); ``` The views of a controller render inside the admin layout when they use the `x-shopper::layouts.app` component, which adds the sidebar, the top bar and the notifications around the page: ```blade title="resources/views/shopper/posts/index.blade.php"
    @foreach ($posts as $post)
  • {{ $post->title }}
  • @endforeach
{{ $posts->links() }}
``` The page renders next to the sidebar of the admin panel, under its top bar: ## Using Livewire Components [#using-livewire-components] Livewire is the recommended approach since the entire Shopper admin is built with Livewire. The `pages` configuration in `config/shopper/admin.php` sets the namespace and view path used by the `make:shopper-page` command: ```php // config/shopper/admin.php 'pages' => [ 'namespace' => 'App\\Livewire\\Shopper', 'view_path' => resource_path('views/livewire/shopper'), ], ``` Create a page component: ```bash php artisan make:shopper-page PostIndex ``` The command creates the class and its view. The class extends `Shopper\Livewire\Pages\AbstractPageComponent`, which renders the page inside the admin panel layout: ```php namespace App\Livewire\Shopper; use Illuminate\Contracts\View\View; use Shopper\Livewire\Pages\AbstractPageComponent; class PostIndex extends AbstractPageComponent { public function render(): View { return view('livewire.shopper.post-index'); } } ``` Register Livewire routes in your custom route file: ```php // routes/shopper.php use App\Livewire\Shopper\PostIndex; use Illuminate\Support\Facades\Route; Route::get('/posts', PostIndex::class)->name('posts.index'); ``` If your component extends `Livewire\Component` instead, add `#[Layout('shopper::components.layouts.app')]` to the class to inherit the admin panel layout with sidebar, header, and notification system. ## Adding Navigation [#adding-navigation] To add your custom page to the admin sidebar, create a sidebar extension. See the [Navigation](/2.x/extending/navigation) page for details on adding menu items that link to your controller or Livewire routes. ## Authorization Pattern for Custom Admin Components [#authorization-pattern-for-custom-admin-components] Custom Livewire components that extend or mimic Shopper's admin surfaces (orders, products, customers, settings) must follow the authorization pattern that Shopper enforces internally. Skipping any of these steps reintroduces the bypass surface that v2.8 closed across the shipped components. ### Chain `authorize()` on Filament Actions [#chain-authorize-on-filament-actions] Declare the required ability on the Filament `Action` itself, not inside the closure. This hides the button when the user lacks the ability instead of throwing a 403 on click: ```php use Filament\Actions\Action; Action::make('cancel') ->authorize('edit_orders') ->action(function (): void { // ... }); ``` ### Authorize Livewire Method Handlers [#authorize-livewire-method-handlers] Every public Livewire method that mutates state must call `$this->authorize()` on its first line. Livewire methods are reachable from the browser regardless of UI state, so the check belongs in the method body, not in the view that rendered the trigger: ```php public function leaveNotes(): void { $this->authorize('edit_orders'); // ... } ``` ### Lock Public Model Properties [#lock-public-model-properties] Any `public Model $x` property on a Livewire component must be marked `#[Locked]`. Without it, the browser can rebind the property to a different model ID and bypass authorization that was performed on the original target: ```php use Livewire\Attributes\Locked; use Shopper\Core\Models\Order; #[Locked] public Order $order; ``` ### Allow-List User Input [#allow-list-user-input] When persisting user input from the browser, use an explicit `Arr::only(...)` allow-list. `Arr::except(...)` is fragile: any new field that lands in the payload (including private state added by the framework) silently flows into the database: ```php use Illuminate\Support\Arr; $data = Arr::only($payload, ['first_name', 'last_name', 'email']); ``` ### Guard Lookups Against Null [#guard-lookups-against-null] Livewire components that resolve a model from user input must handle the lookup failure path. Returning early on null avoids the cascade of bypasses that follow when a misbound ID is treated as authoritative: ```php use Shopper\Models\Permission; public function togglePermission(int $permissionId): void { $this->authorize('access_setting'); $permission = Permission::query()->find($permissionId); if ($permission === null) { return; } // ... } ``` # Empty State (/2.x/extending/empty-state) # Empty State [#empty-state] # Forms (/2.x/extending/forms) # Forms [#forms] The forms allow us to quickly create input fields for our information to be stored in the database. Coming Soon... # Modals (/2.x/extending/modals) # Modals [#modals] Coming Soon... # Navigation (/2.x/extending/navigation) The Control Panel navigation is highly customizable. You can add your own groups, items, and sub-items to it. The navigation is controlled by the [shopper/sidebar](https://github.com/shopperlabs/sidebar) package. This package can be used both as a standalone sidebar builder for any Laravel application or to extend Shopper's admin panel. Learn about the sidebar package architecture and features. Add custom menu items to the Shopper admin panel. Use the sidebar package in any Laravel application. Configure caching, dimensions, and behavior. ## Quick Start [#quick-start] To add navigation items to Shopper, create a sidebar extension class and register it in your service provider: ```php namespace App\Sidebar; use Shopper\Sidebar\AbstractAdminSidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; class BlogSidebar extends AbstractAdminSidebar { public function extendWith(Menu $menu): Menu { $menu->group(__('Blog'), function (Group $group): void { $group->weight(5); $group->setAuthorized(); $group->item(__('Posts'), function (Item $item): void { $item->weight(1); $item->setAuthorized(); $item->useSpa(); $item->route('shopper.posts.index'); $item->setIcon('phosphor-article'); }); }); return $menu; } } ``` Register it in your `AppServiceProvider`: ```php namespace App\Providers; use App\Sidebar\BlogSidebar; use Illuminate\Support\ServiceProvider; use Shopper\Sidebar\SidebarBuilder; class AppServiceProvider extends ServiceProvider { public function register(): void { $this->app['events']->listen(SidebarBuilder::class, BlogSidebar::class); } } ``` The **Blog** group then shows in the sidebar, and its **Posts** entry is selected on the page it links to. The `shopper.posts.index` route is the one registered in [Controllers](/2.x/extending/controllers#using-controllers): Shopper registers its own sidebar listeners in the `register()` method of a service provider. The sidebar is built later, while the admin request runs, so a listener registered in `boot()` works too. ## API Reference [#api-reference] For a complete API reference, see the detailed documentation: | Component | Description | Documentation | |-----------|-------------|---------------| | Menu | Root container for groups | [Standalone Guide](/2.x/sidebar/standalone#group-api) | | Group | Collection of related items | [Standalone Guide](/2.x/sidebar/standalone#group-api) | | Item | Navigation entry with icon, badge, etc. | [Standalone Guide](/2.x/sidebar/standalone#menu-item-api) | | Badge | Notification indicator | [Standalone Guide](/2.x/sidebar/standalone#adding-badges) | | Append | Action button | [Standalone Guide](/2.x/sidebar/standalone#adding-append-elements) | # Extending Shopper (/2.x/extending/overview) Although Shopper is primarily designed for e-commerce sites and has many associated features, you are free to add or modify existing ones. ## Why extend Shopper [#why-extends-shopper] One might ask, knowing that the purpose of setting up an e-commerce site is simply to make the whole system work without always wanting to add to it. For example if you want a blog on your store, a section for a KYC, or maybe a forum, instead of creating another project to manage this you can directly extend Shopper to manage all this in the same administration area. ## How to extend Shopper [#how-to-extend-shopper] To add new features to Shopper, the first thing you need to do is to register a new element in the sidebar by creating a sidebar class (for example `RegisterCustomMenu`, which extends `Shopper\Sidebar\AbstractAdminSidebar`) and listening to the `SidebarBuilder` event with it in your `AppServiceProvider`. See [Extending Shopper](/2.x/sidebar/shopper-extension) for the sidebar class: ```php namespace App\Providers; use App\Sidebar\RegisterCustomMenu; use Illuminate\Support\ServiceProvider; use Shopper\Sidebar\SidebarBuilder; class AppServiceProvider extends ServiceProvider { public function register(): void { $this->app['events']->listen(SidebarBuilder::class, RegisterCustomMenu::class); } } ``` The rest of the configuration will be done using the configuration files in the `config/shopper/` folder - `/routes.php` for the routes that should be dynamically loaded for the admin panel - `/admin.php` for the admin panel configuration (URL prefix, domain, pages, roles, brand). We will deal with all this in more detail later. ## How not to extend Shopper [#how-not-to-extend-shopper] It should go without saying, but we'll say it anyway just in case... Don't ever, for any reason, ever, no matter what, no matter where, or who, or who you are with, or where you are going or... or where you've been... ever, for any reason, whatsoever, edit the files inside `/vendor/shopper`. Or any other Composer package. Anything you do will get blown away and you'll lose those changes forever and ever amen. You should instead build addons, extensions, and submit pull requests to [admin](https://github.com/shopperlabs/shopper) (after checking with the team first if we'll accept them). Thanks! # Slideover (/2.x/extending/slideover) The forms allow us to quickly create input fields for our information to be stored in the database. Coming Soon... # Render Hooks (/2.x/render-hooks) Render hooks give you named injection points inside Shopper's admin views. Instead of overriding templates, you register a callback on a hook name and Shopper renders your content in the right place at the right time. This is the recommended way to extend any admin page: adding a custom banner to the order detail sidebar, inserting a widget above the product list, or injecting tracking scripts into the page head. ## Registering a Hook [#registering-a-hook] Hooks are registered on the `ShopperPanel` instance via the `Shopper` facade. The recommended place to register them is in the `boot()` method of your application's service provider or in a dedicated extension service provider. ```php use Shopper\Facades\Shopper; use Shopper\View\OrderRenderHook; Shopper::renderHook( OrderRenderHook::DETAIL_SIDEBAR_AFTER, fn (): string => view('orders.custom-sidebar-widget')->render(), ); ``` The callback receives no arguments and must return a `string`. Shopper outputs the returned string as HTML without compiling it with Blade, so return plain HTML, a rendered Blade view, or a Livewire component rendered with `Blade::render()`. The `orders.custom-sidebar-widget` view holds the content of the hook: ```blade title="resources/views/orders/custom-sidebar-widget.blade.php"

Ships from the Lyon warehouse.

``` The text shows at the end of the sidebar of the order page, below the billing address: ### Returning a Blade View [#returning-a-blade-view] ```php use Shopper\Facades\Shopper; use Shopper\View\ProductRenderHook; Shopper::renderHook( ProductRenderHook::EDIT_CONTENT_AFTER, fn (): string => view('products.seo-panel')->render(), ); ``` ### Returning a Livewire Component [#returning-a-livewire-component] ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\CustomerRenderHook; Shopper::renderHook( CustomerRenderHook::SHOW_TABS_END, fn (): string => Blade::render(''), ); ``` ### Registering Multiple Hooks [#registering-multiple-hooks] You can chain multiple `renderHook()` calls on the same `Shopper` instance: ```php use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; Shopper::renderHook( LayoutRenderHook::HEAD_END, fn (): string => '', ); Shopper::renderHook( LayoutRenderHook::BODY_START, fn (): string => view('analytics.noscript-tag')->render(), ); ``` Multiple callbacks registered on the same hook are rendered in the order they were registered, concatenated together. ## Disabling a Hook [#disabling-a-hook] Hooks registered from an addon respect the addon's enabled state: they are never registered when the addon is disabled. For application-level hooks, you can conditionally register them: ```php if (config('features.custom_order_widget')) { Shopper::renderHook( OrderRenderHook::DETAIL_MAIN_AFTER, fn (): string => view('orders.external-status')->render(), ); } ``` ## Available Hooks [#available-hooks] ### Layout Hooks [#layout-hooks] `LayoutRenderHook` covers the global admin layout present on every page. | Constant | Hook Name | Position | |----------|-----------|----------| | `HEAD_START` | `shopper::head.start` | In ``, after the meta tags and before the Filament styles and Shopper theme | | `HEAD_END` | `shopper::head.end` | In ``, after the Shopper theme, scripts, and extra stylesheets | | `BODY_START` | `shopper::body.start` | Immediately after `` | | `BODY_END` | `shopper::body.end` | Immediately before `` | | `HEADER_START` | `shopper::header.start` | Start of the top navigation bar | | `HEADER_END` | `shopper::header.end` | In the top navigation bar, before the site link and account dropdown | | `CONTENT_START` | `shopper::content.start` | Before the main page content area | | `CONTENT_END` | `shopper::content.end` | After the main page content area | | `DASHBOARD_START` | `shopper::dashboard.start` | Top of the dashboard page | | `DASHBOARD_END` | `shopper::dashboard.end` | Bottom of the dashboard page | | `ACCOUNT_START` | `shopper::account.start` | Top of the account/profile page | | `ACCOUNT_END` | `shopper::account.end` | Bottom of the account/profile page | | `SETTINGS_INDEX_START` | `shopper::settings.index.start` | Top of the settings index page | | `SETTINGS_INDEX_END` | `shopper::settings.index.end` | Bottom of the settings index page | ### Product Hooks [#product-hooks] `ProductRenderHook` targets the product list and product edit pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::products.index.table.before` | Above the products table | | `INDEX_TABLE_AFTER` | `shopper::products.index.table.after` | Below the products table | | `EDIT_HEADER_AFTER` | `shopper::product.edit.header.after` | Below the product page header | | `EDIT_TABS_BEFORE` | `shopper::product.edit.tabs.before` | Before the edit page tabs | | `EDIT_TABS_END` | `shopper::product.edit.tabs.end` | After the last edit page tab (use to add new tabs) | | `EDIT_CONTENT_BEFORE` | `shopper::product.edit.content.before` | Before the active tab content | | `EDIT_CONTENT_AFTER` | `shopper::product.edit.content.after` | After the active tab content | | `VARIANT_HEADER_AFTER` | `shopper::product.variant.header.after` | Below the variant page header | | `VARIANT_MAIN_AFTER` | `shopper::product.variant.main.after` | After the variant main content area | | `VARIANT_SIDEBAR_AFTER` | `shopper::product.variant.sidebar.after` | After the variant sidebar | ### Order Hooks [#order-hooks] `OrderRenderHook` targets the order list, order detail, shipments, and abandoned carts pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::orders.index.table.before` | Above the orders table | | `INDEX_TABLE_AFTER` | `shopper::orders.index.table.after` | Below the orders table | | `DETAIL_HEADER_AFTER` | `shopper::order.detail.header.after` | Below the order detail page header | | `DETAIL_MAIN_BEFORE` | `shopper::order.detail.main.before` | Before the main content column | | `DETAIL_MAIN_AFTER` | `shopper::order.detail.main.after` | After the main content column | | `DETAIL_SIDEBAR_BEFORE` | `shopper::order.detail.sidebar.before` | Before the sidebar column | | `DETAIL_SIDEBAR_AFTER` | `shopper::order.detail.sidebar.after` | After the sidebar column | | `SHIPMENTS_TABLE_BEFORE` | `shopper::shipments.index.table.before` | Above the shipments table | | `SHIPMENTS_TABLE_AFTER` | `shopper::shipments.index.table.after` | Below the shipments table | | `ABANDONED_CARTS_TABLE_BEFORE` | `shopper::abandoned-carts.table.before` | Above the abandoned carts table | | `ABANDONED_CARTS_TABLE_AFTER` | `shopper::abandoned-carts.table.after` | Below the abandoned carts table | ### Customer Hooks [#customer-hooks] `CustomerRenderHook` targets the customer list and customer detail pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::customers.index.table.before` | Above the customers table | | `INDEX_TABLE_AFTER` | `shopper::customers.index.table.after` | Below the customers table | | `CREATE_FORM_BEFORE` | `shopper::customer.create.form.before` | Before the new customer form | | `CREATE_FORM_AFTER` | `shopper::customer.create.form.after` | After the new customer form | | `SHOW_HEADER_AFTER` | `shopper::customer.show.header.after` | Below the customer detail header | | `SHOW_TABS_BEFORE` | `shopper::customer.show.tabs.before` | Before the customer detail tabs | | `SHOW_TABS_END` | `shopper::customer.show.tabs.end` | After the last customer tab (use to add new tabs) | | `SHOW_CONTENT_BEFORE` | `shopper::customer.show.content.before` | Before the active tab content | | `SHOW_CONTENT_AFTER` | `shopper::customer.show.content.after` | After the active tab content | ### Collection Hooks [#collection-hooks] `CollectionRenderHook` targets the collection list and collection edit pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::collections.index.table.before` | Above the collections table | | `INDEX_TABLE_AFTER` | `shopper::collections.index.table.after` | Below the collections table | | `EDIT_FORM_BEFORE` | `shopper::collection.edit.form.before` | Before the collection edit form | | `EDIT_FORM_AFTER` | `shopper::collection.edit.form.after` | After the collection edit form | ### Catalog Hooks [#catalog-hooks] `CatalogRenderHook` covers the catalog support pages: categories, brands, tags, attributes, and reviews. | Constant | Hook Name | Position | |----------|-----------|----------| | `CATEGORIES_TABLE_BEFORE` | `shopper::categories.index.table.before` | Above the categories table | | `CATEGORIES_TABLE_AFTER` | `shopper::categories.index.table.after` | Below the categories table | | `BRANDS_TABLE_BEFORE` | `shopper::brands.index.table.before` | Above the brands table | | `BRANDS_TABLE_AFTER` | `shopper::brands.index.table.after` | Below the brands table | | `TAGS_TABLE_BEFORE` | `shopper::tags.index.table.before` | Above the tags table | | `TAGS_TABLE_AFTER` | `shopper::tags.index.table.after` | Below the tags table | | `ATTRIBUTES_TABLE_BEFORE` | `shopper::attributes.index.table.before` | Above the attributes table | | `ATTRIBUTES_TABLE_AFTER` | `shopper::attributes.index.table.after` | Below the attributes table | | `REVIEWS_TABLE_BEFORE` | `shopper::reviews.index.table.before` | Above the reviews table | | `REVIEWS_TABLE_AFTER` | `shopper::reviews.index.table.after` | Below the reviews table | ### Sales Hooks [#sales-hooks] `SalesRenderHook` covers the discounts and suppliers pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `DISCOUNTS_TABLE_BEFORE` | `shopper::discounts.index.table.before` | Above the discounts table | | `DISCOUNTS_TABLE_AFTER` | `shopper::discounts.index.table.after` | Below the discounts table | | `SUPPLIERS_TABLE_BEFORE` | `shopper::suppliers.index.table.before` | Above the suppliers table | | `SUPPLIERS_TABLE_AFTER` | `shopper::suppliers.index.table.after` | Below the suppliers table | ## Example: Injecting an External Status Badge on Order Detail [#example-injecting-an-external-status-badge-on-order-detail] A real-world scenario: your store syncs orders to a fulfillment service (ShipStation, ShipBob, etc.) and you want to display the external status directly on the order detail page, without modifying any Shopper files. The hook callback receives no arguments, so it cannot pass the order to your component. Instead, the hook renders a Livewire component that reads the order from the current route in its `mount()` method. The order detail route is `{order}/detail`, and the order detail page resolves `{order}` to the `Order` model. Livewire keeps the component's state on later requests, so `mount()` only runs on the page load. Create the Livewire component: ```php title="app/Livewire/ExternalOrderStatus.php" orderId = request()->route('order')->id; } public function render(): View { $status = ExternalFulfillmentService::getStatus($this->orderId); return view('livewire.external-order-status', ['status' => $status]); } } ``` Register the hook in your service provider: ```php use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\OrderRenderHook; public function boot(): void { Shopper::renderHook( OrderRenderHook::DETAIL_SIDEBAR_AFTER, fn (): string => Blade::render(''), ); } ``` ## Using Hook Constants vs. Raw Strings [#using-hook-constants-vs-raw-strings] Always use the class constants instead of raw hook name strings. They are checked by static analysis, will trigger IDE autocompletion, and won't silently break if a hook name changes in a future release. ```php use Shopper\View\ProductRenderHook; Shopper::renderHook(ProductRenderHook::EDIT_CONTENT_AFTER, fn () => '...'); Shopper::renderHook('shopper::product.edit.content.after', fn () => '...'); ``` # Configuration (/2.x/sidebar/configuration) The sidebar package can be configured through the `config/sidebar.php` file. Publish it if you haven't already: ```bash php artisan vendor:publish --provider="Shopper\Sidebar\SidebarServiceProvider" --tag="sidebar-config" ``` ## Configuration Options [#configuration-options] ### Caching [#caching] ```php 'cache' => [ 'method' => null, 'duration' => 1440, ], ``` | Option | Values | Description | |--------|--------|-------------| | `method` | `null`, `static`, `user-based` | The caching strategy to use | | `duration` | integer | Cache duration in seconds | **Caching Methods:** - `null` - No caching, sidebar is rebuilt on every request - `static` - Cache the sidebar once for all users - `user-based` - Cache per user (useful when authorization differs per user). This method needs a cache store that supports tags For production environments with static sidebars, use `static` caching to improve performance. ### Dimensions [#dimensions] ```php 'width' => '16rem', 'collapsed_width' => '4.5rem', ``` | Option | Default | Description | |--------|---------|-------------| | `width` | `16rem` | The sidebar width when expanded | | `collapsed_width` | `4.5rem` | The sidebar width when collapsed | These values are available as CSS variables `--sidebar-width` and `--sidebar-collapsed-width`. ### Responsive Breakpoint [#responsive-breakpoint] ```php 'breakpoint' => 1024, ``` The pixel width below which the sidebar switches to mobile mode. In mobile mode: - The sidebar is hidden by default - Opening the sidebar shows it as an overlay - The sidebar cannot be collapsed (only opened/closed) ### Collapsible [#collapsible] ```php 'collapsible' => true, ``` Whether the sidebar can be collapsed on desktop screens. When set to `false`, the collapse functionality is disabled and the sidebar remains at full width. ## Full Configuration Example [#full-configuration-example] ```php [ 'method' => null, 'duration' => 1440, ], /* |-------------------------------------------------------------------------- | Sidebar Dimensions |-------------------------------------------------------------------------- | | Configure the sidebar width for expanded and collapsed states. | These values will be injected as CSS variables. | */ 'width' => '16rem', 'collapsed_width' => '4.5rem', /* |-------------------------------------------------------------------------- | Responsive Breakpoint |-------------------------------------------------------------------------- | | The breakpoint (in pixels) below which the sidebar switches to mobile | mode (hidden by default, shown via toggle). | */ 'breakpoint' => 1024, /* |-------------------------------------------------------------------------- | Collapsible |-------------------------------------------------------------------------- | | Whether the sidebar can be collapsed on desktop. | */ 'collapsible' => true, ]; ``` ## Environment Variables [#environment-variables] You can use environment variables for deployment flexibility: ```dotenv SIDEBAR_CACHE=static ``` ```php 'cache' => [ 'method' => env('SIDEBAR_CACHE', null), 'duration' => env('SIDEBAR_CACHE_DURATION', 1440), ], ``` ## Accessing Configuration [#accessing-configuration] Use the helper functions to access configuration values: ```php use function Shopper\Sidebar\sidebar_config; use function Shopper\Sidebar\sidebar_width; use function Shopper\Sidebar\sidebar_collapsed_width; use function Shopper\Sidebar\sidebar_breakpoint; use function Shopper\Sidebar\sidebar_is_collapsible; // Get any config value $cacheMethod = sidebar_config('cache.method'); // Get dimensions $width = sidebar_width(); // '16rem' $collapsed = sidebar_collapsed_width(); // '4.5rem' // Get responsive settings $breakpoint = sidebar_breakpoint(); // 1024 $collapsible = sidebar_is_collapsible(); // true ``` ## Injecting CSS Variables [#injecting-css-variables] Use the helper functions to inject CSS variables in your layout: ```blade ``` The `data-*` attributes are automatically read by the Alpine.js sidebar store to configure its behavior. ## Customizing Views [#customizing-views] Publish the views to customize the sidebar rendering: ```bash php artisan vendor:publish --provider="Shopper\Sidebar\SidebarServiceProvider" --tag="sidebar-views" ``` This publishes the following views to `resources/views/vendor/sidebar/`: | View | Description | |------|-------------| | `menu.blade.php` | The root menu container | | `group.blade.php` | A sidebar group with optional heading | | `item.blade.php` | A single menu item | | `badge.blade.php` | Item badge component | | `append.blade.php` | Item append action component | ### Example: Customizing the Item View [#example-customizing-the-item-view] ```blade {{-- resources/views/vendor/sidebar/item.blade.php --}}
  • withSpa()) wire:navigate @endif @if($item->getNewTab()) target="_blank" @endif class="flex items-center gap-3 p-2 rounded-lg" > @if($item->getIcon()) @endif {{ $item->getName() }} @foreach($item->getBadges() as $badge) @include('sidebar::badge', ['badge' => $badge]) @endforeach @if($item->getItems()->count())
      @foreach($item->getItems() as $subItem) @include('sidebar::item', ['item' => $subItem]) @endforeach
    @endif
  • ``` ## Clearing the Cache [#clearing-the-cache] To clear the sidebar cache, clear the application cache: ```bash php artisan cache:clear ``` When a cache method is set, the package binds a `SidebarFlusher` service for that method. The `SidebarManager` passes it every registered sidebar, so you can flush them all programmatically: ```php use Shopper\Sidebar\SidebarManager; app()->call([app(SidebarManager::class), 'flush']); ``` # Sidebar Package (/2.x/sidebar/overview) The `shopper/sidebar` package is a headless sidebar builder for Laravel that allows you to create and manage sidebars with full customization support. Originally forked from [SpartnerNL/Laravel-Sidebar](https://github.com/SpartnerNL/Laravel-Sidebar), it has been completely rewritten to support modern Laravel applications with Livewire and Alpine.js. ## Features [#features] - **Headless Architecture**: Full control over your sidebar's HTML and styling - **Livewire Integration**: Built-in Livewire component for easy setup - **Alpine.js State Management**: Reactive sidebar state with collapse, expand, and responsive features - **LocalStorage Persistence**: User preferences are saved automatically - **Event-Based Extension**: Extend existing sidebars using Laravel events - **Caching Support**: Optional sidebar caching for performance - **Authorization**: Built-in authorization support for items and groups ## Architecture [#architecture] The sidebar package is built around several key concepts: ### Menu [#menu] The root container that holds all sidebar groups. Each sidebar has one menu that contains multiple groups. ### Group [#group] A collection of related menu items with an optional heading. Groups can be collapsible and styled independently. ### Item [#item] A single navigation entry that can have: - An icon - A badge (for notifications, counts, etc.) - An append element (additional action button) - Nested sub-items ### Contracts [#contracts] The package uses contracts (interfaces) for all major components, allowing you to customize or replace default implementations: - `Shopper\Sidebar\Contracts\Sidebar` - Main sidebar interface - `Shopper\Sidebar\Contracts\Builder\Menu` - Menu builder - `Shopper\Sidebar\Contracts\Builder\Group` - Group builder - `Shopper\Sidebar\Contracts\Builder\Item` - Item builder - `Shopper\Sidebar\Contracts\Builder\Badge` - Badge builder - `Shopper\Sidebar\Contracts\Builder\Append` - Append builder ## Use Cases [#use-cases] ### Standalone Laravel Applications [#standalone-laravel-applications] You can use this package in any Laravel application to create custom sidebars. See the [Standalone Installation](/2.x/sidebar/standalone) guide. ### Extending Shopper [#extending-shopper] If you're using Shopper, you can extend the admin panel sidebar using the event-based system. See [Extending Shopper Navigation](/2.x/sidebar/shopper-extension) for details. ## Requirements [#requirements] - PHP 8.3+ - Laravel 11.28+, 12.x or 13.x - Livewire 3.8+ or 4.x - Alpine.js 3.x # Extending Shopper (/2.x/sidebar/shopper-extension) This guide covers how to add custom navigation items to the Shopper admin panel using the sidebar extension system. ## Overview [#overview] Shopper uses an event-based system to build the sidebar. When the sidebar is rendered, it dispatches a `SidebarBuilder` event that you can listen to and add your own menu groups and items. ## Creating a Sidebar Extension [#creating-a-sidebar-extension] ### 1. Create an Extension Class [#1-create-an-extension-class] Create a class that extends `AbstractAdminSidebar`: ```php group(__('Blog'), function (Group $group): void { $group->weight(5); $group->setAuthorized(); $group->item(__('Posts'), function (Item $item): void { $item->weight(1); $item->setAuthorized(); $item->useSpa(); $item->route('shopper.blog.posts.index'); $item->setIcon('phosphor-article'); }); $group->item(__('Categories'), function (Item $item): void { $item->weight(2); $item->setAuthorized(); $item->useSpa(); $item->route('shopper.blog.categories.index'); $item->setIcon('phosphor-folder'); }); }); return $menu; } } ``` The `$this->user` property is available in your extension class to access the authenticated user for authorization checks. Shopper draws its own entries with Phosphor icons (`phosphor-*`), and the admin panel styles fill every sidebar icon with the text color. Use Phosphor, or another Blade Icons set drawn with filled shapes: an outline icon, such as the Untitled UI icons that the sidebar package installs (`untitledui-*`), gets its outline filled in and shows as a solid shape. ### 2. Register the Extension [#2-register-the-extension] Register your sidebar extension in a service provider: ```php app['events']->listen(SidebarBuilder::class, BlogSidebar::class); } } ``` Shopper registers its own sidebar listeners in the `register()` method of a service provider. The sidebar is built later, while the admin request runs, so a listener registered in `boot()` works too. ## Weight System [#weight-system] The `weight` value determines the order of items and groups. Lower values appear first: | Section | Weight | |---------|--------| | Dashboard | 1 | | Catalog | 2 | | Sales | 3 | | Customers | 3 | | Your Extension | 4 and above | Choose a weight value that positions your menu in the desired location. The Settings link sits in the sidebar footer and does not use a weight. ## Adding Sub-Items [#adding-sub-items] Items can have nested sub-items for dropdown menus: ```php $group->item(__('Blog'), function (Item $item): void { $item->weight(1); $item->setAuthorized(); $item->route('shopper.blog.posts.index'); $item->setIcon('phosphor-article'); // Sub-items $item->item(__('All Posts'), function (Item $subItem): void { $subItem->weight(1); $subItem->setAuthorized(); $subItem->useSpa(); $subItem->route('shopper.blog.posts.index'); }); $item->item(__('Create Post'), function (Item $subItem): void { $subItem->weight(2); $subItem->setAuthorized(); $subItem->useSpa(); $subItem->route('shopper.blog.posts.create'); }); }); ``` The sidebar adds the `sh-items-has-child` class to an item that has sub-items, which enables the dropdown styling. ## Authorization [#authorization] ### Permission-Based Authorization [#permission-based-authorization] Use Laravel's authorization system to control visibility: ```php $group->item(__('Posts'), function (Item $item): void { // Only show if user can manage posts $item->setAuthorized($this->user->can('manage_posts')); // ... rest of configuration }); ``` ### Role-Based Authorization [#role-based-authorization] ```php $group->item(__('Admin Settings'), function (Item $item): void { $item->setAuthorized($this->user->isAdmin()); // ... rest of configuration }); ``` ## Adding Badges [#adding-badges] Show notification counts or labels on menu items. Every call to `badge()` adds a badge, so check the count before adding it: ```php use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Models\Order; $group->item(__('Orders'), function (Item $item): void { // ... item configuration // Add a badge with the new order count $count = Order::query()->where('status', OrderStatus::New)->count(); if ($count > 0) { $item->badge($count, 'bg-danger-500 text-white'); } }); ``` ## Adding Quick Actions (Append) [#adding-quick-actions-append] Add action buttons next to menu items: ```php $group->item(__('Customers'), function (Item $item): void { // ... item configuration // Add a "+" button to quickly create a customer $item->append(function (Append $append): void { $append->route('shopper.customers.create'); $append->setIcon('untitledui-plus'); $append->setName(__('Add Customer')); $append->setClass('sh-sidebar-item-nav'); $append->setAuthorized($this->user->hasPermissionTo('add_customers')); }); }); ``` ## Complete Example [#complete-example] Here's a complete example of a blog sidebar extension: ```php group(__('Content'), function (Group $group): void { $group->weight(5); $group->setAuthorized(); $group->item(__('Blog'), function (Item $item): void { $item->weight(1); $item->setAuthorized($this->user->can('manage_blog')); $item->route('shopper.blog.posts.index'); $item->setIcon('phosphor-note-pencil'); // Badge for draft posts $drafts = Post::draft()->count(); if ($drafts > 0) { $item->badge(function (Badge $badge) use ($drafts): void { $badge->setValue($drafts); $badge->setClass('text-xs bg-warning-100 text-warning-700'); }); } // Quick create button $item->append(function (Append $append): void { $append->route('shopper.blog.posts.create'); $append->setIcon('untitledui-plus'); $append->setName(__('New Post')); $append->setClass('sh-sidebar-item-nav'); }); // Sub-items $item->item(__('All Posts'), function (Item $subItem): void { $subItem->weight(1); $subItem->setAuthorized(); $subItem->useSpa(); $subItem->route('shopper.blog.posts.index'); }); $item->item(__('Categories'), function (Item $subItem): void { $subItem->weight(2); $subItem->setAuthorized(); $subItem->useSpa(); $subItem->route('shopper.blog.categories.index'); }); $item->item(__('Tags'), function (Item $subItem): void { $subItem->weight(3); $subItem->setAuthorized(); $subItem->useSpa(); $subItem->route('shopper.blog.tags.index'); }); }); $group->item(__('Pages'), function (Item $item): void { $item->weight(2); $item->setAuthorized($this->user->can('manage_pages')); $item->useSpa(); $item->route('shopper.pages.index'); $item->setIcon('phosphor-file-text'); }); }); return $menu; } } ``` ## Using Closures for Dynamic Sidebars [#using-closures-for-dynamic-sidebars] For simpler cases, you can use a closure instead of a class: ```php use Illuminate\Support\Facades\Event; use Shopper\Sidebar\SidebarBuilder; Event::listen(SidebarBuilder::class, function (SidebarBuilder $sidebar) { $menu = $sidebar->getMenu(); $menu->group('Quick Links', function ($group) { $group->weight(100); $group->item('Documentation') ->setUrl('https://docs.example.com') ->isNewTab() ->setIcon('phosphor-book-open'); }); $sidebar->add($menu); }); ``` ## Routes Configuration [#routes-configuration] Add your routes in the `routes/shopper.php` file (configured in `config/shopper/routes.php`): ```php use App\Http\Controllers\Shopper\CategoryController; use App\Http\Controllers\Shopper\PostController; use Illuminate\Support\Facades\Route; Route::prefix('blog')->name('blog.')->group(function (): void { Route::get('posts', [PostController::class, 'index'])->name('posts.index'); Route::get('posts/create', [PostController::class, 'create'])->name('posts.create'); Route::get('categories', [CategoryController::class, 'index'])->name('categories.index'); }); ``` All routes in `routes/shopper.php` are automatically prefixed with the Shopper route prefix and have the `shopper.` route name prefix. So the `blog.posts.index` route above becomes `shopper.blog.posts.index`. # Standalone Installation (/2.x/sidebar/standalone) This guide covers how to install and use the sidebar package in a standalone Laravel application (without Shopper). ## Installation [#installation] Install the package via Composer: ```bash composer require shopper/sidebar ``` Publish the configuration file: ```bash php artisan vendor:publish --provider="Shopper\Sidebar\SidebarServiceProvider" --tag="sidebar-config" ``` Optionally, publish the views for customization: ```bash php artisan vendor:publish --provider="Shopper\Sidebar\SidebarServiceProvider" --tag="sidebar-views" ``` ## Setting Up the Middleware [#setting-up-the-middleware] Add the sidebar resolver middleware to your route group or in `bootstrap/app.php`: ```php Route::middleware(['web', \Shopper\Sidebar\Middleware\ResolveSidebars::class]) ->group(function () { ... }); ``` Or in Laravel 11+ with `bootstrap/app.php`: ```php ->withMiddleware(function (Middleware $middleware) { $middleware->appendToGroup('web', [ \Shopper\Sidebar\Middleware\ResolveSidebars::class, ]); }) ``` ## Creating a Sidebar [#creating-a-sidebar] ### 1. Create a Sidebar Class [#1-create-a-sidebar-class] Create a class that implements the `Sidebar` contract: ```php menu->group('Main', function (Group $group): void { $group->weight(1); $group->setAuthorized(); $group->setGroupItemsClass('space-y-1'); $group->item('Dashboard', function (Item $item): void { $item->weight(1); $item->setAuthorized(); $item->route('dashboard'); $item->setIcon('heroicon-o-home'); }); $group->item('Users', function (Item $item): void { $item->weight(2); $item->setAuthorized(); $item->route('users.index'); $item->setIcon('heroicon-o-users'); // Add sub-items $item->item('All Users', function (Item $subItem): void { $subItem->route('users.index'); }); $item->item('Create User', function (Item $subItem): void { $subItem->route('users.create'); }); }); }); $this->menu->group('Settings', function (Group $group): void { $group->weight(10); $group->setAuthorized(); $group->item('General', function (Item $item): void { $item->weight(1); $item->route('settings.general'); $item->setIcon('heroicon-o-cog'); }); }); } public function getMenu(): Menu { return $this->menu; } } ``` ### 2. Register the Sidebar [#2-register-the-sidebar] Register your sidebar in a service provider using the `SidebarManager`: ```php register(AdminSidebar::class); } } ``` Don't forget to register the service provider in `config/app.php` or `bootstrap/providers.php`. ## Using the Sidebar [#using-the-sidebar] ### Option 1: Livewire Component [#option-1-livewire-component] The easiest way to use the sidebar is with the built-in Livewire component: ```blade @livewire('sidebar', [ 'sidebarClass' => \App\Sidebar\AdminSidebar::class, 'class' => 'h-full', 'collapsible' => true, ]) ``` ### Option 2: Custom Blade Implementation [#option-2-custom-blade-implementation] For full control, use the `SidebarRenderer` directly: ```blade @php $sidebar = app(\App\Sidebar\AdminSidebar::class); $sidebar->build(); $renderer = app(\Shopper\Sidebar\Presentation\SidebarRenderer::class); $renderedSidebar = $renderer->render($sidebar); @endphp ``` ## Alpine.js Store Setup [#alpinejs-store-setup] The sidebar uses an Alpine.js store for state management. Livewire ships Alpine, so register the store when Alpine initializes. Alpine calls the store's `init()` method when the store is registered: ```javascript import sidebarStore from './vendor/sidebar/stores/sidebar' document.addEventListener('alpine:init', () => { window.Alpine.store('sidebar', sidebarStore()) }) ``` To get the source JavaScript files, publish them: ```bash php artisan vendor:publish --provider="Shopper\Sidebar\SidebarServiceProvider" --tag="sidebar-js" ``` This will publish the files to `resources/js/vendor/sidebar/`. ### Store API [#store-api] The sidebar store provides these properties and methods: **State properties:** | Property | Description | |---|---| | `$store.sidebar.isOpen` | Mobile: sidebar visibility | | `$store.sidebar.isCollapsed` | Desktop: collapsed state | | `$store.sidebar.collapsible` | Whether collapse is enabled | | `$store.sidebar.currentPath` | Current URL path | **Sidebar visibility (mobile):** ```javascript $store.sidebar.open() $store.sidebar.close() ``` **Sidebar collapse (desktop):** ```javascript $store.sidebar.toggle() $store.sidebar.collapse() $store.sidebar.expand() $store.sidebar.toggleCollapse() ``` **Group management:** ```javascript $store.sidebar.toggleGroup(label) $store.sidebar.isGroupCollapsed(label) $store.sidebar.collapseGroup(label) $store.sidebar.expandGroup(label) ``` **Navigation tracking (for SPA):** ```javascript $store.sidebar.isActive(url) ``` ## CSS Variables [#css-variables] Add CSS variables to your layout for sidebar dimensions: ```blade ``` ## Menu Item API [#menu-item-api] ### Basic Item Options [#basic-item-options] ```php $group->item('Label', function (Item $item): void { // URL or Route $item->setUrl('/path'); // Direct URL $item->route('route.name'); // Route name $item->route('route.name', ['id' => 1]); // Route with parameters // Icon $item->setIcon( icon: 'heroicon-o-home', type: 'blade', // 'blade' or 'svg' iconClass: 'size-5', attributes: ['stroke-width' => '1.5'], ); // Ordering $item->weight(1); // Sort order (lower = higher) // Authorization $item->setAuthorized(); // Always authorized $item->setAuthorized(auth()->user()->can('manage-users')); // Conditional // Behavior $item->useSpa(); // Use wire:navigate for Livewire $item->isNewTab(); // Open in new tab // CSS Classes $item->setItemClass('my-item-class'); $item->setActiveClass('active'); }); ``` ### Adding Badges [#adding-badges] ```php $item->badge('New'); // Simple text badge $item->badge(5); // Number badge $item->badge('3', 'bg-red-500 text-white'); // Styled badge $item->badge(function (Badge $badge): void { $badge->setValue($this->getNotificationCount()); $badge->setClass('bg-primary-500 text-white'); $badge->color('danger'); }); ``` ### Adding Append Elements [#adding-append-elements] Append elements are additional action buttons displayed next to the item. When you pass a string, `append()` reads it as a route name, then takes the icon and the name. Always give the append a CSS class with `setClass()`, since the append view renders it: ```php $item->append('users.create', 'heroicon-o-plus', 'Add User') ->setClass('hover:bg-gray-100'); $item->append(function (Append $append): void { $append->route('users.create'); $append->setIcon('heroicon-o-plus', 'blade', 'size-4'); $append->setName('Add User'); $append->setClass('hover:bg-gray-100'); }); ``` ### Sub-Items [#sub-items] ```php $item->item('Sub Item 1', function (Item $subItem): void { $subItem->route('sub.route.1'); }); $item->item('Sub Item 2', function (Item $subItem): void { $subItem->route('sub.route.2'); }); ``` ## Group API [#group-api] ```php $menu->group('Group Name', function (Group $group): void { $group->weight(1); // Sort order $group->setAuthorized(); // Authorization $group->hideHeading(); // Hide the group heading $group->collapsible(true); // Allow collapsing // CSS Classes $group->setClass('my-group-class'); $group->setHeadingClass('my-heading-class'); $group->setGroupItemsClass('space-y-1'); // Add items $group->item('Item', function (Item $item): void { // ... }); }); ``` ## Helper Functions [#helper-functions] The package provides namespaced helper functions: ```php use function Shopper\Sidebar\sidebar_config; use function Shopper\Sidebar\sidebar_width; use function Shopper\Sidebar\sidebar_collapsed_width; use function Shopper\Sidebar\sidebar_breakpoint; use function Shopper\Sidebar\sidebar_is_collapsible; $value = sidebar_config('cache.method', 'default'); $width = sidebar_width(); $collapsed = sidebar_collapsed_width(); $breakpoint = sidebar_breakpoint(); $collapsible = sidebar_is_collapsible(); // true/false ``` # Livewire Starter Kit (/2.x/livewire-starter-kit) The Livewire Starter Kit is a complete storefront for Shopper, built entirely within the Laravel ecosystem. It uses [Livewire 3](https://livewire.laravel.com/) for reactive components, [Flux UI](https://fluxui.dev) for the design system, and [Tailwind CSS v4](https://tailwindcss.com/) for styling. Because Shopper's admin panel is also built with Livewire, you can reuse patterns and components across your admin and storefront. ## Prerequisites [#prerequisites] The installer checks the PHP, Laravel and Shopper versions of the kit's manifest before it copies anything. | Requirement | Version | |-------------|---------| | PHP | 8.4+ | | Laravel | 11.48+ | | Shopper | 2.11.1+ | | Node.js | 20+ | ## Installation [#installation] The `shopper:kit:install` command is built into Shopper. No additional package is required. ```bash php artisan shopper:kit:install shopperlabs/livewire-starter-kit ``` The installer downloads the kit, reads its [manifest](/2.x/starter-kits#the-manifest), copies all storefront files into your project, and installs the following dependencies. | Package | Purpose | |---------|---------| | `livewire/flux` | UI component library (buttons, inputs, modals, cards) | | `livewire/volt` | Single-file Livewire components | | `laravel/fortify` | Authentication backend (login, register, 2FA) | | `shopper/stripe` | Stripe payment integration | | `laravel/boost` | Development dependency for AI-assisted development | After installing dependencies, the kit runs its post-install commands: `php artisan migrate` and `php artisan storage:link`. Once complete, the kit package is removed from your `composer.json`. The code is yours. The post-install commands do not build the frontend assets. Install the npm packages and build them once the installer finishes: ```bash npm install npm run build ``` On an existing project, create a new branch before installing so you can review every change. ```bash git checkout -b storefront php artisan shopper:kit:install shopperlabs/livewire-starter-kit ``` ## Project Structure [#project-structure] The starter kit publishes files into standard Laravel directories. Here is the full structure. ```text app/ ├── Actions/ │ ├── Cart/ │ │ └── AddToCart.php │ ├── Checkout/ │ │ ├── BuildShippingPackages.php │ │ ├── FetchDeliveryRates.php │ │ ├── FetchPaymentMethods.php │ │ └── ResolveZoneForCountry.php │ ├── Fortify/ │ │ ├── CreateNewUser.php │ │ └── ResetUserPassword.php │ ├── Product/ │ │ ├── AddProductReviewAction.php │ │ ├── BuildVariantOptions.php │ │ └── ResolveVariantAvailability.php │ ├── CreateOrder.php │ ├── GetCountriesByZone.php │ └── ZoneSessionManager.php ├── Concerns/ │ ├── PasswordValidationRules.php │ └── ProfileValidationRules.php ├── DTO/ │ ├── AddressData.php │ ├── CountryByZoneData.php │ ├── PriceData.php │ └── ProductReviewsData.php ├── Http/Controllers/ │ ├── StripeReturnController.php │ └── StripeWebhookController.php ├── Livewire/ │ ├── Account/ │ │ ├── AddressForm.php │ │ └── Addresses.php │ ├── Actions/ │ │ └── Logout.php │ ├── Home/ │ │ ├── FeaturedCollections.php │ │ ├── FeaturedProducts.php │ │ └── ShopByCategory.php │ ├── Pages/ │ │ ├── Cart.php │ │ ├── CategoryIndex.php │ │ ├── CategoryShow.php │ │ ├── Checkout.php │ │ ├── CollectionShow.php │ │ ├── Home.php │ │ ├── ProductIndex.php │ │ ├── ProductShow.php │ │ ├── SearchProducts.php │ │ └── StripePayment.php │ ├── CartCount.php │ ├── StoreFooter.php │ ├── StoreHeader.php │ └── ZoneSelector.php ├── Models/ │ ├── Category.php │ ├── Channel.php │ ├── Product.php │ ├── ProductVariant.php │ └── User.php ├── Providers/ │ ├── AppServiceProvider.php │ ├── FortifyServiceProvider.php │ └── VoltServiceProvider.php ├── Traits/ │ └── HasProductPricing.php ├── CheckoutSession.php └── helpers.php resources/views/ ├── components/ # Blade components (product cards, price display, badges) ├── layouts/ # Store, account, and auth layouts ├── livewire/ # Livewire component views (header, footer, cart count) ├── pages/ │ ├── auth/ # Login, register, password reset, 2FA │ ├── home/ # Homepage sections (collections, products, categories) │ ├── settings/ # Profile, appearance, security │ ├── shop/ # Product listing, detail, cart, checkout │ └── account/ # Order history, order detail └── partials/ # Shared head, settings heading routes/ ├── web.php # Storefront, checkout, account routes └── settings.php # Profile and security routes tests/ ├── Feature/Auth/ # Authentication tests └── Feature/Settings/ # Profile and security tests ``` ## Routing [#routing] The starter kit defines all storefront routes in `routes/web.php`. Each page is a full-page Livewire component. ### Public Routes [#public-routes] These routes are open to guests. | Route | Component | Description | |-------|-----------|-------------| | `/` | `Home` | Homepage with featured collections, products, and categories | | `/shop` | `ProductIndex` | Product catalog with search and filtering | | `/shop/{product:slug}` | `ProductShow` | Product detail with variant selection | | `/categories` | `CategoryIndex` | All categories | | `/categories/{category:slug}` | `CategoryShow` | Products in a category | | `/collections/{collection:slug}` | `CollectionShow` | Products in a collection | | `/search` | `SearchProducts` | Full-text search across products | | `/cart` | `Cart` | Shopping cart | ### Authenticated Routes [#authenticated-routes] These routes require the user to be logged in and have a verified email. The `/profile/edit` route only requires the user to be logged in. | Route | Component | Description | |-------|-----------|-------------| | `/checkout` | `Checkout` | Multi-step checkout flow | | `/checkout/payment` | `StripePayment` | Stripe Payment Element | | `/checkout/payment/return` | `StripeReturnController` | Creates the order once Stripe confirms the payment | | `/checkout/success/{order}` | Volt page | Order confirmation | | `/dashboard` | Blade view | Customer dashboard with links to orders and addresses | | `/account/orders` | Volt page | Order history | | `/account/orders/{order}` | Volt page | Order detail | | `/account/addresses` | `Addresses` | Address management | | `/profile/edit` | Volt page | Profile settings | | `/profile/appearance` | Volt page | Dark mode / appearance | | `/profile/security` | Volt page | Password and two-factor authentication | The Stripe webhook endpoint is registered at `/webhooks/stripe` with rate limiting. ## Architecture [#architecture] The starter kit follows a clear separation of concerns. Business logic lives in Action classes, data structures in DTOs, and UI in Livewire components. This makes it straightforward to modify any part of the storefront without affecting others. ### Actions [#actions] Actions are single-responsibility classes that encapsulate business logic. They are resolved from the container, so you can swap implementations or add dependencies as needed. ```php use App\Actions\Cart\AddToCart; use App\Actions\Checkout\FetchDeliveryRates; use App\Actions\CreateOrder; resolve(AddToCart::class)->handle($product, $selectedVariant); resolve(FetchDeliveryRates::class)->handle($addressData, $packages); resolve(CreateOrder::class)->handle(); ``` The checkout flow is split into four focused actions. | Action | Responsibility | |--------|---------------| | `BuildShippingPackages` | Builds package dimensions from cart items for carrier rate requests | | `FetchDeliveryRates` | Queries available carriers and returns shipping rate options | | `FetchPaymentMethods` | Loads payment methods available for the customer's country | | `ResolveZoneForCountry` | Resolves the pricing zone for a given country with caching | ### DTOs [#dtos] Data Transfer Objects provide type-safe structures for data passed between components. | DTO | Purpose | |-----|---------| | `AddressData` | Structured address data for forms and checkout | | `CountryByZoneData` | Zone session data (zone ID, country code, currency code) | | `PriceData` | Formatted price with amount, currency, and comparison price | | `ProductReviewsData` | Aggregated review data (reviews, average rating, total count) | ### Models [#models] The starter kit publishes model files that extend Shopper's base models. These are configured in `config/shopper/models.php` so that Shopper's internals use your extended versions. ```php title="app/Models/Product.php" namespace App\Models; use App\Traits\HasProductPricing; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; } ``` You can add custom logic directly to these models. Any method you add is available throughout the storefront and in Shopper's admin panel. ### CheckoutSession [#checkoutsession] The `CheckoutSession` class defines constants for session keys used throughout the checkout flow. This provides a single place to reference all checkout-related session data. ```php use App\CheckoutSession; session()->get(CheckoutSession::KEY); // 'checkout' session()->get(CheckoutSession::SHIPPING_ADDRESS); // 'checkout.shipping_address' session()->get(CheckoutSession::SHIPPING_OPTION); // 'checkout.shipping_option' session()->get(CheckoutSession::PAYMENT); // 'checkout.payment' ``` ### Helpers [#helpers] The `app/helpers.php` file defines three global functions used across the storefront. | Function | Purpose | |----------|---------| | `cartSession()` | Returns the current cart or creates a new one with the active zone, currency, and channel | | `current_currency()` | Returns the currency code for the selected zone, or the store default | | `current_tax_label()` | Returns the tax label ("TTC" or "HT") from the tax zone of the selected country, or an empty string when no zone is selected | ## Checkout Flow [#checkout-flow] The checkout is a multi-step process handled by the `Checkout` Livewire component. Each step validates its data before proceeding to the next. **Step 1 - Shipping Address.** The customer enters a new address or selects one of their saved addresses. The address is stored in the session and attached to the cart via `CartManager::addAddress()`. **Step 2 - Delivery Options.** The `BuildShippingPackages` action builds package data from the cart, then `FetchDeliveryRates` queries configured [carriers](/2.x/carriers) for available shipping rates based on the address and packages. The customer selects a delivery option. **Step 3 - Payment.** `FetchPaymentMethods` loads available [payment methods](/2.x/payments) for the customer's country. When the customer places the order with a manual payment method, the `CreateOrder` action converts the cart into an order inside a database transaction, adds shipping costs, and initiates payment processing through Shopper's `PaymentProcessingService`. For Stripe payments, the order does not exist yet when the customer leaves the checkout. The checkout creates a Stripe PaymentIntent for the cart total plus shipping and redirects to a dedicated payment page (`StripePayment`) that renders the Stripe Payment Element. Once Stripe confirms the payment, the `StripeReturnController` checks the PaymentIntent status, creates the order with the `CreateOrder` action, and redirects to the confirmation page. The `StripeWebhookController` then updates the order's payment status from Stripe events. ## Zones and Currency [#zones-and-currency] The starter kit uses Shopper's [zone system](/2.x/zones) for multi-currency and regional pricing. The `ZoneSelector` component in the footer lets customers pick their country. When a zone is selected, the `ZoneSessionManager` stores a `CountryByZoneData` DTO in the session with the zone ID, country code, and currency code. All prices across the storefront update to reflect the zone's currency. If no zone is selected, the storefront falls back to the default currency set in your store settings, returned by `shopper_currency()`. The `current_tax_label()` helper reads the tax zone of the selected country to display "TTC" (tax-inclusive) or "HT" (tax-exclusive) labels alongside prices. To enable zone selection, create at least one active zone in your Shopper admin panel. When your zones cover a single country, the `ZoneSelector` selects it automatically on the first visit. ## Customization [#customization] Once installed, every file belongs to your project. Here are the most common customization paths. ### Styling [#styling] All views use Flux UI components and Tailwind CSS v4. Modify colors, spacing, and layouts by editing the Blade templates in `resources/views/`. The base layout is in `resources/views/layouts/store.blade.php`. ### Homepage Sections [#homepage-sections] The homepage is composed of three independent Livewire components, each with its own view. | Component | View | What it shows | |-----------|------|---------------| | `FeaturedCollections` | `pages/home/featured-collections.blade.php` | The three collections with the most products | | `FeaturedProducts` | `pages/home/featured-products.blade.php` | Up to eight published products marked as featured | | `ShopByCategory` | `pages/home/shop-by-category.blade.php` | Root categories | Remove or reorder these components in `resources/views/pages/home.blade.php` to change the homepage layout. ### Checkout [#checkout] To modify the checkout flow, edit the action classes in `app/Actions/Checkout/`. Each action handles one concern, so you can change how shipping rates are calculated without touching payment logic. To add a new payment provider, implement the provider using Shopper's [payment system](/2.x/payments) and register it in your admin panel. The checkout will automatically pick it up through `FetchPaymentMethods`. ### Adding Pages [#adding-pages] Create a new Livewire component and register a route in `routes/web.php`. Follow the existing pattern of full-page components in `app/Livewire/Pages/`. ```php title="app/Livewire/Pages/About.php" namespace App\Livewire\Pages; use Illuminate\Contracts\View\View; use Livewire\Component; class About extends Component { public function render(): View { return view('pages.about') ->title('About Us'); } } ``` ```php title="routes/web.php" use App\Livewire\Pages\About; Route::get('about', About::class)->name('about'); ``` ### Models [#models-1] Add methods, scopes, or relationships directly to the model files in `app/Models/`. These models extend Shopper's base models, so all existing functionality is preserved. ```php title="app/Models/Product.php" namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Shopper\Models\Product as Model; final class Product extends Model { public function scopeFeatured(Builder $query): Builder { return $query->where('featured', true); } } ``` # React Starter Kit (/2.x/react-starter-kit) The React Starter Kit is a complete storefront for Shopper, built with [Inertia.js](https://inertiajs.com/) and [React 19](https://react.dev/). It keeps the full power of Laravel on the backend, with no separate API layer to maintain, while delivering a modern single-page application experience on the frontend. The design system uses [shadcn/ui](https://ui.shadcn.com/) components and [Tailwind CSS v4](https://tailwindcss.com/), and every route is fully type-safe thanks to [Laravel Wayfinder](https://github.com/laravel/wayfinder) and a PHP-to-TypeScript transformer. ## Prerequisites [#prerequisites] The kit's manifest requires these PHP, Laravel and Shopper versions, and its Vite version needs the Node.js versions below. | Requirement | Version | |-------------|---------| | PHP | 8.4+ | | Laravel | 12.0+ | | Shopper | 2.11+ | | Node.js | 20.19+ or 22.12+ | ## Installation [#installation] The `shopper:kit:install` command is built into Shopper. No additional package is required. ```bash php artisan shopper:kit:install shopperlabs/react-starter-kit ``` The installer downloads the kit, reads its [manifest](/2.x/starter-kits#the-manifest), copies all storefront files into your project, and installs the following dependencies. | Package | Purpose | |---------|---------| | `inertiajs/inertia-laravel` | Inertia server-side adapter for Laravel | | `laravel/fortify` | Authentication backend (login, register, 2FA) | | `laravel/wayfinder` | Typed route helpers generated from your routes | | `spatie/laravel-typescript-transformer` | Generates TypeScript types from PHP DTOs and enums | | `shopper/stripe` | Stripe payment integration | It also installs `laravel/boost` and `laravel/pao` as development dependencies. After installing dependencies, the kit runs its post-install commands: database migrations, storage symlink creation, npm install, and the frontend asset build. Once complete, the kit package is removed from your `composer.json`. The code is yours. On an existing project, create a new branch before installing so you can review every change. ```bash git checkout -b storefront php artisan shopper:kit:install shopperlabs/react-starter-kit ``` ## Project Structure [#project-structure] The starter kit publishes files into standard Laravel directories. The backend is shared with the [Vue Starter Kit](/2.x/vue-starter-kit); only the `resources/js` frontend differs. Here is the full structure. ```text app/ ├── Actions/ │ ├── Cart/ │ │ └── AddToCart.php │ ├── Checkout/ │ │ ├── BuildShippingPackages.php │ │ ├── FetchDeliveryRates.php │ │ ├── FetchPaymentMethods.php │ │ └── ResolveZoneForCountry.php │ ├── Fortify/ │ │ ├── CreateNewUser.php │ │ └── ResetUserPassword.php │ ├── Product/ │ │ ├── AddProductReviewAction.php │ │ ├── BuildVariantOptions.php │ │ └── ResolveVariantAvailability.php │ ├── CreateOrder.php │ ├── GetCountriesByZone.php │ └── ZoneSessionManager.php ├── Concerns/ │ ├── InteractsWithStorefrontMedia.php │ ├── PasswordValidationRules.php │ └── ProfileValidationRules.php ├── DTO/ │ ├── AddressData.php │ ├── CountryByZoneData.php │ ├── PriceData.php │ └── ProductReviewsData.php ├── Http/ │ ├── Controllers/ │ │ ├── Account/ # Address and order management │ │ ├── Settings/ # Profile and security │ │ ├── Shop/ # Home, products, cart, checkout, zone │ │ └── StripeWebhookController.php │ ├── Middleware/ │ │ ├── HandleAppearance.php │ │ └── HandleInertiaRequests.php │ └── Requests/Settings/ # Profile and password form requests ├── Models/ │ ├── Category.php │ ├── Channel.php │ ├── Collection.php │ ├── Product.php │ ├── ProductVariant.php │ └── User.php ├── Providers/ │ ├── AppServiceProvider.php │ ├── FortifyServiceProvider.php │ └── TypeScriptTransformerServiceProvider.php ├── Traits/ │ └── HasProductPricing.php ├── CheckoutSession.php └── helpers.php resources/js/ ├── components/ │ ├── account/ # Order status badge │ ├── shop/ # Product cards, price display, zone selector, Stripe form │ └── ui/ # shadcn/ui primitives (button, dialog, select, ...) ├── hooks/ # useCart, useShop, useStripeElements, useAppearance ├── layouts/ # Storefront, account, settings, and auth layouts ├── lib/ # format, stripe, and utility helpers ├── pages/ │ ├── account/ # Orders, order detail, addresses │ ├── auth/ # Login, register, password reset, 2FA │ ├── settings/ # Profile, appearance, security │ └── shop/ # Home, catalog, product, cart, checkout ├── types/ # Shared and generated TypeScript types └── app.tsx # Inertia application entry point routes/ ├── web.php # Storefront, checkout, account routes └── settings.php # Profile and security routes tests/ ├── Feature/Auth/ # Authentication tests └── Feature/Settings/ # Profile and security tests ``` ## Routing [#routing] The starter kit defines all storefront routes in `routes/web.php`. Unlike the Livewire kit, each page is rendered by a dedicated controller that returns an Inertia response. Routes are named so you can reference them through Wayfinder in your React components. ### Public Routes [#public-routes] These routes are open to guests. | Route | Controller | Description | |-------|-----------|-------------| | `GET /` | `Shop\HomeController` | Homepage with featured collections, products, and categories | | `GET /shop` | `Shop\ProductController@index` | Product catalog with search and filtering | | `GET /shop/{product:slug}` | `Shop\ProductController@show` | Product detail with variant selection | | `GET /categories` | `Shop\CategoryController@index` | All categories | | `GET /categories/{category:slug}` | `Shop\CategoryController@show` | Products in a category | | `GET /collections/{collection:slug}` | `Shop\CollectionController@show` | Products in a collection | | `GET /search` | `Shop\SearchController` | Product search by name | | `GET /cart` | `Shop\CartController@index` | Shopping cart | Cart mutations are exposed as their own throttled endpoints: `POST /cart` adds a line, `PATCH /cart/{line}` updates a quantity, `DELETE /cart/{line}` removes a line, and `DELETE /cart` clears the cart. The active pricing zone is changed with `PATCH /zone`. ### Authenticated Routes [#authenticated-routes] These routes use the `auth` and `verified` middleware, except the profile page (`GET` and `PATCH /settings/profile`), which only requires a login. The `verified` middleware blocks unverified customers only when your `User` model implements Laravel's `MustVerifyEmail` contract, which the kit's model does not. | Route | Controller | Description | |-------|-----------|-------------| | `GET /checkout` | `Shop\CheckoutController@index` | Multi-step checkout flow | | `GET /checkout/payment/{number}` | `Shop\StripePaymentController` | Stripe Payment Element | | `GET /checkout/success/{order}` | `Shop\CheckoutSuccessController` | Order confirmation | | `GET /account/orders` | `Account\OrderController@index` | Order history | | `GET /account/orders/{order}` | `Account\OrderController@show` | Order detail | | `GET /account/addresses` | `Account\AddressController@index` | Address management | | `GET /settings/profile` | `Settings\ProfileController@edit` | Profile settings | | `GET /settings/appearance` | Inertia page | Dark mode / appearance | | `GET /settings/security` | `Settings\SecurityController@edit` | Password and two-factor authentication | The checkout flow posts to dedicated endpoints for each step (`checkout/shipping-address`, `checkout/shipping-option`, `checkout/prepare-payment`, `checkout/place-order`). The Stripe webhook endpoint is registered at `/webhooks/stripe` with rate limiting. ## Architecture [#architecture] The starter kit follows a clear separation of concerns. Business logic lives in Action classes, data structures in DTOs, HTTP handling in controllers, and UI in React components. This makes it straightforward to modify any part of the storefront without affecting others. ### Actions [#actions] Actions are single-responsibility classes that encapsulate business logic. They are resolved from the container, so you can swap implementations or add dependencies as needed. ```php use App\Actions\Cart\AddToCart; use App\Actions\Checkout\FetchDeliveryRates; use App\Actions\CreateOrder; resolve(AddToCart::class)->handle($product, $selectedVariant); resolve(FetchDeliveryRates::class)->handle($addressData, $packages); resolve(CreateOrder::class)->handle(); ``` The checkout flow is split into four focused actions. | Action | Responsibility | |--------|---------------| | `BuildShippingPackages` | Builds package dimensions from cart items for carrier rate requests | | `FetchDeliveryRates` | Queries available carriers and returns shipping rate options | | `FetchPaymentMethods` | Loads payment methods available for the customer's country | | `ResolveZoneForCountry` | Resolves the pricing zone for a given country with caching | Order creation is wrapped in `CreateOrder`, which uses `Cache::lock` for idempotency and verifies cart ownership before converting the cart into an order. ### DTOs [#dtos] Data Transfer Objects provide type-safe structures for data passed between the backend and the React frontend. Because the kit uses the TypeScript Transformer, these DTOs also become TypeScript types your components can import. | DTO | Purpose | |-----|---------| | `AddressData` | Structured address data for forms and checkout | | `CountryByZoneData` | Zone session data (zone ID, country code, currency code) | | `PriceData` | Current price, compare-at price, and discount percentage | | `ProductReviewsData` | Product reviews with the average rating and the review count | ### Controllers [#controllers] Each storefront page is rendered by a controller in `app/Http/Controllers/`. Controllers query Shopper's models, wrap data in DTOs, and return an Inertia response that renders the matching page component. ```php use App\Models\Product; use Inertia\Inertia; use Inertia\Response; public function show(Product $product): Response { return Inertia::render('shop/product', [ 'product' => $product->load('variants', 'media'), ]); } ``` To change what a page receives, edit its controller. To change how it looks, edit the matching page component in `resources/js/pages/`. ### Inertia Shared Data [#inertia-shared-data] The `HandleInertiaRequests` middleware shares global data with every page, so your components always have access to the authenticated user and the current shop state without re-fetching it. The `shop` prop carries the cart count, the selected zone, the active currency, available channels and zones, the tax label, and navigation categories. ```php 'shop' => fn (): array => [ 'cart_count' => $cart?->lines->sum('quantity') ?? 0, 'zone' => $zone, 'currency' => current_currency(), 'tax_label' => current_tax_label(), // navigation categories, channels, available zones ... ], ``` On the frontend, the `useShop` hook reads this shared data, including the cart count, and `useCart` exposes the cart mutations: `add`, `update`, `remove`, and `clear`. ### Models [#models] The starter kit publishes model files that extend Shopper's base models. These are configured in `config/shopper/models.php` so that Shopper's internals use your extended versions. ```php title="app/Models/Product.php" namespace App\Models; use App\Concerns\InteractsWithStorefrontMedia; use App\Traits\HasProductPricing; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; use InteractsWithStorefrontMedia; } ``` You can add custom logic directly to these models. Any method you add is available throughout the storefront and in Shopper's admin panel. The `InteractsWithStorefrontMedia` trait appends `thumbnail` and `images` attributes to every JSON response, so your React components receive ready-to-use media URLs. ### CheckoutSession [#checkoutsession] The `CheckoutSession` class defines constants for the session keys that hold the customer's checkout choices: addresses, delivery option, and payment method. ```php use App\CheckoutSession; session()->get(CheckoutSession::KEY); // 'checkout' session()->get(CheckoutSession::SHIPPING_ADDRESS); // 'checkout.shipping_address' session()->get(CheckoutSession::BILLING_ADDRESS); // 'checkout.billing_address' session()->get(CheckoutSession::SAME_AS_SHIPPING); // 'checkout.same_as_shipping' session()->get(CheckoutSession::SHIPPING_OPTION); // 'checkout.shipping_option' session()->get(CheckoutSession::PAYMENT); // 'checkout.payment' ``` ### Helpers [#helpers] The `app/helpers.php` file defines three global functions used across the storefront. | Function | Purpose | |----------|---------| | `cartSession()` | Returns the current cart or creates a new one with the active zone, currency, and channel | | `current_currency()` | Returns the currency code for the selected zone, or the store default from `shopper_currency()` | | `current_tax_label()` | Returns the tax label ("TTC" or "HT") from the tax zone of the selected country, or an empty string when no zone is selected | ### Type Safety [#type-safety] This kit is type-safe end to end. Three tools work together so your React components never guess at the shape of backend data. | Tool | What it provides | |------|------------------| | Wayfinder | Typed route helpers generated from `routes/web.php`, so `shop.product` becomes an importable function | | TypeScript Transformer | Generates TypeScript definitions from your PHP DTOs and enums into `resources/js/types` | | `@shopperlabs/shopper-types` | Shared domain types (Address, Cart, Order, Product, and enums) published as an npm package | The `TypeScriptTransformerServiceProvider` registers the transformer and writes the types to `resources/js/types/generated.d.ts`. Run `php artisan typescript:transform` after changing a DTO to refresh the TypeScript types your components import. ## Checkout Flow [#checkout-flow] The checkout is a multi-step process handled by `CheckoutController`. Each step posts to its own endpoint and validates its data before proceeding to the next. **Step 1 - Shipping Address.** The customer enters a new address or selects one of their saved addresses. The address is stored in the session and attached to the cart via `CartManager::addAddress()`. **Step 2 - Delivery Options.** The `BuildShippingPackages` action builds package data from the cart, then `FetchDeliveryRates` queries configured [carriers](/2.x/carriers) for available shipping rates based on the address and packages. The customer selects a delivery option. **Step 3 - Payment.** `FetchPaymentMethods` loads available [payment methods](/2.x/payments) for the customer's country. For a manual method such as cash on delivery, placing the order runs the `CreateOrder` action, which converts the cart into an order inside a database transaction and adds the shipping cost. The controller then initiates payment processing through Shopper's `PaymentProcessingService`. When the customer selects Stripe, the checkout creates a Stripe PaymentIntent before any order exists and renders the Stripe Payment Element on the payment step, through the `StripePaymentForm` component and the `useStripeElements` hook. Once the payment is confirmed, Stripe sends the customer back to `checkout/stripe-return`, where the kit checks the PaymentIntent and only then creates the order. The `StripeWebhookController` checks the webhook signature and updates the order's payment status when Stripe reports a payment as authorized, captured, failed, canceled, or refunded. ## Zones and Currency [#zones-and-currency] The starter kit uses Shopper's [zone system](/2.x/zones) for multi-currency and regional pricing. The `ZoneSelector` component in the footer lets customers pick their country. When a customer picks a country, the `ZoneSessionManager` stores its country code in the session and resolves it on each request into a `CountryByZoneData` DTO with the zone, the country, and the currency code. All prices across the storefront update to reflect the zone's currency through the shared `shop` prop. If no zone is selected, the storefront falls back to your store's default currency from `shopper_currency()`. The `current_tax_label()` helper reads the tax zone of the selected country to display "TTC" (tax-inclusive) or "HT" (tax-exclusive) labels alongside prices. To enable zone selection, create at least one active zone in your Shopper admin panel. ## Customization [#customization] Once installed, every file belongs to your project. Here are the most common customization paths. ### Styling [#styling] All views use shadcn/ui components and Tailwind CSS v4. Modify colors, spacing, and layouts by editing the components in `resources/js`. UI primitives live in `resources/js/components/ui/`, and the storefront chrome is in `resources/js/layouts/storefront/`. ### Pages [#pages] Each page is a React component in `resources/js/pages/`. Edit any `.tsx` file to change a page's layout or content. To change the data a page receives, edit its controller in `app/Http/Controllers/`. ### Checkout [#checkout] To modify the checkout flow, edit the action classes in `app/Actions/Checkout/`. Each action handles one concern, so you can change how shipping rates are calculated without touching payment logic. To add a new payment provider, implement the provider using Shopper's [payment system](/2.x/payments), then add the payment method in your admin panel and enable it on your zones. The checkout will automatically pick it up through `FetchPaymentMethods`. ### Adding Pages [#adding-pages] Create a controller, register a named route in `routes/web.php`, and add the matching React component under `resources/js/pages/`. The layout is picked from the page name in `resources/js/app.tsx`: pages under `shop/` get the storefront header and footer. ```php title="app/Http/Controllers/Shop/AboutController.php" namespace App\Http\Controllers\Shop; use App\Http\Controllers\Controller; use Inertia\Inertia; use Inertia\Response; final class AboutController extends Controller { public function __invoke(): Response { return Inertia::render('shop/about'); } } ``` ```php title="routes/web.php" use App\Http\Controllers\Shop\AboutController; Route::get('about', AboutController::class)->name('shop.about'); ``` ```tsx title="resources/js/pages/shop/about.tsx" export default function About() { return

    About Us

    ; } ``` ### Models [#models-1] Add methods, scopes, or relationships directly to the model files in `app/Models/`. These models extend Shopper's base models, so all existing functionality is preserved. ```php use Illuminate\Database\Eloquent\Builder; class Product extends Shopper\Models\Product { public function scopeFeatured(Builder $query): Builder { return $query->where('featured', true); } } ``` # Starter Kits (/2.x/starter-kits) Shopper is a headless e-commerce framework. It ships without a frontend, giving you full control over how customers interact with your store. You can build your storefront with any technology: React, Vue, Svelte, or server-rendered Blade. If you want to skip the blank canvas and start from a working storefront, Shopper provides **Starter Kits**. Each kit is a complete storefront that gets copied directly into your Laravel application. Once installed, the code belongs to you. Modify anything, delete what you don't need, or use it as a reference to build something entirely different. ## Starter Kits vs Themes [#starter-kits-vs-themes] Starter kits are not themes. The distinction matters. A theme is a runtime dependency. Your application relies on it, receives updates from it, and can switch between themes. A starter kit is scaffolding used once: the installer copies files into your project, installs dependencies, and removes itself. There is no hidden package to update, no active dependency at runtime. If you want to "switch" starter kits, you start a new project. This is by design. The trade-off is intentional: you get full ownership and freedom to customize every line of code, at the cost of not being able to swap frontends with a click. ```text Starter Kit Theme (out of scope) -------------------------------- -------------------------------- Scaffold, used once Runtime, active permanently Code belongs to the developer Managed by the system Not switchable Switchable from admin Manual merge for updates Update = dependency upgrade ``` ## Scope [#scope] Shopper starter kits cover **Laravel storefronts** only: Laravel + Livewire and Laravel + Inertia.js (Vue or React within the Laravel context). Projects outside of Laravel (standalone Vue/React SPAs, Svelte, mobile apps) talk to Shopper through an API you expose from your Laravel application, and are distributed through their own channels (GitHub, ThemeForest, Gumroad, etc.). These are not in scope for the starter kit system. ## Available Kits [#available-kits] ### Livewire [#livewire] The [Livewire Starter Kit](/2.x/livewire-starter-kit) is a full-stack Laravel storefront built with [Livewire](https://livewire.laravel.com/), [Flux UI](https://fluxui.dev) and [Tailwind CSS](https://tailwindcss.com/). It provides reactive components for product browsing, cart management, multi-step checkout with Stripe payment, customer accounts, and multi-currency zone support. Because Shopper's admin panel is also built with Livewire, you can reuse patterns and components across your admin and storefront. ### React [#react] The [React Starter Kit](/2.x/react-starter-kit) is an [Inertia.js](https://inertiajs.com/) storefront built with [React](https://react.dev/), [shadcn/ui](https://ui.shadcn.com/) and [Tailwind CSS](https://tailwindcss.com/). It keeps the full power of Laravel on the backend with no separate API layer, and is type-safe end to end through [Wayfinder](https://github.com/laravel/wayfinder) routes and a PHP-to-TypeScript transformer. ### Vue [#vue] The [Vue Starter Kit](/2.x/vue-starter-kit) is an [Inertia.js](https://inertiajs.com/) storefront built with [Vue](https://vuejs.org/), [shadcn-vue](https://www.shadcn-vue.com/) and [Tailwind CSS](https://tailwindcss.com/). It shares the same Laravel backend as the React kit, so the only difference is the frontend layer. The React and Vue kits share the same backend (controllers, actions, DTOs, models, and routes). Choose the kit that matches your frontend stack; everything you read about one applies to the other. ## How It Works [#how-it-works] The `shopper:kit:install` command is built into Shopper. No additional package is required. When you run it with a kit package name, the installer performs the following pipeline: 1. **Backup** your `composer.json` for rollback if anything fails 2. **Detect** the kit package on Packagist, GitHub, Bitbucket, or GitLab 3. **Download** the kit temporarily via `composer require` 4. **Read** the `shopper-kit.yaml` manifest from the kit package 5. **Validate** PHP, Laravel, and Shopper version constraints 6. **Copy** files from the kit into your project according to `export_paths` 7. **Install** Composer dependencies declared in the manifest 8. **Run** post-install commands (migrations, storage link, asset build), after you confirm them 9. **Write** a `.shopper-kit` state file tracking installed files with SHA-256 hashes 10. **Remove** the kit package, and the repository entry added in step 2, from your `composer.json` 11. **Clean up** the backup file After installation, every file lives in your project. The kit package is gone from your dependencies. The command accepts four options: | Option | Description | |--------|-------------| | `--force` | Skip every confirmation: overwrite existing files, run the post-install commands, and continue when a version constraint is not met | | `--path=` | Copy the kit files, run the post-install commands and write the state file in another directory than the project root | | `--no-deps` | Skip the Composer dependencies declared in the manifest | | `--no-post-install` | Skip the post-install commands | ## The Manifest [#the-manifest] Every starter kit contains a `shopper-kit.yaml` manifest at its root. This file declares everything the installer needs: metadata, version constraints, which files to copy, which dependencies to install, and what commands to run after installation. ```yaml name: "My Storefront" description: "A modern storefront for Shopper." version: "1.0.0" author: "acme" url: "https://github.com/acme/my-storefront" shopper: "^2.7" php: "^8.4" laravel: "^12.0" export_paths: - resources/views - resources/css - routes/web.php - app/Livewire dependencies: - livewire/livewire: "^3.7" dev_dependencies: [] post_install: - php artisan migrate - npm install && npm run build ``` | Field | Required | Description | |-------|----------|-------------| | `name` | Yes | Display name of the kit | | `export_paths` | Yes | Files and directories to copy into the project | | `description` | No | Short description | | `version` | No | Semantic version (defaults to `0.0.0`) | | `author` | No | Author name | | `url` | No | Kit repository URL | | `php` | No | PHP version constraint (defaults to `*`) | | `laravel` | No | Laravel version constraint (defaults to `*`) | | `shopper` | No | Shopper version constraint (defaults to `*`) | | `dependencies` | No | Composer packages to install | | `dev_dependencies` | No | Composer dev packages to install | | `post_install` | No | Shell commands to run after file copy | | `stack` | No | Technologies the kit is built with (`livewire`, `inertia`, `react`, `vue`, `blade`, `alpinejs`...), shown on kit listings | | `preview` | No | URL of a live demo | | `docs` | No | URL of the kit documentation | | `screenshots` | No | Image paths in the kit, or URLs, shown on kit listings | The installer blocks certain paths for security: `.env` and `.env.*`, `composer.json`, `composer.lock`, `vendor/`, `.git/`, and `node_modules/` are never copied, even if listed in `export_paths`. Paths containing `..` or starting with `/` are skipped too. ## The `.shopper-kit` State File [#the-shopper-kit-state-file] After installation, a `.shopper-kit` file is created at the root of your project. It records which kit was installed, its version, and the SHA-256 hash of every copied file. ```json { "kit": "shopperlabs/livewire-starter-kit", "version": "1.2.0", "installed_at": "2026-04-06T14:32:00+00:00", "files": { "app/Livewire/Pages/Home.php": "3f1c9b0e7d4a5c2e8b6f0a1d9e7c5b3a2f4e6d8c0b1a3f5e7d9c2b4a6e8f0d1c", "resources/views/pages/home.blade.php": "9a2e4c6b8d0f1e3a5c7b9d2f4e6a8c0b1d3f5e7a9c2b4d6f8e0a1c3b5d7f9e2a" } } ``` Commit this file. When you run `shopper:kit:install` again in the same project, the installer reads it and asks before installing over the existing kit. The hashes record each file as the kit shipped it, so you can tell later which files you changed. ## Creating Your Own Starter Kit [#creating-your-own-starter-kit] A starter kit is built from a working Laravel application: you develop the storefront in a project that runs Shopper, then export the files the kit should ship. Shopper provides a scaffolding command to create the kit directory with the correct structure. ```bash php artisan shopper:kit:init ``` The command prompts you for the kit name, package name (in `vendor/name` format), description, author and stack. It then creates a directory named after the package, at the root of your project, with three files: ```text my-starter-kit/ ├── shopper-kit.yaml # Manifest. Configure export_paths and dependencies ├── composer.json # Package name, description, license and author └── README.md # Installation instructions ``` The generated manifest exports `resources/views`, `resources/css`, `resources/js` and `routes`. Edit `export_paths` to list the files your storefront needs, and `dependencies` to list the Composer packages it requires. You can specify a custom directory for the kit with the `--path` option. ```bash php artisan shopper:kit:init --path=../my-starter-kit ``` When the storefront is ready, copy its files into the kit with `shopper:kit:export`. The command reads the kit's `shopper-kit.yaml`, copies every path of `export_paths` from your project into the kit, and replaces each dependency version with the constraint your project's `composer.json` requires. ```bash php artisan shopper:kit:export my-starter-kit ``` Run it with `--clear` to empty the kit directory first, so files you deleted from the project leave the kit too. The `.git` and `.github` directories, `README.md`, `CHANGELOG.md`, `LICENSE`, `composer.json` and the manifest are kept. Publish the kit on Packagist or a public Git repository on GitHub, GitLab or Bitbucket, and anyone can install it with `shopper:kit:install`. # Vue Starter Kit (/2.x/vue-starter-kit) The Vue Starter Kit is a storefront for Shopper built with [Inertia.js](https://inertiajs.com/) and [Vue 3](https://vuejs.org/). Laravel controllers query the Shopper models and pass the data to Vue pages as Inertia props, so there is no separate API layer to maintain, and Inertia navigates between pages without full reloads. The interface uses [shadcn-vue](https://www.shadcn-vue.com/) components and [Tailwind CSS v4](https://tailwindcss.com/), and [Laravel Wayfinder](https://github.com/laravel/wayfinder) and a PHP-to-TypeScript transformer give the pages typed routes and typed data. ## Prerequisites [#prerequisites] | Requirement | Version | |-------------|---------| | PHP | 8.4+ | | Laravel | 12.0+ | | Shopper | 2.11+ | | Node.js | 20.19+ or 22.12+ | ## Installation [#installation] The `shopper:kit:install` command is built into Shopper. No additional package is required. ```bash php artisan shopper:kit:install shopperlabs/vue-starter-kit ``` The installer downloads the kit, reads its [manifest](/2.x/starter-kits#the-manifest) and copies the storefront files into your project, asking before it overwrites each file your application already has. It then installs the following dependencies. | Package | Purpose | |---------|---------| | `inertiajs/inertia-laravel` | Inertia server-side adapter for Laravel | | `laravel/fortify` | Authentication backend (login, register, 2FA) | | `laravel/wayfinder` | Typed route helpers generated from your routes | | `spatie/laravel-typescript-transformer` | Generates TypeScript types from PHP DTOs and enums | | `shopper/stripe` | Stripe payment integration | It also installs `laravel/boost` and `laravel/pao` as development dependencies. After installing dependencies, the kit runs its post-install commands once you confirm them: `php artisan migrate`, `php artisan storage:link`, `npm install` and `npm run build`. The installer then writes a `.shopper-kit` file that lists every copied file and removes the kit package from your `composer.json`. Every file it copied belongs to your project. On an existing project, create a new branch before installing so you can review every change. ```bash git checkout -b storefront php artisan shopper:kit:install shopperlabs/vue-starter-kit ``` ## Project Structure [#project-structure] The starter kit publishes files into standard Laravel directories. The backend is shared with the [React Starter Kit](/2.x/react-starter-kit); only the `resources/js` frontend differs. Here is the structure it adds to your project. ```text app/ ├── Actions/ │ ├── Cart/ │ │ └── AddToCart.php │ ├── Checkout/ │ │ ├── BuildShippingPackages.php │ │ ├── FetchDeliveryRates.php │ │ ├── FetchPaymentMethods.php │ │ └── ResolveZoneForCountry.php │ ├── Fortify/ │ │ ├── CreateNewUser.php │ │ └── ResetUserPassword.php │ ├── Product/ │ │ ├── AddProductReviewAction.php │ │ ├── BuildVariantOptions.php │ │ └── ResolveVariantAvailability.php │ ├── CreateOrder.php │ ├── GetCountriesByZone.php │ └── ZoneSessionManager.php ├── Concerns/ │ ├── InteractsWithStorefrontMedia.php │ ├── PasswordValidationRules.php │ └── ProfileValidationRules.php ├── DTO/ │ ├── AddressData.php │ ├── CountryByZoneData.php │ ├── PriceData.php │ └── ProductReviewsData.php ├── Http/ │ ├── Controllers/ │ │ ├── Account/ # Address and order management │ │ ├── Settings/ # Profile and security │ │ ├── Shop/ # Home, products, cart, checkout, zone │ │ └── StripeWebhookController.php │ ├── Middleware/ │ │ ├── HandleAppearance.php │ │ └── HandleInertiaRequests.php │ └── Requests/Settings/ # Profile and password form requests ├── Models/ │ ├── Category.php │ ├── Channel.php │ ├── Collection.php │ ├── Product.php │ ├── ProductVariant.php │ └── User.php ├── Providers/ │ ├── AppServiceProvider.php │ ├── FortifyServiceProvider.php │ └── TypeScriptTransformerServiceProvider.php ├── Traits/ │ └── HasProductPricing.php ├── CheckoutSession.php └── helpers.php resources/js/ ├── components/ │ ├── account/ # Order status badge │ ├── shop/ # Product cards, price display, zone selector, Stripe form │ └── ui/ # shadcn-vue primitives (button, dialog, select, ...) ├── composables/ # useCart, useShop, useStripeElements, useAppearance ├── layouts/ # Storefront, account, settings, and auth layouts ├── lib/ # format, stripe, and utility helpers ├── pages/ │ ├── account/ # Orders, order detail, addresses │ ├── auth/ # Login, register, password reset, 2FA │ ├── settings/ # Profile, appearance, security │ ├── shop/ # Home, catalog, product, cart, checkout │ └── dashboard.vue # Customer dashboard ├── types/ # Shared and generated TypeScript types └── app.ts # Inertia application entry point routes/ ├── web.php # Storefront, checkout, account routes └── settings.php # Profile and security routes tests/ ├── Feature/Auth/ # Authentication tests ├── Feature/Settings/ # Profile and security tests └── Unit/ ``` ## Routing [#routing] The starter kit defines all storefront routes in `routes/web.php`. Unlike the Livewire kit, each page is rendered by a dedicated controller that returns an Inertia response. Routes are named so you can reference them through Wayfinder in your Vue components. ### Public Routes [#public-routes] | Route | Controller | Description | |-------|-----------|-------------| | `GET /` | `Shop\HomeController` | Homepage with featured collections, products, and categories | | `GET /shop` | `Shop\ProductController@index` | Product catalog with search and filtering | | `GET /shop/{product:slug}` | `Shop\ProductController@show` | Product detail with variant selection | | `GET /categories` | `Shop\CategoryController@index` | All categories | | `GET /categories/{category:slug}` | `Shop\CategoryController@show` | Products in a category | | `GET /collections/{collection:slug}` | `Shop\CollectionController@show` | Products in a collection | | `GET /search` | `Shop\SearchController` | Search products by name | | `GET /cart` | `Shop\CartController@index` | Shopping cart | Cart mutations are exposed as their own endpoints, limited to 60 requests per minute: `POST /cart` adds a line, `PATCH /cart/{line}` updates a quantity, `DELETE /cart/{line}` removes a line, and `DELETE /cart` clears the cart. The active pricing zone is changed with `PATCH /zone`. Search and the zone change are limited to 30 requests per minute. ### Authenticated Routes [#authenticated-routes] These routes require the user to be logged in. They also carry Laravel's `verified` middleware, which only checks the email address when the `User` model implements `MustVerifyEmail`. The kit's model does not, so a customer can check out right after registering. The profile settings page requires the login only. | Route | Controller | Description | |-------|-----------|-------------| | `GET /checkout` | `Shop\CheckoutController@index` | Multi-step checkout flow | | `GET /checkout/stripe-return` | `Shop\CheckoutController@stripeReturn` | Return URL of a Stripe payment, creates the order | | `GET /checkout/payment/{number}` | `Shop\StripePaymentController` | Stripe Payment Element for an existing order. The checkout does not link to it, it renders the Payment Element in its payment step | | `GET /checkout/success/{order}` | `Shop\CheckoutSuccessController` | Order confirmation | | `GET /dashboard` | Inertia page | Customer dashboard | | `GET /account/orders` | `Account\OrderController@index` | Order history | | `GET /account/orders/{order}` | `Account\OrderController@show` | Order detail | | `GET /account/addresses` | `Account\AddressController@index` | Address management | | `GET /settings/profile` | `Settings\ProfileController@edit` | Profile settings | | `GET /settings/appearance` | Inertia page | Light and dark appearance | | `GET /settings/security` | `Settings\SecurityController@edit` | Password and two-factor authentication | The checkout flow posts to dedicated endpoints for each step (`checkout/shipping-address`, `checkout/shipping-option`, `checkout/prepare-payment`, `checkout/place-order`). The Stripe webhook endpoint is `POST /webhooks/stripe`, outside the authenticated group and limited to 60 requests per minute. `bootstrap/app.php` excludes `webhooks/*` from CSRF verification so Stripe can reach it. ## Architecture [#architecture] Business logic lives in Action classes, data structures in DTOs, HTTP handling in controllers, and UI in Vue components, so you can change one layer of the storefront without editing the others. ### Actions [#actions] Actions are single-responsibility classes that encapsulate business logic. They are resolved from the container, so you can swap implementations or add dependencies as needed. ```php use App\Actions\Cart\AddToCart; use App\Actions\Checkout\FetchDeliveryRates; use App\Actions\CreateOrder; resolve(AddToCart::class)->handle($product, $selectedVariant); resolve(FetchDeliveryRates::class)->handle($addressData, $packages); resolve(CreateOrder::class)->handle(); ``` The checkout flow is split into four focused actions. | Action | Responsibility | |--------|---------------| | `BuildShippingPackages` | Builds package dimensions from cart items for carrier rate requests | | `FetchDeliveryRates` | Queries available carriers and returns shipping rate options | | `FetchPaymentMethods` | Loads payment methods available for the customer's country | | `ResolveZoneForCountry` | Resolves the pricing zone for a given country with caching | Order creation is wrapped in `CreateOrder`. It answers 422 when the checkout session has no delivery option or payment method, and 403 when the cart belongs to another customer. It then takes a 10-second `Cache::lock` on the cart, so a second submit of the same cart gets a 409 instead of a duplicate order, and converts the cart inside a database transaction. ### DTOs [#dtos] Data Transfer Objects give a fixed shape to the data passed between the backend and the Vue frontend. Because the kit uses the TypeScript Transformer, these DTOs also become TypeScript types your components can import. | DTO | Purpose | |-----|---------| | `AddressData` | Structured address data for forms and checkout | | `CountryByZoneData` | Selected zone and country (zone ID, code and name, country ID, name, code and flag, currency code) | | `PriceData` | Price with its comparison price and discount percentage | | `ProductReviewsData` | Product reviews with the average rating and the review count | ### Controllers [#controllers] Each storefront page is rendered by a controller in `app/Http/Controllers/`. Controllers query Shopper's models, eager load what the page displays, and return an Inertia response that renders the matching page component. The product page answers 404 for an unpublished product and loads prices in the active currency only. ```php title="app/Http/Controllers/Shop/ProductController.php" public function show(Product $product): Response { abort_unless($product->isPublished(), 404); $currencyCode = current_currency(); $priceConstraint = fn ($q) => $q->whereRelation('currency', 'code', $currencyCode); $product->load([ 'brand', 'media', 'prices' => $priceConstraint, 'relatedProducts.brand', 'relatedProducts.media', 'relatedProducts.prices' => $priceConstraint, 'variants.media', 'variants.values.attribute', 'variants.prices' => $priceConstraint, ]); // ... return Inertia::render('shop/product', [ 'product' => $product, 'variantOptions' => $variantOptions, ]); } ``` To change what a page receives, edit its controller. To change how it looks, edit the matching page component in `resources/js/pages/`. ### Inertia Shared Data [#inertia-shared-data] The `HandleInertiaRequests` middleware shares data with every page, so your components receive the authenticated user and the current shop state without another request. The `shop` prop is built by `shopProps()`. ```php title="app/Http/Middleware/HandleInertiaRequests.php" return [ 'cart_count' => $cart?->lines->sum('quantity') ?? 0, 'zone' => $zone ? [ 'country_code' => $zone->countryCode, 'country_name' => $zone->countryName, 'currency_code' => $zone->currencyCode, 'zone_id' => $zone->zoneId, ] : null, 'currency' => current_currency(), 'channels' => Channel::query() ->scopes('enabled') ->select('id', 'name', 'slug') ->get() ->toArray(), 'available_zones' => fn (): array => resolve(GetCountriesByZone::class)->handle()->values()->toArray(), 'tax_label' => current_tax_label(), 'nav_categories' => $this->topCategories(4, 'nav'), 'footer_categories' => $this->topCategories(6, 'footer'), ]; ``` On the frontend, the `useShop` composable reads this shared data and changes the country with `changeZone()`. The `useCart` composable exposes `add`, `update`, `remove` and `clear`, which call the cart endpoints. ### Models [#models] The starter kit adds `Category`, `Channel`, `Collection`, `Product` and `ProductVariant` models in `app/Models/` that extend Shopper's base models. They are registered in `config/shopper/models.php`, so Shopper's internals and the admin panel use your versions. ```php title="app/Models/Product.php" namespace App\Models; use App\Concerns\InteractsWithStorefrontMedia; use App\Traits\HasProductPricing; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; use InteractsWithStorefrontMedia; /** @param Builder $query */ #[Scope] protected function withCurrentPrices(Builder $query): Builder { return $query->with([ 'prices' => fn ($q) => $q->whereRelation('currency', 'code', current_currency()), ]); } } ``` You can add custom logic directly to these models. Any method you add is available throughout the storefront and in Shopper's admin panel. The `withCurrentPrices` scope loads only the prices in the active currency, and `HasProductPricing` adds `getFormattedPrice()`, which returns a `PriceData` with the amount, the comparison price and the discount percentage in that currency. The `InteractsWithStorefrontMedia` trait appends `thumbnail` and `images` attributes to every JSON response, so your Vue components receive media URLs they can use as is. ### CheckoutSession [#checkoutsession] The `CheckoutSession` class defines the session keys of the checkout in one place. The checkout stores the shipping address, the delivery option and the payment method under these keys. `BILLING_ADDRESS` and `SAME_AS_SHIPPING` are defined, but the kit's checkout does not use them. ```php use App\CheckoutSession; session()->get(CheckoutSession::KEY); // 'checkout' session()->get(CheckoutSession::SHIPPING_ADDRESS); // 'checkout.shipping_address' session()->get(CheckoutSession::BILLING_ADDRESS); // 'checkout.billing_address' session()->get(CheckoutSession::SAME_AS_SHIPPING); // 'checkout.same_as_shipping' session()->get(CheckoutSession::SHIPPING_OPTION); // 'checkout.shipping_option' session()->get(CheckoutSession::PAYMENT); // 'checkout.payment' ``` ### Helpers [#helpers] The `app/helpers.php` file defines three global functions used across the storefront. | Function | Purpose | |----------|---------| | `cartSession()` | Returns the current cart or creates a new one with the active zone, currency, and channel | | `current_currency()` | Returns the currency code for the selected zone, or the store default from `shopper_currency()` | | `current_tax_label()` | Returns the tax label ("TTC" or "HT") from the tax zone of the selected country, or an empty string when no zone is selected | ### Type Safety [#type-safety] Three tools give your Vue components the shape of the backend data, so a renamed route or a changed DTO shows up as a TypeScript error. | Tool | What it provides | |------|------------------| | Wayfinder | Typed route helpers generated from your routes into `resources/js/routes` and `resources/js/actions`, so `shop.product.url({ product: product.slug })` builds a product URL | | TypeScript Transformer | Generates TypeScript definitions from your PHP DTOs and enums into `resources/js/types/generated.d.ts` | | `@shopperlabs/shopper-types` | Shared domain types (Address, Cart, Order, Product, and enums) published as an npm package | The Wayfinder Vite plugin in `vite.config.ts` regenerates the route helpers while `npm run dev` runs and during `npm run build`. The `TypeScriptTransformerServiceProvider` registers the transformer; run it after changing a DTO to refresh the types your components import. ```bash php artisan typescript:transform ``` ## Checkout Flow [#checkout-flow] The checkout is a multi-step process handled by `CheckoutController`. Each step posts to its own endpoint and validates its data before proceeding to the next. **Step 1 - Shipping Address.** The customer enters a new address or selects one of their saved addresses to fill the form. The address takes the country selected in the storefront, then it is stored in the session and attached to the cart as its shipping address through `CartManager::addAddress()`. **Step 2 - Delivery Options.** The `BuildShippingPackages` action builds package data from the cart, then `FetchDeliveryRates` queries configured [carriers](/2.x/carriers) for available shipping rates based on the address and packages. The customer selects a delivery option. **Step 3 - Payment.** `FetchPaymentMethods` loads the enabled [payment methods](/2.x/payments) of the zone that contains the address country, and keeps only those whose driver is configured: Stripe is listed once `STRIPE_SECRET_KEY` is set in your `.env`. For a method other than Stripe, such as cash on delivery, placing the order runs the `CreateOrder` action, which converts the cart into an order inside a database transaction and adds shipping costs, then initiates payment processing through Shopper's `PaymentProcessingService`. For Stripe payments, choosing the method creates a Stripe PaymentIntent without creating an order, and the payment step renders the Stripe Payment Element through the `useStripeElements` composable. Once Stripe confirms the payment, it sends the customer back to `/checkout/stripe-return`, which checks the PaymentIntent and runs `CreateOrder`. The `StripeWebhookController` receives Stripe events on `/webhooks/stripe`, finds the order through its payment transaction, and reports an authorization or a capture whose amount in cents differs from the order's `price_amount` without changing the order. An authorized payment sets the order's payment status to `Authorized` and a captured one to `Paid`. A failed or canceled payment cancels the order and voids its payment, and a refund cancels the order with the `Refunded` payment status. ## Zones and Currency [#zones-and-currency] The starter kit uses Shopper's [zone system](/2.x/zones) for multi-currency and regional pricing. The `ZoneSelector` component in the footer lets customers pick their country. When a zone is selected, the `ZoneSessionManager` stores the country code in the session and resolves it to a `CountryByZoneData` DTO with the zone ID, country code, and currency code. It also resets the checkout in progress and moves the cart to the new zone and currency. Product prices across the storefront switch to the zone's currency through the shared `shop` prop. If no zone is selected, the storefront falls back to your store's default currency from `shopper_currency()`. The `current_tax_label()` helper reads the tax zone of the selected country to display "TTC" (tax-inclusive) or "HT" (tax-exclusive) labels alongside prices. To enable zone selection, create at least one active zone in your Shopper admin panel. ## Customization [#customization] Once installed, every file belongs to your project. These are the places you change first. ### Styling [#styling] All views use shadcn-vue components and Tailwind CSS v4. Modify colors, spacing, and layouts by editing the components in `resources/js`. UI primitives live in `resources/js/components/ui/`, and the storefront header and footer are in `resources/js/layouts/storefront/`. ### Pages [#pages] Each page is a Vue single-file component in `resources/js/pages/`. Edit any `.vue` file to change a page's layout or content. To change the data a page receives, edit its controller in `app/Http/Controllers/`. Pages do not declare their layout: the `layout` callback of `resources/js/app.ts` picks it from the page name. | Page name | Layout | |-----------|--------| | `shop/*` | Storefront header and footer, from `layouts/storefront-layout.vue` | | `account/*` and `dashboard` | Storefront layout with the account navigation of `layouts/account-layout.vue` | | `settings/*` | Account layout with the settings navigation of `layouts/settings-sub-layout.vue` | | `auth/*` | Authentication layout, from `layouts/auth-layout.vue` | | Any other name | Sidebar application layout, from `layouts/app-layout.vue` | ### Checkout [#checkout] To modify the checkout flow, edit the action classes in `app/Actions/Checkout/`. Each action handles one concern, so you can change how shipping rates are calculated without touching payment logic. To add a new payment provider, implement the provider using Shopper's [payment system](/2.x/payments), register it in your admin panel, and enable it on the zones where customers can use it. `FetchPaymentMethods` lists it once its driver is configured, and placing the order follows the redirect URL the driver returns, if any. ### Adding Pages [#adding-pages] Create a controller, register a named route in `routes/web.php`, and add the matching Vue component under `resources/js/pages/`. Name the page under `shop/` so it renders with the storefront header and footer. ```php title="app/Http/Controllers/AboutController.php" namespace App\Http\Controllers; use Inertia\Inertia; use Inertia\Response; final class AboutController extends Controller { public function __invoke(): Response { return Inertia::render('shop/about'); } } ``` ```php title="routes/web.php" use App\Http\Controllers\AboutController; Route::get('about', AboutController::class)->name('about'); ``` ```vue title="resources/js/pages/shop/about.vue" ``` Wayfinder adds an `about` function to `@/routes` the next time Vite runs, so a link in the footer reads `About`, the way `resources/js/layouts/storefront/store-footer.vue` links to `home`. ### Models [#models-1] Add methods, scopes, or relationships directly to the model files in `app/Models/`. These models extend Shopper's base models, so all existing functionality is preserved. ```php title="app/Models/Product.php" use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; final class Product extends Model { #[Scope] protected function featured(Builder $query): Builder { return $query->where('featured', true); } } ``` # Catalog Types (/2.x/reference/types/catalog) ## Category [#category] The `Category` interface represents a product category. ```typescript import type { Category } from '@shopperlabs/shopper-types' ``` ### Definition [#definition] ```typescript interface Category extends Entity, SEOFields { name: string slug: string description: string | null is_enabled: boolean position: number parent_id: number | null metadata: Metadata slug_path?: string // Relationships image?: Media | null parent?: Category children?: Category[] products?: Product[] } ``` ### Usage Examples [#usage-examples] ```typescript import type { Category } from '@shopperlabs/shopper-types' function buildCategoryTree(categories: Category[]): Category[] { const map = new Map() const roots: Category[] = [] categories.forEach((cat) => map.set(cat.id, { ...cat, children: [] })) categories.forEach((cat) => { const category = map.get(cat.id)! if (cat.parent_id && map.has(cat.parent_id)) { map.get(cat.parent_id)!.children!.push(category) } else { roots.push(category) } }) return roots } // Get category breadcrumb function getCategoryPath(category: Category): string[] { return category.slug_path?.split('/') ?? [category.slug] } ``` --- ## Brand [#brand] The `Brand` interface represents a product brand. ```typescript import type { Brand } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-1] ```typescript interface Brand extends Entity, SEOFields { name: string slug: string | null website: string | null description: string | null position: number is_enabled: boolean metadata: Metadata // Relationships image?: Media | null } ``` --- ## Collection [#collection] The `Collection` interface represents a product collection. ```typescript import type { Collection } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-2] ```typescript interface Collection extends Entity, SEOFields { name: string slug: string description?: string | null type: CollectionType match_conditions: CollectionCondition | null sort: string | null published_at: DateEntity | null metadata: Metadata // Relationships image?: Media | null rules?: CollectionRule[] zones?: Zone[] products?: Product[] } ``` ### CollectionType Enum [#collectiontype-enum] ```typescript enum CollectionType { MANUAL = 'manual', AUTO = 'auto', } ``` ### CollectionCondition Enum [#collectioncondition-enum] ```typescript enum CollectionCondition { ALL = 'all', ANY = 'any', } ``` ### CollectionRule Interface [#collectionrule-interface] ```typescript interface CollectionRule extends Entity { rule: CollectionRuleType operator: CollectionOperator value: string collection_id: number collection?: Collection } enum CollectionRuleType { PRODUCT_TITLE = 'product_title', PRODUCT_BRAND = 'product_brand', PRODUCT_CATEGORY = 'product_category', PRODUCT_PRICE = 'product_price', COMPARE_AT_PRICE = 'compare_at_price', INVENTORY_STOCK = 'inventory_stock', PRODUCT_CREATED_AT = 'product_created_at', PRODUCT_FEATURED = 'product_featured', PRODUCT_RATING = 'product_rating', PRODUCT_SALES_COUNT = 'product_sales_count', } enum CollectionOperator { EQUALS_TO = 'equals_to', NOT_EQUAL_TO = 'not_equal_to', LESS_THAN = 'less_than', GREATER_THAN = 'greater_than', STARTS_WITH = 'starts_with', ENDS_WITH = 'ends_with', CONTAINS = 'contains', NOT_CONTAINS = 'not_contains', } ``` --- ## Attribute [#attribute] The `Attribute` interface represents a product attribute (color, size, etc.). ```typescript import type { Attribute, AttributeValue } from '@shopperlabs/shopper-types' ``` ### Attribute Definition [#attribute-definition] ```typescript interface Attribute extends Entity { name: string slug: string type: FieldType icon: string | null description: string | null is_enabled: boolean is_searchable: boolean is_filterable: boolean type_formatted?: string // Relationships values?: AttributeValue[] } ``` ### AttributeValue Definition [#attributevalue-definition] ```typescript interface AttributeValue { id: number value: string key: string position: number attribute_id: number attribute?: Attribute } ``` ### FieldType Enum [#fieldtype-enum] ```typescript enum FieldType { TEXT = 'text', NUMBER = 'number', RICH_TEXT = 'richtext', SELECT = 'select', CHECKBOX = 'checkbox', COLOR_PICKER = 'colorpicker', DATE_PICKER = 'datepicker', } ``` ### Usage Examples [#usage-examples-1] ```typescript import type { Attribute } from '@shopperlabs/shopper-types' import { FieldType } from '@shopperlabs/shopper-types' // Get filterable attributes function getFilterableAttributes(attributes: Attribute[]): Attribute[] { return attributes.filter((attr) => attr.is_filterable && attr.is_enabled) } // Check if attribute has selectable values function hasSelectableValues(attribute: Attribute): boolean { return [FieldType.SELECT, FieldType.CHECKBOX, FieldType.COLOR_PICKER] .includes(attribute.type) } // Render attribute input based on type function getInputComponent(attribute: Attribute): string { switch (attribute.type) { case FieldType.TEXT: return 'TextInput' case FieldType.NUMBER: return 'NumberInput' case FieldType.RICH_TEXT: return 'RichTextEditor' case FieldType.SELECT: return 'Select' case FieldType.CHECKBOX: return 'CheckboxGroup' case FieldType.COLOR_PICKER: return 'ColorPicker' case FieldType.DATE_PICKER: return 'DatePicker' default: return 'TextInput' } } ``` # Customer Types (/2.x/reference/types/customer) ## Customer [#customer] The `Customer` interface represents a customer in your store. ```typescript import type { Customer } from '@shopperlabs/shopper-types' ``` ### Definition [#definition] ```typescript interface Customer extends Entity { first_name: string | null last_name: string email: string gender: GenderType | null phone_number: string | null birth_date: string | null email_verified_at: string | null avatar: AvatarType timezone?: string | null opt_in: boolean last_login_at: DateEntity | null last_login_ip?: string | null // Relationships addresses?: Address[] } ``` ### GenderType Enum [#gendertype-enum] ```typescript enum GenderType { MALE = 'male', FEMALE = 'female', } ``` ### AvatarType Interface [#avatartype-interface] ```typescript interface AvatarType { type: string url: string default: string } ``` ### Usage Examples [#usage-examples] ```typescript import type { Customer } from '@shopperlabs/shopper-types' // Get full name function getCustomerName(customer: Customer): string { if (customer.first_name) { return `${customer.first_name} ${customer.last_name}` } return customer.last_name } // Get default shipping address function getDefaultShippingAddress(customer: Customer) { return customer.addresses?.find((addr) => addr.shipping_default) } // Check if customer has opted in to marketing function canSendMarketing(customer: Customer): boolean { return customer.opt_in && customer.email_verified_at !== null } ``` --- ## Address [#address] The `Address` interface represents a customer address. ```typescript import type { Address } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-1] ```typescript interface Address extends Entity { first_name: string | null last_name: string full_name: string company_name: string | null street_address: string street_address_plus?: string | null postal_code: string city: string state: string | null phone_number?: string | null type: AddressType metadata: Metadata shipping_default: boolean billing_default: boolean user_id: number country_id: number // Relationships country?: Country } ``` ### AddressType Enum [#addresstype-enum] ```typescript enum AddressType { BILLING = 'billing', SHIPPING = 'shipping', } ``` ### Usage Examples [#usage-examples-1] ```typescript import type { Address } from '@shopperlabs/shopper-types' import { AddressType } from '@shopperlabs/shopper-types' // Format address for display function formatAddress(address: Address): string { const lines = [ address.full_name, address.company_name, address.street_address, address.street_address_plus, `${address.city}, ${address.state ?? ''} ${address.postal_code}`, address.country?.name, ].filter(Boolean) return lines.join('\n') } // Filter shipping addresses function getShippingAddresses(addresses: Address[]): Address[] { return addresses.filter((addr) => addr.type === AddressType.SHIPPING) } ``` --- ## Country [#country] The `Country` interface represents a country. ```typescript import type { Country } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-2] ```typescript interface Country { id: number name: string name_official: string region: string subregion: string cca3: string cca2: string flag: string svg_flag: string latitude: number longitude: number phone_calling_code: Record currencies: Record // Relationships zones?: Zone[] } ``` # Order Types (/2.x/reference/types/order) ## Order [#order] The `Order` interface represents a customer order with three independent statuses tracking order progress, payment, and shipping. ```typescript import type { Order } from '@shopperlabs/shopper-types' ``` ### Definition [#definition] ```typescript interface Order extends Entity { number: string price_amount: number notes: string | null currency_code: string total_amount?: number status: OrderStatus payment_status: PaymentStatus shipping_status: ShippingStatus cancelled_at: DateEntity | null archived_at: DateEntity | null zone_id: number | null shipping_address_id: number | null billing_address_id: number | null payment_method_id: number | null customer_id: number | null channel_id: number | null parent_order_id: number | null shipping_option_id?: number | null metadata: Metadata // Relationships shippingOption?: CarrierOption shippingAddress?: OrderAddress | null billingAddress?: OrderAddress | null paymentMethod?: PaymentMethod | null zone?: Zone | null channel?: Channel | null parent?: Order | null customer?: Customer items?: OrderItem[] shippings?: OrderShipping[] children?: Order[] refund?: OrderRefund } ``` ### OrderStatus Enum [#orderstatus-enum] Tracks the overall lifecycle of the order. ```typescript enum OrderStatus { NEW = 'new', PROCESSING = 'processing', COMPLETED = 'completed', CANCELLED = 'cancelled', ARCHIVED = 'archived', } ``` ### PaymentStatus Enum [#paymentstatus-enum] Tracks whether payment has been collected. ```typescript enum PaymentStatus { PENDING = 'pending', AUTHORIZED = 'authorized', PAID = 'paid', PARTIALLY_REFUNDED = 'partially_refunded', REFUNDED = 'refunded', VOIDED = 'voided', } ``` ### ShippingStatus Enum [#shippingstatus-enum] Tracks the overall shipping state at the order level. ```typescript enum ShippingStatus { UNFULFILLED = 'unfulfilled', PARTIALLY_SHIPPED = 'partially_shipped', SHIPPED = 'shipped', PARTIALLY_DELIVERED = 'partially_delivered', DELIVERED = 'delivered', PARTIALLY_RETURNED = 'partially_returned', RETURNED = 'returned', } ``` ### Usage Examples [#usage-examples] ```typescript import type { Order } from '@shopperlabs/shopper-types' import { OrderStatus, PaymentStatus, ShippingStatus } from '@shopperlabs/shopper-types' function canCancel(order: Order): boolean { return ( order.status !== OrderStatus.CANCELLED && order.status !== OrderStatus.ARCHIVED && order.shipping_status === ShippingStatus.UNFULFILLED ) } function canCapture(order: Order): boolean { return order.payment_status === PaymentStatus.AUTHORIZED } function getStatusColor(status: OrderStatus): string { const colors: Record = { [OrderStatus.NEW]: '#3b82f6', [OrderStatus.PROCESSING]: '#2563eb', [OrderStatus.COMPLETED]: '#059669', [OrderStatus.CANCELLED]: '#ef4444', [OrderStatus.ARCHIVED]: '#6b7280', } return colors[status] } function calculateTotal(order: Order): number { return order.items?.reduce((sum, item) => sum + item.total, 0) ?? 0 } ``` --- ## OrderItem [#orderitem] The `OrderItem` interface represents a line item in an order. Each item tracks its own fulfillment status independently. ```typescript import type { OrderItem } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-1] ```typescript interface OrderItem extends Entity { name: string quantity: number unit_price_amount: number | null total: number sku: string | null product_id: number product_type: string order_id: number order_shipping_id: number | null fulfillment_status: FulfillmentStatus | null // Relationships order?: Order shipment?: OrderShipping } ``` ### FulfillmentStatus Enum [#fulfillmentstatus-enum] Tracks item-level fulfillment, enabling partial shipments and multi-carrier delivery. ```typescript enum FulfillmentStatus { PENDING = 'pending', FORWARDED_TO_SUPPLIER = 'forwarded_to_supplier', PROCESSING = 'processing', SHIPPED = 'shipped', DELIVERED = 'delivered', CANCELLED = 'cancelled', } ``` --- ## OrderAddress [#orderaddress] The `OrderAddress` interface represents a shipping or billing address for an order. ```typescript import type { OrderAddress } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-2] ```typescript interface OrderAddress extends Entity { first_name: string last_name: string full_name: string street_address: string street_address_plus: string | null postal_code: string city: string state: string | null company: string | null phone: string | null country_name: string | null customer_id?: number | null customer?: Customer } ``` --- ## OrderShipping [#ordershipping] The `OrderShipping` interface represents a shipment, a physical package sent to the customer. Each shipment tracks its own delivery progress and has a timeline of tracking events. ```typescript import type { OrderShipping } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-3] ```typescript interface OrderShipping extends Entity { status: ShipmentStatus | null shipped_at: DateEntity | null received_at: DateEntity | null returned_at: DateEntity | null tracking_number: string | null tracking_url: string | null voucher: Record | null order_id: number carrier_id: number | null // Relationships order?: Order carrier?: Carrier items?: OrderItem[] events?: OrderShippingEvent[] } ``` ### ShipmentStatus Enum [#shipmentstatus-enum] Tracks the delivery progress of a single package. ```typescript enum ShipmentStatus { PENDING = 'pending', PICKED_UP = 'picked_up', IN_TRANSIT = 'in_transit', AT_SORTING_CENTER = 'at_sorting_center', OUT_FOR_DELIVERY = 'out_for_delivery', DELIVERED = 'delivered', DELIVERY_FAILED = 'delivery_failed', RETURNED = 'returned', } ``` --- ## OrderShippingEvent [#ordershippingevent] The `OrderShippingEvent` interface represents a tracking event in a shipment's timeline. ```typescript import type { OrderShippingEvent } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-4] ```typescript interface OrderShippingEvent extends Entity { status: ShipmentStatus description: string | null location: string | null latitude: number | null longitude: number | null occurred_at: DateEntity | null metadata: Record | null order_shipping_id: number // Relationships shipment?: OrderShipping } ``` --- ## OrderRefund [#orderrefund] The `OrderRefund` interface represents a refund for an order. ```typescript import type { OrderRefund } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-5] ```typescript interface OrderRefund extends Entity { refund_reason: string | null refund_amount: number | null status: OrderRefundStatus notes: string | null currency: string order_id: number user_id: number | null metadata: Metadata order?: Order } ``` ### OrderRefundStatus Enum [#orderrefundstatus-enum] ```typescript enum OrderRefundStatus { PENDING = 'pending', AWAITING = 'awaiting', TREATMENT = 'treatment', PARTIAL_REFUND = 'partial_refund', REFUNDED = 'refunded', CANCELLED = 'cancelled', REJECTED = 'rejected', } ``` # Product Types (/2.x/reference/types/product) ## Product [#product] The `Product` interface represents a product in your catalog. ```typescript import type { Product } from '@shopperlabs/shopper-types' ``` ### Definition [#definition] ```typescript interface Product extends Entity, SEOFields, ShippingFields { name: string slug: string sku?: string | null barcode: string | null summary: string | null description: string | null security_stock: number | null featured: boolean is_visible: boolean type: ProductType | null published_at: DateEntity | null external_id: string | null stock: number variants_stock?: number supplier_id?: number | null brand_id: number | null metadata: Metadata // Relationships supplier?: Supplier brand?: Brand channels?: Channel[] categories?: Category[] options?: Attribute[] collections?: Collection[] tags?: ProductTag[] variants?: ProductVariant[] relatedProducts?: Product[] images?: Media[] | null reviews?: Review[] prices?: Price[] } ``` ### ProductType Enum [#producttype-enum] ```typescript enum ProductType { EXTERNAL = 'external', VIRTUAL = 'virtual', STANDARD = 'standard', VARIANT = 'variant', } ``` ### Usage Examples [#usage-examples] ```typescript import type { Product } from '@shopperlabs/shopper-types' import { ProductType } from '@shopperlabs/shopper-types' function isVariantProduct(product: Product): boolean { return product.type === ProductType.VARIANT } async function fetchProduct(slug: string): Promise { const response = await fetch(`/api/products/${slug}`) return response.json() } function isInStock(product: Product): boolean { if (product.type === ProductType.VARIANT) { return (product.variants_stock ?? 0) > 0 } return product.stock > 0 } function getProductImage(product: Product): string | null { return product.images?.[0]?.url ?? null } ``` --- ## ProductVariant [#productvariant] The `ProductVariant` interface represents a variant of a product (size, color, etc.). ```typescript import type { ProductVariant } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-1] ```typescript interface ProductVariant extends Entity, ShippingFields { name: string sku?: string | null barcode: string | null ean: string | null upc: string | null position: number allow_backorder: boolean product_id: number stock: number metadata: Metadata // Relationships product?: Product values?: AttributeValue[] images?: Media[] | null prices?: Price[] } ``` ### Usage Examples [#usage-examples-1] ```typescript import type { Product, ProductVariant } from '@shopperlabs/shopper-types' function findVariant( product: Product, attributes: Record ): ProductVariant | undefined { return product.variants?.find((variant) => { return variant.values?.every((value) => { const attr = value.attribute return attr && attributes[attr.slug] === value.key }) }) } function isVariantAvailable(variant: ProductVariant): boolean { return variant.stock > 0 || variant.allow_backorder } function getVariantPrice(variant: ProductVariant): number | null { return variant.prices?.[0]?.amount ?? null } ``` --- ## ProductTag [#producttag] The `ProductTag` interface represents a simple label attached to products. ```typescript import type { ProductTag } from '@shopperlabs/shopper-types' ``` ### Definition [#definition-2] ```typescript interface ProductTag extends Entity { name: string slug: string | null // Relationships products?: Product[] } ``` ### Usage Examples [#usage-examples-2] ```typescript import type { Product, ProductTag } from '@shopperlabs/shopper-types' function getProductsByTag(products: Product[], tagSlug: string): Product[] { return products.filter((product) => product.tags?.some((tag) => tag.slug === tagSlug) ) } function getTagNames(product: Product): string[] { return product.tags?.map((tag) => tag.name) ?? [] } ``` # Overview (/2.x/reference/typescript-types) The `@shopperlabs/shopper-types` package provides comprehensive TypeScript type definitions for all Shopper models and entities. These types are useful when building storefronts, mobile apps, or any TypeScript application that interacts with the Shopper API. ## Installation [#installation] ```npm npm install @shopperlabs/shopper-types ``` As of v2.9 the package ships as ECMAScript Modules (`"type": "module"` with an `exports` map). Use `import` rather than CommonJS `require()`. ESM-first projects need no changes. ## Usage [#usage] Import types directly from the package: ```typescript import type { Product, ProductVariant, Order } from '@shopperlabs/shopper-types' // Use in your API calls async function getProduct(id: number): Promise { const response = await fetch(`/api/products/${id}`) return response.json() } // Type your component props interface ProductCardProps { product: Product } ``` ## Available Types [#available-types] The package exports types for all Shopper models: | Type | Description | |------|-------------| | `Product` | Product model with variants, categories, and media | | `ProductVariant` | Product variant with pricing and attributes | | `ProductTag` | Simple label for cross-cutting product organization | | `Order` | Order with items, addresses, and shipping | | `OrderItem` | Individual order line item | | `OrderShipping` | Shipment with tracking and carrier | | `OrderShippingEvent` | Tracking event in a shipment timeline | | `OrderAddress` | Shipping or billing address on an order | | `OrderRefund` | Refund request for an order | | `Customer` | Customer profile and addresses | | `Category` | Hierarchical product category | | `Brand` | Product brand | | `Collection` | Product collection (manual or automatic) | | `Attribute` | Product attribute definition | | `AttributeValue` | Attribute value option | | `Address` | Customer address | | `Channel` | Sales channel | | `Zone` | Shipping/pricing zone | | `Carrier` | Shipping carrier | | `CarrierOption` | Carrier shipping option | | `Currency` | Currency configuration | | `Discount` | Discount/coupon code | | `Inventory` | Inventory location | | `PaymentMethod` | Payment method | | `Review` | Product review | | `Supplier` | Product supplier | ## Enums [#enums] The package also exports enums for type-safe status checks: ```typescript import { ProductType, OrderStatus, PaymentStatus, ShippingStatus, CollectionType, AddressType } from '@shopperlabs/shopper-types' if (product.type === ProductType.VARIANT) { // Handle variant product } if (order.status === OrderStatus.COMPLETED) { // Order is complete } if (order.payment_status === PaymentStatus.AUTHORIZED) { // Payment can be captured } ``` ### Available Enums [#available-enums] | Enum | Values | |------|--------| | `ProductType` | `STANDARD`, `VARIANT`, `VIRTUAL`, `EXTERNAL` | | `OrderStatus` | `NEW`, `PROCESSING`, `COMPLETED`, `CANCELLED`, `ARCHIVED` | | `PaymentStatus` | `PENDING`, `AUTHORIZED`, `PAID`, `PARTIALLY_REFUNDED`, `REFUNDED`, `VOIDED` | | `ShippingStatus` | `UNFULFILLED`, `PARTIALLY_SHIPPED`, `SHIPPED`, `PARTIALLY_DELIVERED`, `DELIVERED`, `PARTIALLY_RETURNED`, `RETURNED` | | `FulfillmentStatus` | `PENDING`, `FORWARDED_TO_SUPPLIER`, `PROCESSING`, `SHIPPED`, `DELIVERED`, `CANCELLED` | | `ShipmentStatus` | `PENDING`, `PICKED_UP`, `IN_TRANSIT`, `AT_SORTING_CENTER`, `OUT_FOR_DELIVERY`, `DELIVERED`, `DELIVERY_FAILED`, `RETURNED` | | `OrderRefundStatus` | `PENDING`, `AWAITING`, `TREATMENT`, `PARTIAL_REFUND`, `REFUNDED`, `CANCELLED`, `REJECTED` | | `CollectionType` | `MANUAL`, `AUTO` | | `CollectionCondition` | `ALL`, `ANY` | | `CollectionRuleType` | `PRODUCT_TITLE`, `PRODUCT_BRAND`, `PRODUCT_CATEGORY`, `PRODUCT_PRICE`, `COMPARE_AT_PRICE`, `INVENTORY_STOCK`, `PRODUCT_CREATED_AT`, `PRODUCT_FEATURED`, `PRODUCT_RATING`, `PRODUCT_SALES_COUNT` | | `CollectionOperator` | `EQUALS_TO`, `NOT_EQUAL_TO`, `LESS_THAN`, `GREATER_THAN`, `STARTS_WITH`, `ENDS_WITH`, `CONTAINS`, `NOT_CONTAINS` | | `AddressType` | `BILLING`, `SHIPPING` | | `DiscountType` | `PERCENTAGE`, `FIXED_AMOUNT` | | `GenderType` | `MALE`, `FEMALE` | | `FieldType` | `TEXT`, `NUMBER`, `RICH_TEXT`, `SELECT`, `CHECKBOX`, `COLOR_PICKER`, `DATE_PICKER` | | `Weight` | `KG`, `G`, `LBS` | | `Length` | `M`, `CM`, `MM`, `FT`, `IN` | | `Volume` | `L`, `ML`, `GAL`, `FLOZ` | ## Common Interfaces [#common-interfaces] ### Entity [#entity] All models extend the base `Entity` interface: ```typescript interface Entity { id: number created_at?: DateEntity updated_at?: DateEntity deleted_at?: DateEntity | null } ``` ### DateEntity [#dateentity] Dates are returned with both raw and human-readable formats: ```typescript interface DateEntity { date: string // e.g., "2026-02-11 14:30:00" human: string // e.g., "2 hours ago" } ``` ### Price [#price] Pricing information for products and variants: ```typescript interface Price { amount: number | null compare_amount: number | null cost_amount: number | null currency_id: number currency_code: string currency?: Currency } ``` ### ShippingFields [#shippingfields] Physical dimensions for shippable products: ```typescript interface ShippingFields { width_unit: Length width_value: number | null weight_unit: Weight weight_value: number | null height_unit: Length height_value: number | null depth_unit: Length depth_value: number | null volume_unit: Volume volume_value: number | null } ``` ## Example: Storefront Product List [#example-storefront-product-list] ```typescript import type { Product, Category } from '@shopperlabs/shopper-types' import { ProductType } from '@shopperlabs/shopper-types' interface ProductListProps { products: Product[] category?: Category } function ProductList({ products, category }: ProductListProps) { return (
    {category &&

    {category.name}

    } {products.map((product) => (

    {product.name}

    {product.description}

    {product.type === ProductType.VARIANT && ( {product.variants?.length} variants )} {product.prices?.[0] && ( {product.prices[0].currency_code} {product.prices[0].amount} )}
    ))}
    ) } ``` ## Example: Order Details [#example-order-details] ```typescript import type { Order, OrderItem } from '@shopperlabs/shopper-types' import { OrderStatus, PaymentStatus, ShippingStatus } from '@shopperlabs/shopper-types' function OrderDetails({ order }: { order: Order }) { const statusColors: Record = { [OrderStatus.NEW]: '#3b82f6', [OrderStatus.PROCESSING]: '#2563eb', [OrderStatus.COMPLETED]: '#059669', [OrderStatus.CANCELLED]: '#ef4444', [OrderStatus.ARCHIVED]: '#6b7280', } return (

    Order #{order.number}

    {order.status} {order.payment_status} {order.shipping_status}

    Items

    {order.items?.map((item: OrderItem) => (
    {item.name} x{item.quantity} {item.unit_price_amount}
    ))} {order.shippingAddress && (

    Shipping Address

    {order.shippingAddress.full_name}

    {order.shippingAddress.street_address}

    {order.shippingAddress.city}, {order.shippingAddress.state}

    {order.shippingAddress.postal_code}

    )}
    ) } ``` ## Source Code [#source-code] The types are open source and available on GitHub: View the source code and contribute to the types package. # Roles & Permissions (/2.x/user-guide/administration/roles) Roles and permissions allow you to control what each staff member can do in your store's administration panel. This ensures security and prevents unauthorized access to sensitive areas. ## Overview [#overview] The access control system consists of: - **Roles** - Groups of permissions assigned to users - **Permissions** - Individual actions a user can perform ## Accessing Roles & Permissions [#accessing-roles--permissions] 1. Click on **Settings** in the sidebar 2. Select **Staff & permissions** The page opens with the title **Administrators & roles**. Your roles appear as cards under **Administrator role available**, each with its number of accounts and a **View details** link that opens the role. ## Understanding Permissions [#understanding-permissions] Permissions control access to specific actions: ### Permission Categories [#permission-categories] Permissions are sorted into groups. Most groups hold the same five permissions for one area of the admin: **Browse** (see the list), **Read** (open a record), **Edit**, **Add** and **Delete**. | Category | Examples | |----------|----------| | **System** | **Access Dashboard**; **Access Setting** (all store settings except staff, roles and permissions); **Views Users** (staff accounts, roles and permissions) | | **Brands** | Browse, read, edit, add and delete brands | | **Categories** | Browse, read, edit, add and delete categories | | **Collections** | Browse, read, edit, add and delete collections | | **Products** | Browse, read, edit, add and delete products, plus the same five permissions for inventories, attributes, reviews, product variants, suppliers and tags | | **Customers** | Browse, read, edit, add and delete customers | | **Orders** | Browse, read, edit, add and delete orders. There is no separate permission for refunds | | **Discounts** | Browse, read, edit, add and delete discounts | Permissions created without a group are listed under **Custom permission**. ### Browsing Permissions [#browsing-permissions] Open a role with **View details** and click the **Permissions** tab. Every permission is listed by group, with a checkbox that shows whether the role has it and the date it was created: ## Managing Roles [#managing-roles] ### Creating a Role [#creating-a-role] To create a new role: 1. On the **Administrators & roles** page, click the **+** button next to **Administrator role available** (its tooltip reads **Add new role**) 2. Enter the **Name (in lowercase)**, for example "manager" 3. Enter the **Display name** shown in the admin, for example "Manager", and a **Description** 4. Click **Save** 5. Open the new role with **View details**, click the **Permissions** tab and check the permissions the role needs. Each checkbox is saved as soon as you click it ### Role Fields [#role-fields] | Field | Description | |-------|-------------| | **Name (in lowercase)** | Internal name of the role, unique (e.g., "store_manager") | | **Display name** | Name shown in the admin (e.g., "Store Manager") | | **Description** | What this role is for | Permissions are not part of this form: you check them on the role's **Permissions** tab once the role exists. ### Updating a Role [#updating-a-role] Open the role with **View details**. The role page has three tabs: - **Role**: change the **Name (in lowercase)**, **Display name** and **Description**, then click **Update**. Editing the name fills the display name for you. On the Administrator role, a warning reminds you that a wrong change could block your access to the dashboard - **Users**: the staff members who have this role - **Permissions**: check or uncheck the permissions of the role A role you created can be removed with the **Delete** button at the top of its page. The Administrator and Manager roles that Shopper installs cannot be deleted. Changes apply immediately to all users with that role. ## Creating Permissions [#creating-permissions] Add custom permissions for your specific needs from a role's page. Two buttons at the top of the page, shown to **Administrator** accounts only, create permissions and give them to that role straight away: - **Create permission** opens the **New permission** window. Pick a **Group name** (optional), enter the **Permission name (in lowercase)** (up to 30 characters, unique), the **Display name** (up to 75 characters) and a **Description**, then click **Save** - **Generate permissions** creates the five standard permissions (browse, read, edit, add and delete) for one area in one go. Enter the **Resource name**, for example "shipments", pick a **Group name** if you want, check the list under **Permissions that will be created**, then click **Generate permissions** A new permission only controls something once your developer checks it in the admin or in a custom screen. Creating it does not restrict anything on its own. Creating or deleting a permission requires an **Administrator** account. Other staff members can still grant existing permissions to roles, but only permissions they hold themselves, and they cannot modify the Administrator role. ## Custom Permissions [#custom-permissions] Create permissions tailored to your business. Permissions created without a group appear under **Custom permission** on the role's **Permissions** tab. A permission made with **Create permission** has a trash icon that lets an Administrator delete it; the permissions Shopper installs and those made with **Generate permissions** cannot be deleted. ## Common Role Examples [#common-role-examples] ### Store Manager [#store-manager] Full operational access: - All product permissions - All order permissions - All customer permissions - **Access Setting** only if they manage the store settings, as it opens all of them at once ### Content Editor [#content-editor] Focus on catalog management: - View/edit products - View/edit categories - View/edit collections - No order or customer access ### Support Agent [#support-agent] Customer service focus: - Browse and read orders - Browse and read customers - Edit orders only if they handle order changes - No product management ### Marketing [#marketing] Promotional access: - View products - Manage discounts - Manage collections - No customer data access ## Best Practices [#best-practices] Begin with minimal permissions and add as needed. Create roles that match actual job functions. Audit roles periodically to ensure they're still appropriate. Keep clear descriptions of what each role can do. ## Permission Hierarchy [#permission-hierarchy] Some permissions may depend on others. For example, to edit a product, a user typically also needs the **Browse** permission to reach the product list. When assigning permissions, consider: 1. **Browse** - Can see the list 2. **Read** - Can open a record and see its details 3. **Add** - Can add new items 4. **Edit** - Can modify existing items 5. **Delete** - Can remove items (most sensitive) ## Security Considerations [#security-considerations] - **Know who has access** - The **Users** tab of each role lists its members. Shopper does not keep a history of who changed what - **Separation of duties** - Don't give one person all permissions - **Regular reviews** - Remove unnecessary access - **Test roles** - Verify permissions work as expected For developer details, see the [Roles & Permissions documentation](/2.x/acl). # Two-Factor Authentication (/2.x/user-guide/administration/two-factor) Two-factor authentication (2FA) adds an extra layer of security to your administrator account. Even if someone discovers your password, they won't be able to access your account without the second factor. ## What is Two-Factor Authentication? [#what-is-two-factor-authentication] 2FA requires two forms of verification: 1. **Something you know** - Your password 2. **Something you have** - A code from your phone This means an attacker would need both your password AND your phone to access your account. ## Enabling Two-Factor Authentication [#enabling-two-factor-authentication] ### Step 1: Access Security Settings [#step-1-access-security-settings] 1. Click your avatar at the top right of the header 2. Select **Personal Account** 3. Find the **Two Factor Authentication** section The section only appears when two-factor authentication is turned on for your store. If you do not see it, ask your developer to turn it on. ### Step 2: Start Setup [#step-2-start-setup] 1. Click **Enable Two Factor** 2. In the **Confirm Password** window, enter your password and click **Confirm** Two-factor authentication is turned on right away. The section now shows a QR code and your recovery codes. ### Step 3: Scan QR Code [#step-3-scan-qr-code] 1. Install an authenticator app on your phone: - Google Authenticator - Authy - Microsoft Authenticator - 1Password 2. Open the app and scan the QR code displayed on screen. The QR code is shown only now: to use a second device, scan it with that device too before you leave the page 3. The app generates a 6-digit code for your store ### Step 4: Verify Setup [#step-4-verify-setup] Shopper does not ask for a code at this point. Before you leave the page, check that your authenticator app shows a 6-digit code for your store: from your next login, you need it to sign in. ### Step 5: Save Recovery Codes [#step-5-save-recovery-codes] Below the QR code, Shopper shows 8 recovery codes. **Save these securely!** Each recovery code lets you sign in once if you lose your phone. To see them again later, click **Show Recovery Codes** in the **Two Factor Authentication** section. **Regenerate Recovery Codes** replaces all of them with new ones. Store your recovery codes in a safe place, like a password manager or a secure physical location. Don't store them on your phone. ## Logging In with 2FA [#logging-in-with-2fa] After enabling two-factor authentication: 1. Enter your email and password as usual 2. The **Authenticate Your Account** screen asks for a code 3. Open your authenticator app 4. Enter the 6-digit code in the **Code** field 5. Click **Login** To use a recovery code instead, click **Use a recovery code**. ## Disabling Two-Factor Authentication [#disabling-two-factor-authentication] If you need to disable 2FA: 1. Click your avatar at the top right, then **Personal Account** 2. Find the **Two Factor Authentication** section 3. Click **Disable** 4. If the **Confirm Password** window opens, enter your password and click **Confirm** Only disable 2FA temporarily if necessary. Re-enable it as soon as possible to maintain account security. ## Recovery Options [#recovery-options] ### Lost Your Phone? [#lost-your-phone] If you've lost access to your authenticator: 1. **Use a recovery code** - On the login screen, click **Use a recovery code** and enter one of your saved codes 2. **Contact your developer** - No screen in the admin turns off another administrator's 2FA, so your developer turns it off for your account 3. **Use backup device** - If you scanned the QR code with a second device during setup ### Recovery Codes [#recovery-codes] Each recovery code can only be used once. After using a code: - That code is no longer valid - Shopper replaces it with a new one: click **Show Recovery Codes** in your profile to save the updated list - Click **Regenerate Recovery Codes** if you think someone else has seen your codes ## Best Practices [#best-practices] Ask every staff member with admin access to turn on 2FA from their profile. Shopper does not force it. Store recovery codes separately from your password. Choose a reputable authenticator app. Set up 2FA on a backup device if possible. ## Recommended Authenticator Apps [#recommended-authenticator-apps] | App | Platform | Features | |-----|----------|----------| | **Google Authenticator** | iOS, Android | Simple, widely supported | | **Authy** | iOS, Android, Desktop | Cloud backup, multi-device | | **Microsoft Authenticator** | iOS, Android | Microsoft integration | | **1Password** | All platforms | Password manager integration | ## Troubleshooting [#troubleshooting] ### Code Not Working? [#code-not-working] - **Check the time** - Your phone's time must be accurate - **Try the next code** - Codes refresh every 30 seconds - **Use a recovery code** - If you can't generate valid codes ### Locked Out? [#locked-out] 1. Try using a recovery code 2. Ask your developer to turn off 2FA for your account 3. As a last resort, contact technical support For developer details, see the [Two-Factor Authentication documentation](/2.x/two-factor). # Managing Staff Users (/2.x/user-guide/administration/users) Staff users are the people who help manage your store. Shopper allows you to create multiple admin accounts with different levels of access. ## Overview [#overview] The Staff management section allows you to: - Add new administrators - See every staff account with its role and level of access - Assign roles and permissions - Delete the accounts of people who no longer need access ## Accessing Staff Settings [#accessing-staff-settings] 1. Click on **Settings** in the sidebar 2. Select **Staff & permissions** from the settings menu The page opens with the title **Administrators & roles**. The **Administrators accounts** table lists your staff: | Column | Description | |--------|-------------| | **Full Name** | The staff member's name and registration date. Your own row shows a **Me** badge | | **Email** | Login email address, with a green icon once it is verified | | **Role** | The role assigned to the staff member | | **Access** | **Full** for administrators, **Limited** for every other role | ## Adding a New Admin [#adding-a-new-admin] To add a new staff member: 1. Click the **Add administrator** button 2. Under **Login information**, enter the **Email address** and a **Password**, or click **Generate** to create one. Turn on **Send Invite** to email the login details to the new administrator 3. Under **Personal Information**, enter the **First name** and **Last Name**, and optionally the **Gender** and **Phone number** 4. Under **Role Information**, pick a role in **Choose a role for this admin** 5. Click **Save** The account can be used right away: its email address is marked as verified when you create it. ### Admin Fields [#admin-fields] | Field | Required | Description | |-------|----------|-------------| | **Email address** | Yes | Login email address (must not be used by another account) | | **Password** | Yes | Login password. **Generate** fills in a random 16-character password, and the eye icon shows it | | **Send Invite** | No | Sends the new administrator an email with their login information | | **First name** | Yes | Staff member's first name | | **Last Name** | Yes | Staff member's last name | | **Gender** | No | Male or Female | | **Phone number** | No | Contact phone number | | **Choose a role for this admin** | Yes | The role of this user, picked from a list of radio buttons | Only administrators can assign the **Administrator** role to a new team member. For other staff members, this role does not appear in the role choices. A warning in the form reminds you that the Administrator role gives the same rights and permissions as yours. ## Staff Roles [#staff-roles] Each staff member is assigned a role that determines what they can access: | Role | Typical Access | |------|----------------| | **Administrator** | Full access to all features. Installed with Shopper | | **Manager** | Installed with Shopper without any permission: give it the ones your managers need, for example everything except settings | | **Editor** | A role you create for product and content management | | **Support** | A role you create for orders and customer management | See [Roles & Permissions](/2.x/user-guide/administration/roles) to create roles and choose their permissions. Create roles that match your team structure. The principle of least privilege suggests giving users only the access they need for their job. ## Managing Existing Staff [#managing-existing-staff] ### Edit Staff Member [#edit-staff-member] The staff list has no edit action: you cannot change another person's name, email address, password or role after the account is created. Instead: - Each staff member updates their own details and password from their profile (see [Your Profile](#your-profile) below) - To change what someone can do, change the permissions of their role on the [Roles & Permissions](/2.x/user-guide/administration/roles) page. The change applies to everyone with that role ### Disable Staff Member [#disable-staff-member] Shopper has no option to disable a staff account and enable it again later. To stop someone from signing in, delete their account as described below. If they come back, add them again with **Add administrator**. ### Delete Staff Member [#delete-staff-member] Permanently remove a staff account: 1. Click the trash icon on the staff member's row in **Administrators accounts**. The same icon appears on the **Users** tab of each role 2. Confirm the deletion - Only administrators see the trash icon, and it never appears on an administrator's row - Use with caution - this cannot be undone ## Your Profile [#your-profile] Each staff member can manage their own profile. Click your avatar at the top-right of the header, then **Personal Account**: From your profile, you can: - Update personal information - Change your password - Enable two-factor authentication, when it is turned on for your store - See the devices signed in to your account and log out your other browser sessions ## Best Practices [#best-practices] Give each person their own account - never share credentials. Require strong passwords for all admin accounts. Encourage or require two-factor authentication. Periodically review who has access to your admin. ## Security Recommendations [#security-recommendations] 1. **Remove inactive accounts** - Delete the accounts of staff who leave 2. **Use role-based access** - Don't give everyone admin access 3. **Enable two-factor** - Add an extra layer of security 4. **Monitor activity** - Ask staff to check the devices signed in to their account from their profile and log out the sessions they don't recognize. Shopper does not keep a history of staff actions 5. **Regular password changes** - Encourage periodic password updates For developer details, see the [Roles & Permissions documentation](/2.x/acl). # Managing Attributes (/2.x/user-guide/catalog/attributes) Attributes define the characteristics of your products. They're essential for creating product variants and helping customers filter and compare products. ## Overview [#overview] Attributes describe product properties such as: - **Size** - Small, Medium, Large, XL - **Color** - Red, Blue, Green, Black - **Material** - Cotton, Polyester, Leather - **Storage** - 64GB, 128GB, 256GB ## Accessing Attributes [#accessing-attributes] 1. Click on **Products** in the sidebar 2. Select **Attributes** from the submenu ## Creating an Attribute [#creating-an-attribute] To create a new attribute: 1. Click the **Create** button 2. Fill in the attribute details in the **New attribute** panel 3. Click **Save** The form has no values. Once the attribute is saved, you add its values from the list (see [Attribute Values](#attribute-values)). ### Attribute Fields [#attribute-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The attribute name (e.g., "Color", "Size"), up to 75 characters | | **Slug** | Auto | Generated from the name. It cannot be edited. | | **Type** | Yes | The kind of field used to fill in the attribute (see below) | | **Icon** | No | An icon shown next to the attribute in the list | | **Description** | No | Explain what this attribute represents, up to 100 characters | | **Enable** | No | Toggle to make the attribute visible to customers | | **Is Searchable** | No | Use this attribute to search and filter products | | **Is Filterable** | No | Use this attribute as a filter on your storefront | ### Attribute Types [#attribute-types] The type sets how the attribute is filled in on each product: | Type | Best For | |------|----------| | **Select** | One value per product from a list you define (e.g., size) | | **Checkbox** | Several values per product from a list you define (e.g., features) | | **Color picker** | Several colors per product, each value picked with a color picker | | **Text field (input)** | A short text typed on each product | | **Text field (number)** | A number typed on each product (e.g., storage in GB) | | **Rich text** | Formatted text written on each product (e.g., care instructions) | | **Date picker** | A date picked on each product (e.g., release date) | ## Attribute Values [#attribute-values] Only **Select**, **Checkbox** and **Color picker** attributes have a list of values. After saving one of them: 1. Click **Values** on the attribute's row in the list 2. In the **Attribute values** panel, click **New Value** 3. Fill in the **Key** (a short identifier in slug format; for a color, the color itself) and the **Value** (the name shown for this value) 4. Repeat for each value Examples of values: | Attribute | Example Values | |-----------|----------------| | Size | XS, S, M, L, XL, XXL | | Color | Red, Blue, Green, Yellow, Black, White | | Material | Cotton, Wool, Polyester, Silk | ## Using Attributes on Products [#using-attributes-on-products] Once created, attributes can be assigned to products: Attributes enable you to: - Create product variants (e.g., a shirt in multiple sizes) - Allow customers to filter products - Compare products with similar attributes ## Common Attribute Examples [#common-attribute-examples] ### Fashion / Apparel [#fashion--apparel] | Attribute | Values | |-----------|--------| | Size | XS, S, M, L, XL | | Color | Various colors | | Material | Cotton, Polyester, etc. | | Fit | Slim, Regular, Loose | ### Electronics [#electronics] | Attribute | Values | |-----------|--------| | Storage | 64GB, 128GB, 256GB | | Color | Black, White, Silver | | Memory | 4GB, 8GB, 16GB | ### Food & Beverages [#food--beverages] | Attribute | Values | |-----------|--------| | Weight | 250g, 500g, 1kg | | Flavor | Vanilla, Chocolate, etc. | ## Best Practices [#best-practices] Create attributes before adding products. It's easier to set up your attribute structure first and then assign them to products. - **Be consistent** - Use the same attribute names across similar products - **Keep it simple** - Only create attributes that help customers make decisions - **Use clear names** - Attribute names should be instantly understandable - **Order logically** - Arrange values in a logical order (S, M, L, not M, S, L) For developer details, see the [Attributes documentation](/2.x/attributes). # Managing Brands (/2.x/user-guide/catalog/brands) Brands help customers identify and find products from their favorite manufacturers. Managing brands effectively can improve navigation and boost customer trust. ## Overview [#overview] Brands in Shopper represent the manufacturers or labels of your products. They help customers: - Filter products by manufacturer - Find all products from a specific brand - Make informed purchasing decisions ## Accessing Brands [#accessing-brands] Click on **Brands** in the sidebar to access the brand management page. ## Creating a Brand [#creating-a-brand] To add a new brand to your store: 1. Click the **New brand** button on the Brands page 2. Fill in the brand details 3. Click **Save** to create the brand ### Brand Fields [#brand-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The brand name as it will appear to customers | | **Website** | No | The brand's official website URL | | **Visibility** | No | Toggle to show or hide the brand on your store. Off by default. | | **Description** | No | A brief description of the brand | | **Image preview** | No | In the **Media** section, upload a logo image for the brand | | **Metadata** | No | In the **Metadata** section, extra key and value pairs your developer can use on the storefront | ### SEO Settings [#seo-settings] Optimize your brand pages for search engines in the **SEO** section: | Field | Description | |-------|-------------| | **Title** | Custom title for search engine results. Keep it under 60 characters so it is not cut off. | | **Description** | Meta description for search engines (max 160 characters) | ## Brand States [#brand-states] Brands can be in two states: - **Visibility** on - Visible to customers and offered in the **Brand** field of the product form - **Visibility** off - Marked as hidden for customers and no longer offered in the product **Brand** field. Products already linked keep their brand. New brands are hidden until you turn on **Visibility**, which is off by default. Turn it off later to hide a brand temporarily without removing product associations. ## Empty State [#empty-state] When you first access the Brands page with no brands created, you'll see a helpful empty state prompting you to create your first brand. ## Displaying Brands on Your Store [#displaying-brands-on-your-store] The starter kits show the brand name on each product card. A list of brands or a page per brand depends on your storefront: ask your developer if you want one. ## Best Practices [#best-practices] - **Use official logos** - Always use the official brand logo when available - **Keep descriptions concise** - A brief description helps customers understand what the brand offers - **Optimize for SEO** - Add relevant keywords to help customers find brands through search - **Regular updates** - Keep brand information current, especially for websites and descriptions For developer details, see the [Brands documentation](/2.x/brands). # Managing Categories (/2.x/user-guide/catalog/categories) Categories are essential for organizing your product catalog. They help customers navigate your store and find products easily. ## Overview [#overview] Categories create a hierarchical structure for your products. You can create: - **Parent categories** - Top-level categories (e.g., "Clothing", "Electronics") - **Subcategories** - Nested categories (e.g., "Men's Shirts" under "Clothing") ## Accessing Categories [#accessing-categories] Click on **Categories** in the sidebar to access the category management page. ## Creating a Category [#creating-a-category] To add a new category: 1. Click the **New category** button on the Categories page 2. Fill in the category details 3. Click **Save** to create the category ### Category Fields [#category-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The category name displayed to customers | | **Parent** | No | Select a parent to create a subcategory. Only visible categories are listed. Leave it empty for a top-level category. | | **Visibility** | No | Toggle to show or hide the category. Off by default. | | **Description** | No | Detailed description of the category | | **Image preview** | No | In the **Media** section, a representative image for the category | | **Metadata** | No | In the **Metadata** section, extra key and value pairs your developer can use on the storefront | ### SEO Settings [#seo-settings] Improve your category pages visibility in search engines in the **SEO** section: | Field | Description | |-------|-------------| | **Title** | Custom title for search results | | **Description** | Meta description for the category page (max 160 characters) | ## Category Hierarchy [#category-hierarchy] Categories can be nested to create a logical structure: ``` Electronics ├── Computers │ ├── Laptops │ └── Desktops ├── Phones │ ├── Smartphones │ └── Accessories └── Audio ├── Headphones └── Speakers ``` To create a subcategory: 1. Create a new category 2. Select the parent category in the **Parent** field 3. Save the category ## Managing Category Order [#managing-category-order] Categories can be reordered to control how they appear in navigation: 1. Click the **Reorder** button above the category list 2. In the **Reorder** panel, drag categories by their handle into the order you want. Dropping a category inside another one also changes its parent. 3. Each move is saved as soon as you drop it. Click **Close** when you are done. Position determines the display order on your storefront. ## Category States [#category-states] - **Visibility** on - Visible to customers and appears in navigation - **Visibility** off - Hidden from customers, and no longer offered in the product **Categories** field or the **Parent** field. Products already in the category stay categorized. Create a clear and logical category structure from the start. Reorganizing categories later may affect URLs and SEO. ## Best Practices [#best-practices] Don't create too many levels. 2-3 levels deep is usually sufficient. Category names should be descriptive and match what customers search for. Visual categories help customers navigate faster. Think about your full product range before creating the category structure. For developer details, see the [Categories documentation](/2.x/categories). # Managing Collections (/2.x/user-guide/catalog/collections) Collections allow you to group products together for marketing and merchandising purposes. Unlike categories, collections are flexible groupings that can include products from different categories. ## Overview [#overview] Collections are useful for: - **Seasonal promotions** - "Summer Collection", "Holiday Gifts" - **Marketing campaigns** - "Best Sellers", "New Arrivals" - **Thematic groupings** - "Eco-Friendly Products", "Made in France" ## Accessing Collections [#accessing-collections] Click on **Collections** in the sidebar to access collection management. ## Creating a Collection [#creating-a-collection] To create a new collection: 1. Click the **New collection** button 2. Fill in the collection details and choose the **Collection Type** 3. Click **Save**. The collection's edit page opens. 4. Add products to the collection: click **Browse** above the product list for a manual collection, or **Conditions** for an automatic one (see [Automatic Collections](#automatic-collections)) On the edit page, click **Update** to save changes to the collection details. ### Collection Fields [#collection-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The collection name | | **Availability** | Yes | The date and time the collection becomes available on your store. Defaults to now; set a later date to schedule it. | | **Collection Type** | Yes | **Manual** or **Automatic** (condition-based). It cannot be changed after the collection is created. | | **Zones** | No | Limit the collection to the selected zones | | **Description** | No | Describe what this collection represents | | **Image preview** | No | In the **Media** section, a cover image for the collection | | **Title** and **Description** | No | In the **SEO** section, how the collection page appears in search engine results | | **Metadata** | No | In the **Metadata** section, extra key and value pairs your developer can use on the storefront | ## Collection Types [#collection-types] ### Manual Collections [#manual-collections] Manually select which products belong to the collection: - Full control over which products are included - Products stay in the collection until you remove them - Best for curated selections ### Automatic Collections [#automatic-collections] Use conditions to include products automatically. On the collection's edit page, click **Conditions** above the product list to open the **Product conditions** panel: 1. Under **Products must match**, choose **All conditions** or **Any condition** 2. For each condition, pick a rule in **Choose a rule**, an operator in **Select operator**, then fill in the **Value** 3. Click **Add condition** to add another one 4. Click **Save** Available rules: | Rule | Example | |------|---------| | **Product title** | Contains "organic" | | **Product brand** | Equals to "Nike" | | **Product category** | Contains "Shoes" | | **Product price** | Greater than 50 | | **Compare at price** | Greater than 0 (products shown with a former price) | | **Inventory stock** | Greater than 5 | | **Product created date** | Greater than a date you pick | | **Product featured** | Equals to Yes | | **Product rating** | Greater than 3 | | **Product sales count** | Greater than 100 | The product list of an automatic collection is filled when you save its conditions. Products you add or change afterwards join or leave the list the next time you click **Save** in the **Product conditions** panel. On the starter kits, the collection page checks the conditions each time it loads, so matching products show there right away. ## Collection Preview [#collection-preview] On the starter kits, each collection has its own page with a breadcrumb, the collection title and description, then its products. The page is available once the **Availability** date has passed. ## Collections on Storefront [#collections-on-storefront] The starter kit home page has a **Shop by Collections** section that shows three collections, the ones with the most products, each linking to its collection page. There is no page listing all collections. ## Use Cases [#use-cases] Create an automatic collection with a **Product created date** condition, Greater than the date your new season starts. Group all discounted products for easy customer access. Manually curate products perfect for gifting occasions. Highlight your most popular products. ## Best Practices [#best-practices] - **Update regularly** - Keep seasonal collections fresh and relevant - **Use compelling images** - Collection images should be eye-catching - **Write descriptions** - Help customers understand what makes the collection special - **Feature on homepage** - Use collections to drive traffic to key products For developer details, see the [Collections documentation](/2.x/collections). # Creating a Product (/2.x/user-guide/catalog/products/creating-product) Creating a product in Shopper is done through a guided wizard that walks you through each step. The process is the same for all product types, with some steps adapting based on the type you choose. ## Starting the Wizard [#starting-the-wizard] From the Products page, click the **New product** button to open the product creation wizard. ## Step 1: Choose the Product Type [#step-1-choose-the-product-type] The first step asks you to select the type of product you want to create. Each type is presented as a card with an icon and a description to help you make the right choice. The available types are: - **Standard**. Physical products that require shipping - **Virtual**. Digital products (downloads, subscriptions, courses) - **External**. Dropshipping products fulfilled by a third party - **Variant**. Products with multiple options (size, color, material) If your store only sells one type of product, select it and turn on **Set as default product type** below the cards. The type is saved for the next products you create, and the wizard then opens directly on the General Information step. You can still go back to this step to pick another type or turn the toggle off. Changing this toggle requires access to the store settings. Select your product type and click **Next** to continue. ## Step 2: General Information [#step-2-general-information] This step collects the core information about your product. | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The product name displayed to customers. A URL-friendly slug is generated automatically. | | **Slug** | Yes | Filled in from the name. You cannot type in this field. | | **Summary** | No | A short description shown in product listings and cards. | | **Description** | No | The full product description with rich formatting (bold, lists, links, etc.). | | **Visible** | No | On by default. Turn it off to hide the product from all sales channels. Useful to prepare products before launching. | | **Availability** | Yes | The date and time when the product becomes available. It defaults to now and cannot be earlier than one hour ago. Pick a future date to schedule the publication. | The **Name** field automatically generates a URL slug (e.g., "Blue Running Shoes" becomes `blue-running-shoes`). The slug cannot be edited, and it stays the same if you rename the product later. ## Step 3: Associations [#step-3-associations] Link your product to the organizational structures of your store. This step only appears when your store uses brands, categories or collections. | Field | Description | |-------|-------------| | **Brand** | Associate the product with a brand. Only enabled brands are listed. Hidden if your store does not use brands. | | **Categories** | Assign one or more categories from the category tree. You can select a parent category or any of its subcategories. Only enabled categories are listed. | | **Sales channels** | Choose which sales channels this product appears on (e.g., web store, mobile app, POS). Only enabled channels are listed, and your default channel is selected for you. | | **Collections** | Add the product to one or more collections. | You can always update associations after creation. If you haven't set up categories or brands yet, you can skip this step and come back later. ## Step 4: Media [#step-4-media] Upload images to showcase your product. | Element | Description | |---------|-------------| | **Thumbnail** | The main image shown in product listings, search results, and cards. Upload one image. | | **Images** | Additional images shown on the product detail page. Upload multiple images for different angles or details. | **Image best practices:** - Use high-resolution images (minimum 800x800px recommended) - Keep a consistent aspect ratio across products - Show the product from multiple angles - Use a clean background for the thumbnail ## Step 5: Stock & Inventory [#step-5-stock--inventory] Set up the initial inventory information for your product. | Field | Required | Description | |-------|----------|-------------| | **SKU** | No | Stock Keeping Unit, a unique identifier for your product in your inventory system. Two products cannot share the same SKU. | | **Barcode** | No | The product barcode (UPC, EAN, ISBN, etc.) for scanning and identification. Letters, numbers and hyphens only, unique per product. | | **Quantity** | No | The initial stock quantity available for sale. It is added to your default inventory location. | | **Safety Stock** | No | The minimum stock level you want to keep before reordering. Shopper saves this number with the product but does not send a notification when stock reaches it. | This step also appears for **Variant** products. What you enter here applies to the parent product. Each variant (per size/color combination) gets its own SKU, barcode and stock, which you set when you create the variants after saving. This step also appears for **Virtual** and **External** products. You can leave it empty when there's no physical stock to manage. ## Completing the Creation [#completing-the-creation] After filling in all the steps, click **Save** to create your product. You'll be redirected to the product detail page where you can: - Configure pricing - Set up shipping dimensions (Standard & Variant products) - Add product attributes (Standard, Virtual & Variant products) - Upload digital files (Virtual products) - Generate variants (Variant products) - Optimize SEO settings - Link related products ## What's Next? [#whats-next] Depending on your product type, continue with the specific guide: Configure shipping, attributes, and inventory for physical goods. Upload digital files and configure access for downloadable products. Set up dropshipping product details and supplier information. Create variants from attribute combinations like size and color. # External Product (Dropshipping) (/2.x/user-guide/catalog/products/external-product) An external product is an item listed in your store but **fulfilled and shipped by a third-party supplier**. You don't hold inventory. When a customer places an order, the supplier handles storage, packing, and shipping directly to the customer. This is the foundation of a **dropshipping** business model. ## When to Use External Products [#when-to-use-external-products] Use the External product type when: - **Dropshipping**. You sell products that a supplier ships directly to your customers - **Affiliate products**. You list products from another store and earn a commission - **Marketplace model**. You curate products from multiple vendors in your catalog - **Print-on-demand**. Items are printed and shipped by a third-party service - **Made-to-order**. Products manufactured by a partner after the order is placed ## How Dropshipping Works with Shopper [#how-dropshipping-works-with-shopper] The typical dropshipping flow with External products: 1. You list the product in your store with your own pricing and branding 2. A customer places an order on your store 3. You forward the order to your supplier 4. The supplier ships the product directly to your customer 5. You keep the profit margin (your price minus supplier cost) ## What Makes External Products Unique [#what-makes-external-products-unique] External products have the most simplified configuration since fulfillment is handled externally: | Feature | Available | Notes | |---------|-----------|-------| | **Shipping** | No | Handled by the supplier | | **Inventory tracking** | No | Managed by the supplier | | **Attributes** | No | Product specs come from the supplier | | **Variants** | No | Create separate external products for each option | | **Digital files** | No | Not applicable | | **Pricing** | Yes | Set your retail price (markup over supplier cost) | | **SEO** | Yes | Optimize for your store's search visibility | | **Categories & collections** | Yes | Organize in your catalog as usual | | **Media** | Yes | Use supplier images or your own product photos | ## Configuring an External Product [#configuring-an-external-product] After creating an external product through the [creation wizard](/2.x/user-guide/catalog/products/creating-product), the configuration focuses on: ### Pricing Strategy [#pricing-strategy] The key to dropshipping profitability is your pricing: | Field | Description | |-------|-------------| | **Price** | Your retail selling price (what the customer pays) | | **Compare at price** | Optional higher price to show a deal | | **Cost per item** | The supplier's price (your cost). The difference is your profit margin. | **Example pricing calculation:** - Supplier price (cost): $25.00 - Your retail price: $59.99 - Compare at price: $79.99 - **Your profit margin: $34.99 per sale** A common dropshipping markup is 2x to 3x the supplier cost. Research competitor pricing to find the sweet spot between competitiveness and profitability. ### Product Information [#product-information] Even though the product is fulfilled externally, you should provide: - **Compelling descriptions**. Write unique descriptions rather than copying the supplier's text. This helps SEO and builds customer trust. - **Quality images**. Use high-resolution product photos. Request sample products from your supplier for original photography when possible. - **Accurate details**. Ensure your product descriptions match what the supplier actually ships. ## Example: Creating a Dropshipping Product [#example-creating-a-dropshipping-product] Let's create a "Minimalist Wooden Watch" from a dropshipping supplier: 1. **Type**: Select "External Product" 2. **General info**: Name it "Minimalist Wooden Watch, Natural Bamboo", write a unique product description that highlights craftsmanship and sustainability 3. **Associations**: Brand "EcoTime" (your private label), category "Accessories > Watches", collection "Eco-Friendly" 4. **Media**: Upload supplier product photos (front, side, on wrist, packaging) 5. **Stock**: Skip, supplier manages inventory After creation: - **Pricing**: Price $89.00, compare at $129.00, cost $28.00 (supplier price) - **SEO**: Title "Bamboo Wood Watch - Eco-Friendly Minimalist Timepiece" - **Related products**: Link to other watches and accessories in your store ## Managing Supplier Relationships [#managing-supplier-relationships] While Shopper handles the storefront, you'll manage supplier relationships outside the platform: | Aspect | Your Responsibility | |--------|---------------------| | **Order forwarding** | Send customer orders to your supplier | | **Inventory sync** | Check supplier stock availability regularly | | **Shipping times** | Communicate realistic delivery times to customers | | **Returns** | Coordinate returns between customer and supplier | | **Quality control** | Order samples to verify product quality | Always verify supplier reliability before listing products. Order samples, check shipping times, and ensure quality meets your standards. Your brand reputation depends on the supplier's execution. ## Dropshipping Best Practices [#dropshipping-best-practices] Write original product descriptions. Avoid copying supplier text. It hurts SEO and looks generic. Be transparent about delivery times, especially for international suppliers. Order the product yourself before listing it. Verify quality, packaging, and shipping speed. Account for marketing costs, returns, and refunds when setting your markup. ## Differences from Other Product Types [#differences-from-other-product-types] | Aspect | Standard | External (Dropshipping) | |--------|----------|-------------------------| | Inventory | You manage stock | Supplier manages stock | | Shipping | You ship to customer | Supplier ships to customer | | Upfront investment | Buy inventory first | No inventory needed | | Profit margins | Higher (you control costs) | Lower (supplier sets costs) | | Fulfillment speed | Under your control | Depends on supplier | | Quality control | You inspect products | Limited visibility | | Risk | Unsold inventory | Supplier reliability | # Managing Products (/2.x/user-guide/catalog/products/managing-products) After creating a product, you can manage all its details from the product edit page. This guide covers the common management tasks available for all product types. ## Product Edit Page [#product-edit-page] Click on any product from the products list to open its edit page. The page is organized into tabs based on your product type: **Overview**, **Media**, **Pricing** (all types except Variant), **Files** (Virtual), **Attributes** (Standard, Virtual and Variant), **Variants** (Variant), **Stock & Inventory**, **Shipping** (Standard and Variant), **SEO** and **Related Products**. ## Pricing [#pricing] The pricing section lets you configure your product's price, comparison price, and cost. If your store supports multiple currencies, you can set prices in each currency. | Field | Description | |-------|-------------| | **Price amount** | The regular selling price shown to customers. Required when you fill in **Compare at price**. | | **Compare at price** | The original price displayed with a strikethrough to indicate a discount. Leave empty if the product is not on sale. | | **Cost per item** | Your cost to acquire or produce the item. Used for profit margin calculations and not visible to customers. | Click **Add new price** to open the **Product pricing** panel, fill in the fields and click **Save**. The prices you set are listed per currency in the **Product pricing** table. To change a price, click **Edit** on its row: the panel then shows only that currency. ### Multi-Currency Pricing [#multi-currency-pricing] If you have multiple currencies configured in your store: - Each currency has its own set of price fields in the **Product pricing** panel - The **Add new price** button only shows while at least one of your store currencies has no price yet - Set appropriate prices for each market (don't just convert; consider local pricing strategies) - The customer sees the price in their local currency based on your store's currency detection For variant products, pricing is set at the variant level. The parent product doesn't have its own price. Each variant can have a different price. ### Pricing Strategies [#pricing-strategies] | Strategy | How to configure | |----------|-----------------| | **Fixed price** | Set only the "Price amount" field | | **Sale price** | Set "Price amount" lower than "Compare at price" | | **Cost-plus** | Fill "Cost per item" to track margins, set "Price amount" with your desired markup | | **Anchor pricing** | Set a high "Compare at price" to make the actual price feel like a deal | ## Media Management [#media-management] Manage your product's visual content, including thumbnail and gallery images. ### Thumbnail [#thumbnail] The thumbnail is your product's primary image. It appears in: - Product listings and search results - Shopping cart and checkout - Order confirmations and invoices ### Product Gallery [#product-gallery] Additional images shown on the product detail page: - Upload multiple images for different angles - Upload them in the order you want them shown, as the gallery has no drag and drop reordering - Delete images you no longer need **Image recommendations:** - Minimum resolution: 800x800 pixels - Consistent aspect ratio across products (square works best for most stores) - Clean white or neutral background for the thumbnail - Lifestyle and detail shots for gallery images ## SEO Optimization [#seo-optimization] Optimize your product pages for search engines to drive organic traffic. | Field | Description | Best practice | |-------|-------------|---------------| | **Title** | The title shown in search engine results | Keep under 60 characters. Include the product name and a key benefit. | | **Description** | The meta description shown below the title in search results. Limited to 160 characters. | Describe the product and include a call to action. | | **Metadata** | Extra key and value pairs saved with the product. Click **Add row** to add a pair. | Only fill it in if your storefront is built to read these keys. Ask your developer which ones it uses. | Click **Update** to save. Next to the form, a preview shows how the product can appear in search results, including its URL. The URL ends with the product slug, which is created from the product name when you create the product and cannot be edited. Choose a clear product name from the start, since renaming the product later does not change the slug. ### SEO Tips [#seo-tips] - **Include keywords** naturally in the title and description. Think about what customers search for - **Be specific**. "Red Leather Crossbody Bag" is better than "Nice Bag" - **Add a call to action** in the meta description, such as "Shop now", "Free shipping", "Limited edition" - **Avoid duplicate content**. Each product should have unique SEO text If left empty, search engines will use your product name as the title and pull text from your description. It's always better to set these explicitly for optimal results. ## Related Products [#related-products] Link related products to encourage customers to explore more of your catalog and increase average order value. ### Adding Related Products [#adding-related-products] 1. Open the **Related Products** tab on your product. Its section is titled **Similar Products** 2. Click **Add product** (or **New product** if the product has no related products yet) 3. In the **Add Similar Products** panel, search for published products, select them and click **Add Selected Products** 4. Related products appear on the product detail page on your storefront To unlink a product, click **Remove** on its card and confirm. ### When to Use Related Products [#when-to-use-related-products] | Use case | Example | |----------|---------| | **Complementary items** | Shoes: shoe cleaner, laces, socks | | **Same category** | Blue dress: other dresses in similar style | | **Frequently bought together** | Phone: phone case, screen protector | | **Upsell** | Basic model: premium model of the same product | | **Accessories** | Camera: lens, tripod, bag | ## Visibility & Publishing [#visibility--publishing] Control when and where your product is visible. Both settings are in the **Product availability** section of the **Overview** tab. ### Visibility Toggle [#visibility-toggle] - **Visible**: Product appears on your storefront and in search results - **Hidden**: Product exists in the admin but is not shown to customers Use hidden mode to: - Prepare products before a launch - Temporarily remove seasonal items - Hide products being updated or photographed ### Publication Date [#publication-date] The **Availability** date controls when the product goes live: - **Past or current date**: Product is immediately available (if visible) - **Future date**: Product is scheduled and will become available at that date and time Combine a future publication date with "Visible" to schedule product launches. The product won't appear until the scheduled date. ## Channels [#channels] If your store uses multiple sales channels, you can control which channels a product appears on with the **Sales channels** field, in the **Associations** section of the **Overview** tab. It lists the enabled channels of your store, for example: - **Web store**. Your main online store - **Mobile app**. If you have a mobile shopping app - **POS**. Point of sale / in-store - **Marketplace**. Third-party marketplace listings Each product can be assigned to one or more channels. ## Product on Storefront [#product-on-storefront] Here's how a fully configured product appears to customers: --- ## Common Actions [#common-actions] | Action | How | |--------|-----| | **Edit product info** | Click on the product, modify fields, click **Update** | | **Change visibility** | Toggle the **Visible** switch in the **Overview** tab, click **Update** | | **Update stock** | Go to the **Stock & Inventory** tab, click **Add stock** | | **Update pricing** | Go to the **Pricing** tab, click **Edit** on a price, save | | **Delete product** | Click **Delete** at the top of the product page, or on its row in the products list (irreversible) | | **Duplicate product** | There is no duplicate action. Click **New product** and fill in the details again | Deleting a product cannot be undone from the admin. It also removes the product's images, prices and stock history. Consider hiding the product instead if you might need it again. For developer details, see the [Products documentation](/2.x/products). # Overview (/2.x/user-guide/catalog/products/overview) Products are the core of your e-commerce store. Shopper supports multiple product types to cover a wide range of selling scenarios, from physical goods to digital downloads and dropshipping. ## Accessing Products [#accessing-products] Click on **Products** in the sidebar to access the product management page. Here you can see all your products, filter by name, type, availability, or publication date, and quickly access any product for editing. If you haven't created any products yet, you'll see an empty state with a button to create your first product. ## Product Types [#product-types] Shopper offers four product types, each designed for a specific selling scenario. When creating a product, you'll choose the type that best fits what you're selling. Physical goods that require shipping. This is the most common product type for stores selling tangible items like clothing, electronics, or furniture. Digital products that don't require shipping. Ideal for downloadable files, software licenses, online courses, or subscriptions. Products fulfilled by a third-party supplier. Perfect for dropshipping, where you sell products without holding inventory. Products with multiple options like size, color, or material. Each combination becomes a separate variant with its own price, stock, and SKU. ## Choosing the Right Type [#choosing-the-right-type] | What you're selling | Recommended type | |---------------------|------------------| | Physical items you stock and ship yourself | **Standard** | | Digital files (ebooks, music, software) | **Virtual** | | Online courses or memberships | **Virtual** | | Items shipped directly by a supplier | **External** (Dropshipping) | | A t-shirt in multiple sizes and colors | **Variant** | | A single unique handmade item | **Standard** | | Affiliate products from another store | **External** (Dropshipping) | | A phone case in 10 colors | **Variant** | The product type is set during creation and cannot be changed afterward. Make sure to choose the correct type before proceeding. ## Type Capabilities [#type-capabilities] Not all features are available for every product type. Here's what each type supports: | Feature | Standard | Virtual | External | Variant | |---------|----------|---------|----------|---------| | Shipping & dimensions | Yes | No | No | Yes | | Inventory tracking | Yes | Yes | Yes | Yes (per variant) | | Product attributes | Yes | Yes | No | Yes | | Variants (size, color...) | No | No | No | Yes | | Digital file downloads | No | Yes | No | No | | Pricing | Yes | Yes | Yes | Yes (per variant) | | SEO | Yes | Yes | Yes | Yes | | Categories & collections | Yes | Yes | Yes | Yes | | Related products | Yes | Yes | Yes | Yes | | Media (images) | Yes | Yes | Yes | Yes | ## What's Next? [#whats-next] Follow the step-by-step wizard to create your first product. Learn how to edit pricing, SEO, media, and more after creation. For developer details, see the [Products documentation](/2.x/products). # Standard Product (/2.x/user-guide/catalog/products/standard-product) A standard product is the most common product type in e-commerce. It represents a **physical item** that you stock in your warehouse and ship to customers. Examples include clothing, electronics, books, furniture, food items, or any tangible goods. ## When to Use Standard Products [#when-to-use-standard-products] Use the Standard product type when: - You sell a physical item that needs to be shipped - The product does not have variations (no size/color options) - You manage inventory for this product - The product has weight and dimensions for shipping calculations If your physical product comes in multiple options (different sizes, colors, materials), use the [Variant Product](/2.x/user-guide/catalog/products/variant-product) type instead. ## What Makes Standard Products Unique [#what-makes-standard-products-unique] After creating a Standard product through the [creation wizard](/2.x/user-guide/catalog/products/creating-product), you have access to these additional features: | Feature | Description | |---------|-------------| | **Shipping** | Configure weight and package dimensions for carrier calculations | | **Attributes** | Add product characteristics (material, care instructions, etc.) | | **Inventory** | Track stock levels per location with a full history, and record a safety stock level | | **Pricing** | Set prices in multiple currencies with compare-at and cost prices | ## Configuring Shipping [#configuring-shipping] The shipping section lets you define the physical characteristics of your product for accurate shipping rate calculations. | Field | Description | |-------|-------------| | **Width** | Package width with unit selection (m, cm, mm, ft, in). Default unit: cm | | **Height** | Package height with unit selection (m, cm, mm, ft, in). Default unit: cm | | **Weight** | Package weight with unit selection (kg, g, lbs). Default unit: kg | | **Volume** | Package volume, entered by hand, with unit selection (l, ml, gal, floz). Default unit: ml | | **Depth** | Package depth with unit selection (m, cm, mm, ft, in). Default unit: cm | These fields are in the **Package dimension** section of the **Shipping** tab. Click **Update** to save them. Accurate weight and dimensions are essential for calculating shipping costs with carriers. Measure your product when packaged, not just the item alone. ## Managing Attributes [#managing-attributes] Attributes let you add structured information about your product's characteristics. This is useful for displaying product specs on your storefront or enabling filtering in your catalog. Common attributes for standard products: - **Material**. Cotton, polyester, leather, wood, metal - **Color**. When it's a single-color product without variants - **Care instructions**. Machine washable, hand wash only - **Country of origin**. Where the product is manufactured - **Warranty**. Duration and coverage details To add attributes: 1. Open your product's **Attributes** tab 2. Click **Choose attributes**. The button only shows once your store has at least one attribute 3. In the **Attributes** step of the panel, select one or more attributes from your attribute library, then go to the next step 4. In the **Values** step, set the value for this product. Attributes with predefined values show a list to pick from; the others show a field where you type the value 5. Click **Save** Attributes must be created first in the [Attributes](/2.x/user-guide/catalog/attributes) section before they can be assigned to products. ## Inventory Management [#inventory-management] The **Stock & Inventory** tab shows your current stock levels and provides a complete history of stock movements. It has two sections: **Inventory attributes** and **Stock management**. ### Stock Information [#stock-information] | Field | Description | |-------|-------------| | **SKU** | Your internal stock keeping unit identifier | | **Barcode** | Product barcode for scanning (UPC, EAN, ISBN) | | **Safety Stock** | The minimum stock level you want to keep before reordering. No notification is sent when stock reaches it. | These fields are in the **Inventory attributes** section. Click **Update** to save them. The current stock, the total available quantity across all locations, shows as **Total** in the **Summary** row at the bottom of the stock history table. ### Adding Inventory [#adding-inventory] You can manually adjust stock levels by adding or removing inventory: 1. Click **Add stock** in the **Stock management** section 2. In **Inventory name**, select the inventory location 3. In **Quantity**, enter the quantity to add (positive, for example 50) or remove (negative, for example -5) 4. Click **Submit**. The stock history records this adjustment with a timestamp ### Stock History [#stock-history] Every stock movement is a row in the history table, with these columns: - **Date**: when the change happened - **Event**: the reason for the change, such as "Initial inventory", "Manually added", "Manually removed", "Reserved for order" or "Released from cancelled order" - **Inventories**: the location where the stock changed - **Adjustment** and **Quantity Movement**: the quantity added or removed The table does not show which team member made a change. You can filter the history by location, or group it by **Inventories**. ## Pricing [#pricing] Configure how much your product costs. See [Managing Products](/2.x/user-guide/catalog/products/managing-products) for detailed pricing configuration. ## Example: Creating a Standard Product [#example-creating-a-standard-product] Let's walk through creating a "Leather Messenger Bag": 1. **Type**: Select "Standard" 2. **General info**: Name it "Leather Messenger Bag", add a description highlighting the craftsmanship and features 3. **Associations**: Assign to brand "Heritage Craft", category "Bags > Messenger Bags", collection "New Arrivals" 4. **Media**: Upload photos from multiple angles (front, back, inside, strap detail) 5. **Stock & Inventory**: SKU `BAG-LEATH-001`, initial quantity 50, safety stock 10 After creation: - **Shipping**: Weight 1.2 kg, dimensions 40x30x10 cm - **Attributes**: Material "Full grain leather", Color "Brown", Origin "Italy" - **Pricing**: $189.00, compare at $229.00, cost $85.00 - **SEO**: Title "Leather Messenger Bag - Heritage Craft", description with keywords ## Best Practices [#best-practices] Always measure packed products for accurate shipping calculations. Set a safety stock level and check your stock against it, so you reorder before you run out. Add relevant attributes to help customers make informed decisions. Show your product from every angle. Customers can't touch it online. # Variant Product (/2.x/user-guide/catalog/products/variant-product) A variant product is a **physical item that comes in multiple options**. Instead of creating separate products for each size or color, you create one parent product and generate variants for every combination. Each variant has its own SKU, price, stock level, and image. ## When to Use Variant Products [#when-to-use-variant-products] Use the Variant product type when: - A product comes in **multiple sizes** (S, M, L, XL, XXL) - A product is available in **different colors** (Red, Blue, Black) - A product has **different materials** (Cotton, Polyester, Silk) - A product has **capacity options** (64GB, 128GB, 256GB) - Any combination of the above (Size + Color, Color + Material, etc.) **Do NOT use variants when:** | Scenario | Better approach | |----------|----------------| | Completely different products | Create separate Standard products | | Products with only price differences | Use separate Standard products with different names | | Digital products with tiers | Create separate Virtual products | | Bundles or kits | Use related products | ## How Variants Work [#how-variants-work] Variants are built from **attributes**, structured properties you define for your products. Here's the flow: 1. Create a **Variant** product 2. Attach **attributes** to the product (e.g., Size, Color) 3. Each attribute has **values** (Size: S, M, L / Color: Red, Blue) 4. **Generate variants** from all combinations 5. Configure each variant (price, stock, image) ### Example: T-Shirt with Size and Color [#example-t-shirt-with-size-and-color] **Attributes:** - Size: S, M, L, XL - Color: Red, Blue, Black **Generated variants (12 total):** | Variant | SKU | Price | Stock | |---------|-----|-------|-------| | S / Red | TSH-S-RED | $29.99 | 25 | | S / Blue | TSH-S-BLU | $29.99 | 30 | | S / Black | TSH-S-BLK | $29.99 | 20 | | M / Red | TSH-M-RED | $29.99 | 40 | | M / Blue | TSH-M-BLU | $29.99 | 35 | | M / Black | TSH-M-BLK | $29.99 | 45 | | L / Red | TSH-L-RED | $32.99 | 20 | | L / Blue | TSH-L-BLU | $32.99 | 25 | | L / Black | TSH-L-BLK | $32.99 | 30 | | XL / Red | TSH-XL-RED | $34.99 | 15 | | XL / Blue | TSH-XL-BLU | $34.99 | 20 | | XL / Black | TSH-XL-BLK | $34.99 | 10 | ## Setting Up Variant Attributes [#setting-up-variant-attributes] Before generating variants, you need to attach attributes to your product. ### Prerequisites [#prerequisites] Make sure you have created the necessary attributes in the [Attributes](/2.x/user-guide/catalog/attributes) section. Variant-compatible attributes typically use these field types: - **Select**. A dropdown list of values. You add one value to the product at a time - **Color picker**. Visual color selection. You can add several values at once - **Checkbox**. Multiple selectable values. You can add several values at once Attributes of type text, number, rich text or date are not used to generate variants. ### Adding Attributes to Your Product [#adding-attributes-to-your-product] 1. Open your variant product's **Attributes** tab 2. Click **Choose attributes** 3. In the **Attributes** step of the panel, select the attributes you want to use for variants (e.g., Size, Color), then go to the next step 4. In the **Values** step, pick the values this product comes in (e.g., S, M, L). A **Select** attribute takes one value at a time: click **Choose attributes** again to add the next one 5. Click **Save**. The values you picked become the options for variant generation ## Generating Variants [#generating-variants] Once attributes are attached, you can generate all variant combinations automatically. ### Automatic Generation [#automatic-generation] 1. Go to the **Variants** tab on your product 2. Click **Generate variants**. The button only shows once the product has attribute values 3. Shopper calculates all possible combinations from your attribute values 4. Review the list in the **Generate variants** panel. Each combination is a row with a **Name** (required, filled in from the values), a **SKU (Stock Keeping Unit)** made from the product SKU and the values, a **Price** and a **Stock number value**. Rows marked **New** are variants that do not exist yet 5. Edit the name, SKU, price and stock as needed. To leave out a combination you do not sell, click the delete icon on its row. If that combination is an existing variant, the variant is deleted when you save 6. Click **Save** to create all variants at once The **Price** field in this panel does not convert decimals: type the amount in cents, for example 15000 for 150.00. It sets the price in your default currency only. To enter prices with decimals or in other currencies, leave it at 0 and use the **Product pricing** section on each variant's page. The number of variants equals the product of all attribute value counts. For example: 4 sizes x 3 colors = 12 variants. Keep this manageable, too many combinations can be hard to maintain. ### Adding Individual Variants [#adding-individual-variants] You can also add variants one at a time: 1. Go to the **Variants** tab 2. Click **Add variant** 3. Fill in the variant details step by step, then click **Save** The individual variant creation wizard has 4 steps: **Step 1: General** - **Name** of the variant (required) - **SKU** (must be unique within the product) - One value for each of the product's attributes, under **Variant attributes**. If another variant already uses the same values, the panel shows "This variant already exists!" and you cannot save **Step 2: Media** - **Thumbnail** for this variant - Additional **Images** for this variant **Step 3: Pricing** - **Price amount** per currency - **Compare at price** - **Cost per item** **Step 4: Inventories** - **Barcode** - **Quantity**, added to your default inventory location ## Managing Variants [#managing-variants] After generation, you can manage each variant individually. The **Products variations** list on the **Variants** tab shows each variant's thumbnail, name, SKU, position and current stock. ### Variant Properties [#variant-properties] Each variant can have its own: | Property | Description | |----------|-------------| | **Name** | Descriptive name (filled in from the attribute values when you generate variants) | | **SKU** | Stock keeping unit for this specific variant, unique within the product | | **Barcode** | Unique barcode (UPC, EAN) for this variant | | **Price amount** | Different pricing per variant and per currency | | **Compare at price** | Show original price for discounted variants | | **Cost per item** | Your cost for this variant (for margin calculations) | | **Quantity** | Stock level for this specific combination, per inventory location | | **Thumbnail** and **Images** | Images showing this color or option | | **Package dimension** | Width, height, weight, volume and depth, if they vary by size | | **Allow backorder** | Whether to accept orders when out of stock | | **Position** | The variant's place in the variant list. Use the reorder button above the list and drag the variants into order | ### Editing a Variant [#editing-a-variant] Click the **Edit** icon on a variant's row to open the variant's own page, titled with its name. From there you can update: - The name, **Allow backorder**, the attribute values and the **Package dimension**: click **Edit** in the **Variant information** section - All pricing fields, per currency, in the **Product pricing** section, the same way as for a product - The SKU and barcode: click **Edit** in the **Inventories** section - Stock levels: in the **Quantity Inventory** list, click **Update**, select the **Inventory name** and enter the **Quantity** to add (50) or remove (-5) - Variant-specific images: click **Edit** in the **Media** section to change the **Thumbnail** and **Images** ### Deleting Variants [#deleting-variants] If you discontinue a specific option (e.g., removing the "XS" size): 1. Find the variant in the list on the **Variants** tab 2. Click the delete icon on its row. To delete several variants, select them and choose **Delete** from the bulk actions 3. Confirm the deletion Deleting a variant is permanent and removes its images, prices and stock history. If a variant is temporarily unavailable, set its stock to 0 instead. ## Variant Pricing Strategies [#variant-pricing-strategies] ### Same Price for All [#same-price-for-all] All variants at the same price point: - Basic t-shirt: All sizes and colors at $29.99 ### Price by Size [#price-by-size] Larger sizes cost more due to material usage: - S/M: $29.99 - L/XL: $34.99 - XXL: $39.99 ### Price by Option [#price-by-option] Premium options at a higher price: - Standard colors (Black, White, Gray): $49.99 - Limited edition colors (Gold, Rose): $59.99 ### Per-Variant Pricing [#per-variant-pricing] Each combination has its own price: - Useful for products where cost varies significantly by option ## Shipping for Variant Products [#shipping-for-variant-products] Variant products have package dimensions at both levels: - **Parent product**: the **Package dimension** section of the **Shipping** tab - **Individual variants**: the **Package dimension** fields behind **Edit** in the **Variant information** section of each variant's page With the starter kits, shipping rates use the dimensions of the variant in the cart. The parent product's dimensions are not copied to its variants, so fill them in on each variant (e.g., XL is heavier). ## Inventory Per Variant [#inventory-per-variant] Stock is tracked individually for each variant: - Each variant has its own quantity per inventory location - The products list shows the total stock across all variants, for example "in stock for 12 variant(s)" - Safety stock is set on the parent product only. Variants have no safety stock level, and Shopper sends no alert when a variant runs low - With the starter kits, an option whose variants have no stock (and do not allow backorder) cannot be selected, while the other options stay purchasable ## Storefront Display [#storefront-display] On your storefront, variant products display option selectors that let customers choose their preferred combination: When a customer selects different options: - The **price** shows the selected variant's price, or the product price when the variant has none - The **images** stay those of the product: the starter kits do not show variant images on the product page - **Availability**: options with no stock and no backorder cannot be selected. The Vue and React starter kits also show an "Out of stock" badge - The **Add to Cart** button: in the Vue and React starter kits it stays disabled until every option is chosen, and reads "Out of stock" when the selected variant has no stock. The Livewire starter kit keeps it active and shows a message when an option is missing or stock is too low ## Example: Creating a Variant Product [#example-creating-a-variant-product] Let's create a "Classic Cotton Hoodie" with Size and Color options: 1. **Type**: Select "Variant" 2. **General info**: Name "Classic Cotton Hoodie", describe the material and fit 3. **Associations**: Brand "UrbanWear", categories "Clothing > Hoodies", collection "Fall Collection" 4. **Media**: Upload lifestyle photos showing different colors 5. **Stock & Inventory**: SKU for parent product `HOOD-CLASSIC` (variants will have their own SKUs) After creation: 1. **Attributes**: Attach "Size" (S, M, L, XL) and "Color" (Navy, Gray, Black) 2. **Generate variants**: Creates 12 combinations automatically 3. **Pricing**: S/M at $59.99, L/XL at $64.99 4. **Stock**: Set quantities per variant based on your inventory 5. **Images**: Upload color-specific photos for each color variant 6. **Shipping**: Weight 0.5 kg for S/M, 0.6 kg for L/XL ## Best Practices [#best-practices] Keep variant count manageable. 3 sizes x 3 colors (9 variants) is easier to manage than 6 sizes x 8 colors (48 variants). Use a consistent SKU pattern: PRODUCT-SIZE-COLOR (e.g., HOOD-M-NAV). Upload variant-specific images for color options. The starter kits show the product's own images on the product page, so ask your developer if you want variant images shown. Check the stock of your popular variants often: Shopper sends no alert when a variant runs low. ## Limitations [#limitations] - There is no fixed limit on variant attributes (e.g., Size + Color + Material), but each one multiplies the number of variants - The total number of variants is the product of all attribute values - Consider splitting into separate products if you exceed 50+ variants - Product type cannot be changed after creation, so plan ahead For developer details, see the [Product Variants documentation](/2.x/product-variants). # Virtual Product (/2.x/user-guide/catalog/products/virtual-product) A virtual product is a **digital or intangible item** that doesn't require physical shipping. Customers receive their purchase through a download link, an access code, or an online account. There's no need for inventory tracking, shipping calculations, or package dimensions. ## When to Use Virtual Products [#when-to-use-virtual-products] Use the Virtual product type when you sell: - **Digital downloads**. Ebooks, music, software, templates, presets - **Online courses**. Video courses, tutorials, educational content - **Software licenses**. Activation keys, subscription codes - **Memberships**. Access to premium content or services - **Digital art**. Photos, illustrations, design assets - **Documents**. Reports, guides, legal templates ## What Makes Virtual Products Unique [#what-makes-virtual-products-unique] Virtual products have a simplified configuration compared to physical products: | Feature | Available | Notes | |---------|-----------|-------| | **Shipping** | No | No physical delivery needed | | **Inventory tracking** | No | Digital goods have unlimited stock | | **Attributes** | No | Not applicable for digital items | | **Variants** | No | Use separate products for different tiers | | **Digital files** | Yes | Upload downloadable files for customers | | **Pricing** | Yes | Full pricing support including compare-at prices | | **SEO** | Yes | Optimize for search visibility | | **Categories & collections** | Yes | Organize alongside physical products | ## Managing Digital Files [#managing-digital-files] The key feature of virtual products is the ability to attach downloadable files that customers receive after purchase. ### Uploading Files [#uploading-files] After creating your virtual product, navigate to the **Files** section: 1. Click **Add file** or drag and drop your files 2. Upload one or more files (PDF, ZIP, MP3, MP4, etc.) 3. Files are stored securely and only accessible to customers who purchase the product ### File Types [#file-types] You can upload any file type. Common formats include: | Category | Common formats | |----------|----------------| | Documents | PDF, DOCX, XLSX, PPTX | | Images | PNG, JPG, PSD, AI, SVG | | Audio | MP3, WAV, FLAC, AAC | | Video | MP4, MOV, AVI, MKV | | Software | ZIP, DMG, EXE, MSI | | Archives | ZIP, RAR, TAR.GZ | For large files, consider compressing them into a ZIP archive before uploading. This reduces upload time and provides a single download for customers. ## Pricing Virtual Products [#pricing-virtual-products] Virtual products support the same pricing options as physical products: | Field | Description | |-------|-------------| | **Price** | The regular selling price | | **Compare at price** | Show a crossed-out original price (useful for promotions) | | **Cost per item** | Your cost for profit margin calculations | You can set prices in multiple currencies if your store supports it. Virtual products often use the compare-at price for limited-time offers or launch promotions. For example, an online course priced at $49 with a compare-at price of $99 shows customers they're getting a deal. ## Example: Creating a Virtual Product [#example-creating-a-virtual-product] Let's create a "Photography Masterclass" online course: 1. **Type**: Select "Virtual Product" 2. **General info**: Name it "Photography Masterclass: From Beginner to Pro", add a description covering what students will learn, the curriculum outline, and what's included 3. **Associations**: Category "Courses > Photography", collection "Best Sellers" 4. **Media**: Upload a course cover image and preview screenshots of the video content 5. **Stock**: Skip, no physical inventory needed After creation: - **Files**: Upload the course ZIP file containing video lessons, PDF workbook, and preset pack - **Pricing**: $79.00, compare at $149.00 - **SEO**: Title "Photography Masterclass Online Course", optimize description with keywords like "learn photography", "photo editing course" ## Best Practices [#best-practices] Clearly describe what files or access customers will receive after purchase. Use images and descriptions to give customers a preview of what they're buying. Bundle multiple files into a well-organized ZIP with a README or guide. Use compare-at pricing for launches and time-limited promotions. ## Differences from Standard Products [#differences-from-standard-products] | Aspect | Standard Product | Virtual Product | |--------|-----------------|-----------------| | Delivery | Physical shipping | Instant download | | Inventory | Tracked with stock levels | Unlimited availability | | Shipping config | Weight, dimensions required | Not applicable | | Attributes | Material, size, etc. | Not applicable | | Files | Not applicable | Downloadable files attached | | Returns | Physical return process | Refund-based (no return) | # Managing Suppliers (/2.x/user-guide/catalog/suppliers) Suppliers represent external vendors or manufacturers who provide products for your store. This is primarily used in **dropshipping** scenarios where products are shipped directly from the supplier to the customer, without you handling inventory yourself. The supplier feature must be enabled by your developer before it appears in the admin panel. If you don't see "Suppliers" in the sidebar, ask your developer to enable it (see [Feature Flag](/2.x/suppliers#feature-flag)). ## Accessing Suppliers [#accessing-suppliers] When the feature is enabled, suppliers appear under the Products section: 1. Click on **Products** in the sidebar 2. Select **Suppliers** from the submenu ## Adding a Supplier [#adding-a-supplier] To add a new supplier: 1. Click the **New supplier** button 2. Fill in the supplier details 3. Click **Save** ### Supplier Fields [#supplier-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The supplier's company name | | **Email address** | No | Contact email for placing orders | | **Phone number** | No | Contact phone number | | **Contact** | No | Primary contact person at the supplier | | **Website** | No | Supplier's website URL | | **Visibility** | No | Whether the supplier is active and can be picked on products. Off by default. | | **Description** | No | In the **Description** section, details about the supplier and their products | | **Notes** | No | In the **Description** section, internal notes (not visible to customers) | | **Metadata** | No | In the **Metadata** section, extra key and value pairs your developer can use | ## Editing a Supplier [#editing-a-supplier] To update a supplier's information: 1. Click the **Edit** icon next to the supplier 2. Modify the fields you want to change 3. Click **Save** ## Enabling or Disabling a Supplier [#enabling-or-disabling-a-supplier] The **Visibility** column in the list shows whether each supplier is active; it cannot be clicked. To change it, edit the supplier and switch **Visibility**, or select several suppliers in the list and use the **Enable** or **Disable** bulk action. Disabled suppliers stay linked to their products but no longer appear in the product **Supplier** dropdown. ## Linking Products to Suppliers [#linking-products-to-suppliers] Products are linked to suppliers from the product edit form, once the product is created: the creation wizard has no supplier field. When editing an **External** product: 1. Go to the product's edit page 2. In the **Overview** tab, find the **Supplier** dropdown in the **Product information** section, next to **Product external Id** 3. Select the supplier. Only enabled suppliers are listed 4. Fill in **Product external Id**, the identifier of the product at your supplier. Both fields are required 5. Click **Update** The **Supplier** dropdown, like the **Suppliers** menu, only appears when the supplier feature is enabled. Only **External** products can be linked to suppliers. Standard, variant, and virtual products are managed from your own inventory. ## How Dropshipping Works [#how-dropshipping-works] When a customer orders a product linked to a supplier, the order flow is: 1. **Customer places order** on your store 2. **You receive the order** in the admin panel 3. **You forward the order** to the supplier (via email, their portal, or API) 4. **Supplier ships directly** to the customer 5. **You add tracking info** from the supplier to the order 6. **Customer receives the product** The key difference from regular orders is that you never handle the physical product. The supplier ships directly to your customer. With dropshipping, you depend on the supplier's inventory and shipping speed. Make sure to verify your supplier's reliability before listing their products. Delays or quality issues reflect on your store. ## Supplier Information to Collect [#supplier-information-to-collect] When onboarding a new supplier, gather this information: | Information | Why You Need It | |-------------|----------------| | **Order email** | To send purchase orders when customers buy | | **Product catalog** | To know what they offer and at what price | | **Lead time** | To set customer expectations for delivery | | **Return policy** | To handle customer returns | | **Payment terms** | To manage your cash flow (Net 30, prepaid, etc.) | | **Minimum order** | To know if there's a minimum quantity per order | ## Best Practices [#best-practices] Order samples from a supplier before listing their products. Test quality, packaging, and delivery time. Use the cost price field on products to track your profit margin on supplier products. Set clear expectations with suppliers about order format, shipping requirements, and branding. Use the Notes field to track payment terms, minimum orders, and special instructions. For developer details on suppliers, fulfillment workflows, and the dropshipping API, see the [Suppliers documentation](/2.x/suppliers). # Managing Tags (/2.x/user-guide/catalog/tags) Tags are flat, flexible labels you attach to products for cross-cutting organization. Unlike [categories](/2.x/user-guide/catalog/categories) (which are hierarchical) or [collections](/2.x/user-guide/catalog/collections) (which can be rule-based), tags are simple keywords that help you group products across your catalog. Common uses for tags include seasonal labels ("Summer 2026"), marketing campaigns ("Flash Sale"), product attributes ("Eco-Friendly"), or storefront filters ("New Arrival", "Best Seller"). ## Accessing Tags [#accessing-tags] 1. Click on **Products** in the sidebar 2. Select **Tags** from the submenu The tags list shows all your tags with their name, slug, and creation date. You can search, edit, and delete tags from this page. ## Creating a Tag [#creating-a-tag] To create a new tag: 1. Click the **Create** button 2. In the **Create tag** window, enter the tag name 3. Click **Submit** | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The tag label (e.g., "Summer 2026", "New Arrival") | | **Slug** | Auto | Generated automatically from the name. Used in URLs on your storefront. | The slug is generated automatically from the tag name and cannot be edited manually. Each slug must be unique: if another tag already uses the same slug, the form shows an error and the tag is not created. Choose a different name. ## Editing a Tag [#editing-a-tag] To update an existing tag: 1. Click the **Edit** icon next to the tag 2. Modify the name 3. Click **Update** Renaming a tag keeps its existing slug, so its storefront URLs do not change. ## Deleting Tags [#deleting-tags] To remove a tag: 1. Click the **Delete** icon next to the tag 2. Confirm the deletion You can also select multiple tags and use the bulk delete action to remove several at once. Deleting a tag removes it from all products that use it. The products themselves are not affected. ## Assigning Tags to Products [#assigning-tags-to-products] Tags are assigned to products from the product edit form, not from the tags page. When editing a product: 1. Go to the product's edit page 2. In the **Overview** tab, find the **Tags** field in the **Associations** section 3. Select existing tags, or click the **+** button next to the field to create a new one 4. Click **Update** You can create new tags directly from the product edit form without going to the Tags page. Click the **+** button next to the **Tags** field, enter the name in the **Create tag** window, then click **Create**. The new tag is selected in the field: click **Update** to save the product. ## Tags vs Categories vs Collections [#tags-vs-categories-vs-collections] | Feature | Tags | Categories | Collections | |---------|------|-----------|-------------| | **Structure** | Flat labels | Hierarchical tree | Flat groups | | **Assignment** | Manual per product | Manual per product | Manual or automatic (rule-based) | | **Best for** | Cross-cutting labels, campaigns | Product taxonomy, navigation | Marketing groups, curated lists | | **Example** | "Eco-Friendly", "Flash Sale" | Electronics > Computers > Laptops | "Summer Essentials", "Best Sellers" | ## Common Tag Strategies [#common-tag-strategies] | Strategy | Tags | Use Case | |----------|------|----------| | Seasonal | "Spring 2026", "Summer 2026" | Rotate seasonal products on your storefront | | Marketing | "Flash Sale", "Clearance" | Highlight promotional products | | Product traits | "Organic", "Handmade", "Vegan" | Help customers filter by values | | Internal | "Low Margin", "Restock Soon" | Track products without showing on storefront | Tags are visible on your storefront if your developer builds filtering based on them. If a tag is for internal use only, you can use it without displaying it to customers. For developer details on tags, see the [Product Tags documentation](/2.x/product-tags). # Discovering Dashboard (/2.x/user-guide/getting-started/dashboard) The Dashboard is your command center for managing your online store. Let's explore its key elements and learn how to navigate efficiently. ## Overview [#overview] When you log in, you'll see the main dashboard which displays key metrics and quick access to important features. ## Main Navigation [#main-navigation] The sidebar on the left side of the screen is your main navigation tool. It provides access to all sections of your store management: | Section | Description | |---------|-------------| | **Dashboard** | Overview of your store's performance and recent activity | | **Products** | Manage your product catalog | | **Categories** | Organize products into categories | | **Collections** | Create curated product collections | | **Brands** | Manage product brands | | **Customers** | View and manage customer accounts | | **Orders** | Process and track orders | | **Discounts** | Create and manage discount codes | | **Reviews** | Moderate customer reviews | | **Settings** | Configure your store settings | ## Quick Actions [#quick-actions] From the dashboard, you can quickly access common tasks: - Check your **Total Revenue** for the month and your **Total Products**, **Total Orders** and **Total Customers**, each compared with last month. **View more** on a card opens the matching list. - Follow your revenue over time in the **Performance** chart - See your **Top Selling Products** - View recent orders in **Recent Orders**, or click **View all** - Access store settings On a new store, the dashboard shows a **Setup guide** instead: add your first product, create a collection, set up shipping zones, payment methods and taxes. Click **Dismiss** to hide it. ## Settings Panel [#settings-panel] Click on **Settings** in the sidebar to access all configuration options for your store. The settings panel shows one card per area, in this order: - **[General](/2.x/user-guide/store-setup/general-settings)** - Store name, contact details, address, currencies and social links - **[Staff & permissions](/2.x/user-guide/administration/users)** - Administrator accounts, roles and permissions - **[Inventories](/2.x/user-guide/store-setup/locations)** - The places where you stock inventory and sell products - **[Payment methods](/2.x/user-guide/store-setup/payment-methods)** - The payment methods offered to your customers - **[Carriers](/2.x/user-guide/store-setup/carriers)** - Shipping carriers and delivery providers - **[Legal](/2.x/user-guide/store-setup/legal)** - Privacy policy, terms of use, shipping and refund policies - **[Zones](/2.x/user-guide/store-setup/zones)** - Shipping, payment and fulfillment per zone - **[Taxes](/2.x/user-guide/store-setup/taxes)** - How your store charges taxes - **[Currencies](/2.x/user-guide/store-setup/currencies)** - Enabled currencies and exchange rates Once you open a settings page, the same areas appear as tabs at the top of the page, so you can move from one to another without going back. ## Your Profile [#your-profile] Access your personal profile settings by clicking on your avatar at the top-right of the header, then **Personal Account**. From here you can: - Update your personal information - Change your password - Enable two-factor authentication, when it is turned on for your store - See the devices signed in to your account and log out your other browser sessions To sign out, click your avatar and select **Sign out**. # Introduction (/2.x/user-guide/getting-started/introduction) Shopper gives you a complete administration panel to manage your online store. From this panel, you can create products, process orders, manage customers, set up discounts, and configure every aspect of your store without writing any code. ## What You Can Do [#what-you-can-do] Create and manage products with variants, images, pricing, and inventory. Organize them into categories, collections, and brands. Track customer orders from placement to delivery. Manage payments, shipping, and fulfillment from a single screen. View customer profiles, order history, and addresses. Keep track of who is buying what. Create discount codes with conditions, usage limits, and expiration dates to drive sales. Configure your store name, currencies, locations, legal pages, and more. Add staff members, assign roles, and control who can access what in the admin panel. ## Who Is This Guide For? [#who-is-this-guide-for] This User Guide is designed for **store administrators and managers** who use Shopper daily to manage their e-commerce operations. No technical knowledge is required. Every feature is explained with step-by-step instructions. Looking for developer documentation? The [Documentation](/2.x/getting-started) tab covers installation, configuration, model references, and customization options. ## Getting Help [#getting-help] If you need assistance while using Shopper: - Join the [Discord community](https://laravelshopper.dev/discord) to connect with other users and the Shopper team - Check the [GitHub repository](https://github.com/shopperlabs/shopper) for updates and known issues ## Next Steps [#next-steps] Ready to get started? Learn how to [log in to your administration panel](/2.x/user-guide/getting-started/login). # Logging In (/2.x/user-guide/getting-started/login) To manage your store, you need to log in to the Shopper administration panel. This guide will walk you through the login process. ## Accessing the Login Page [#accessing-the-login-page] Your Shopper administration panel is accessible at your website URL followed by `/cpanel`. For example: ``` https://your-store.com/cpanel/login ``` ## Logging In [#logging-in] The login card reads **Sign in with email**. 1. Enter your email in the **Email address** field 2. Enter your password in the **Password** field 3. Optionally check **Remember me** to stay signed in on this browser 4. Click the **Login** button If you've enabled two-factor authentication on your account, you'll be prompted to enter a verification code after submitting your credentials. Learn more about [Two-Factor Authentication](/2.x/user-guide/administration/two-factor). ## Forgot Your Password? [#forgot-your-password] If you've forgotten your password: 1. Click the **Forgot your password?** link next to the **Password** label 2. Enter your email address and click **Send password reset mail** 3. Check your email for a password reset link 4. Follow the instructions in the email to create a new password ## After Logging In [#after-logging-in] Once logged in, you'll be taken to the **Dashboard**, which provides an overview of your store's activity. From here, you can navigate to any section of the administration panel using the sidebar on the left. ## Logging Out [#logging-out] To log out of your account: 1. Click your **profile picture** in the top-right corner of the header 2. Select **Sign out** from the dropdown menu The same menu opens your profile (**Personal Account**) and the staff list (**Manage Users**, shown only if you can view staff accounts), and switches the admin between **Light**, **Dark** and **System** themes. # Managing Discounts (/2.x/user-guide/marketing/discounts) Discounts are a powerful way to attract customers, boost sales, and reward loyalty. Shopper provides flexible discount options for your marketing campaigns. ## Overview [#overview] The Discounts section allows you to: - Create discount codes - Limit a discount code to one zone - Define discount rules and conditions - Track discount usage - Schedule promotional periods ## Accessing Discounts [#accessing-discounts] Click on **Discounts** in the sidebar to access discount management. ### Empty State [#empty-state] If you haven't created any discounts yet: ## Creating a Discount [#creating-a-discount] To create a new discount: 1. Click the **New discount** button 2. Choose the zone, the type, the code and the value 3. Set the usage limits and the **Active dates** 4. Set the **Conditions**: what the code applies to, who can use it and the minimum requirements 5. Click **Save** ### Discount Types [#discount-types] | Type | Description | Example | |------|-------------|---------| | **Percentage** | Discount as a percentage | 20% off | | **Fixed amount** | Specific amount off | $10 off | There is no free shipping discount type. To offer free delivery, add a delivery option with a price of 0 in the zone (see [Setting Up Delivery Options](/2.x/user-guide/store-setup/carriers#setting-up-delivery-options)). ### Discount Configuration [#discount-configuration] | Field | Description | |-------|-------------| | **Zone** | Optional. Limits the code to one zone. A fixed amount is then in the zone's currency. | | **Type** | **Percentage** or **Fixed amount** | | **Code** | The code customers enter at checkout (e.g., SUMMER20). Must be unique. Click **Generate** to create a random code. | | **Percentage** or **Fixed amount** | The discount value: from 1 to 100 for a percentage, at least 0.01 for a fixed amount | | **Visibility** | Turn on to make the code usable at checkout. A code with **Visibility** off is ignored. | | **Applies To** | **Entire order** or **Specific products** (see [Product Restrictions](#product-restrictions)) | | **Metadata** | Extra key and value pairs your developer can use | ## Discount Conditions [#discount-conditions] Set rules for when the discount can be used in the **Conditions** part of the form: ### Minimum Requirements [#minimum-requirements] Under **Minimum requirements**, choose one option, then enter the value: | Condition | Example | |-----------|---------| | **None** | No minimum | | **Minimum purchase amount** | Order must be at least $50 | | **Minimum quantity of items** | Cart must have at least 3 items | ### Customer Eligibility [#customer-eligibility] | Option | Description | |--------|-------------| | **Everyone** | Anyone can use the discount | | **Specific customers** | Only the customers you pick in **Select customers** | ### Product Restrictions [#product-restrictions] Under **Applies To**, choose: | Option | Description | |--------|-------------| | **Entire order** | Applies to everything in the cart | | **Specific products** | Only the products you pick in **Select products** | To discount a whole collection or brand, pick its products in **Select products**. ## Usage Limits [#usage-limits] Control how the discount can be used: | Limit | Description | |-------|-------------| | **Limit number of times this discount can be used in total** | Turn on, then enter the maximum in **Usage limit value**. The limit counts uses by all customers together. | | **Limit to one use per customer** | Each customer can use the code once | A cart holds one discount code at a time: applying a new code replaces the previous one, so codes never add up. ## Scheduling Discounts [#scheduling-discounts] Set active periods for your discounts: - **Start date** - When the discount becomes active. Required, and it cannot be in the past. - **End date** - When the discount expires. It must be on or after the start date. - **No end date** - Leave **End date** empty and the discount runs indefinitely ## Discount Strategies [#discount-strategies] Send new customers a code with **Limit to one use per customer** turned on, so each of them can use it once. Create time-limited discounts for holidays and seasons. Check the **Abandoned Carts** list under **Orders** and send those customers an exclusive code yourself. Shopper does not send recovery emails. Reward repeat customers with special discounts. ## Best Practices [#best-practices] Use unique, memorable discount codes that are easy to type. Avoid confusing characters like 0/O or 1/l/I. - **Clear naming** - Make codes descriptive (SUMMER2024, SAVE10) - **Set limits** - Protect margins with usage limits - **Track performance** - Monitor which discounts drive sales - **Create urgency** - Use end dates to encourage quick action - **Test first** - Always test discounts before promoting them ## Common Discount Examples [#common-discount-examples] | Campaign | Code | Type | Value | |----------|------|------|-------| | Welcome offer | WELCOME10 | Percentage | 10% off, one use per customer | | Spend and save | SAVE10 | Fixed amount | $10 off orders over $50 | | Flash sale | FLASH25 | Percentage | 25% off, 24 hours only | | Holiday | HOLIDAY15 | Percentage | 15% off storewide | For developer details, see the [Discounts documentation](/2.x/discounts). # Advanced Pricing (/2.x/user-guide/marketing/pricing) Beyond basic product pricing, Shopper offers advanced pricing features to help you implement sophisticated pricing strategies. ## Overview [#overview] Advanced pricing allows you to: - Set up sale prices and compare-at prices - Create customer group pricing - Implement quantity-based discounts - Schedule price changes ## Basic Price Structure [#basic-price-structure] Every product has these pricing fields: | Field | Description | |-------|-------------| | **Price** | The current selling price | | **Compare at price** | Original price (shows as strikethrough) | | **Cost per item** | Your cost (for margin calculations) | ## Sale Pricing [#sale-pricing] To put a product on sale: 1. Set the **Price** to the sale price 2. Set the **Compare at price** to the original price 3. The original price will display as strikethrough ### Example [#example] | Field | Value | Display | |-------|-------|---------| | Price | $24.99 | Current price | | Compare at price | $34.99 | ~~$34.99~~ | Customers see: ~~$34.99~~ **$24.99** (Save 29%) ## Cost and Profit [#cost-and-profit] Track your margins by entering the cost per item: | Field | Value | |-------|-------| | Price | $49.99 | | Cost | $20.00 | | **Profit** | $29.99 | | **Margin** | 60% | Always enter your product costs to accurately track profit margins and make informed pricing decisions. ## Variant Pricing [#variant-pricing] When products have variants, you can set different prices: | Variant | Price | |---------|-------| | Small | $29.99 | | Medium | $29.99 | | Large | $34.99 | | XL | $39.99 | This is useful for: - Size-based pricing (larger = more expensive) - Premium option pricing - Material-based pricing ## Pricing Strategies [#pricing-strategies] Price products similar to competitors. Price based on perceived value to customers. Offer discounts when products are bought together. Adjust prices based on demand and inventory. ## Price Display [#price-display] Prices appear throughout your store: - Product listing pages - Product detail pages - Shopping cart - Checkout - Order confirmations ### Currency Formatting [#currency-formatting] Prices are formatted according to your currency settings: | Currency | Format | |----------|--------| | USD | $1,234.56 | | EUR | €1.234,56 | | GBP | £1,234.56 | ## Best Practices [#best-practices] ### Setting Prices [#setting-prices] - **Research competitors** - Know what similar products cost - **Consider costs** - Ensure profitable margins - **Test prices** - A/B test different price points - **Round strategically** - $29.99 vs $30.00 ### Managing Sales [#managing-sales] - **Plan ahead** - Schedule sales in advance - **Limit duration** - Create urgency with end dates - **Track results** - Monitor sales performance - **Restore prices** - Remember to revert after sales end Use the "Compare at price" feature to show value even when not running a sale - display the "regular" price to emphasize everyday savings. ## Pricing Checklist [#pricing-checklist] Before publishing a product, verify: - [ ] Price is set correctly - [ ] Compare at price (if applicable) is higher than price - [ ] Cost per item is entered for margin tracking - [ ] Variant prices are consistent with your strategy - [ ] Currency formatting looks correct For developer details, see the [Pricing documentation](/2.x/pricing). # Managing Customers (/2.x/user-guide/sales/customers) Your customers are essential to your business. Shopper helps you manage customer information, track their orders, and build lasting relationships. ## Overview [#overview] The Customers section allows you to: - View all registered customers - Access customer details and order history - See customer addresses - Send login credentials to the customers you create - Create customers manually - Anonymize a customer who asks for their data to be removed ## Accessing Customers [#accessing-customers] Click on **Customers** in the sidebar to access customer management. ## Customer List [#customer-list] The customer list displays: | Column | Description | |--------|-------------| | **Full Name** | Customer's full name and picture | | **Email address** | Contact email address | | **Country** | Country of the customer's first address | | **Order Placed** | Number of paid orders that are processing or completed | | **Registered At** | When they registered | You can filter the list by **E-mail Verified** and by registration date. ### Empty State [#empty-state] If you don't have any customers yet, you'll see a helpful prompt: ## Customer Details [#customer-details] Click a customer's name, or the eye icon (**View**), to open their profile. The header shows their name, their email (with an icon when the email is verified), how long they have been a customer, and the **Anonymize customer** button. Below it, the **Profile**, **Addresses**, and **Orders** tabs: ### Profile Information [#profile-information] The **Profile** tab is read-only. It has two cards: - **Profile**. First name, last name, picture, email address, birth date, and gender (when set) - **Account**. **Email Marketing** shows whether the customer agreed to receive marketing emails, and **Two-Factor Authentication** whether they turned it on. Each shows **Enable** or **Disable** The profile has no account status and no notes field. The verified icon next to the email tells you the customer confirmed their email address, and the phone number appears on each address card. For internal comments, use the private notes on each order. ### Addresses [#addresses] The **Addresses** tab shows each of the customer's addresses as a card, labelled **Shipping Address** or **Billing Address**, with the name, street, postal code, city, country, and phone number. Addresses cannot be edited from the admin. When you create a customer, the **Address** section of the **New customer** form records their first address, which becomes their default shipping address: Customers can have multiple addresses. With the starter kit, they add and remove them from their account on your storefront and choose: - **Default shipping address** - **Default billing address** - **Additional addresses**, kept for later orders ### Order History [#order-history] The **Orders** tab lists all orders placed by the customer: - Order numbers and dates - Order totals - Payment and shipping status - Purchased items ## Creating a Customer [#creating-a-customer] To manually add a customer: 1. Click the **New customer** button on the Customers page 2. Fill in the customer details 3. Click **Save** ### Customer Fields [#customer-fields] The form has four sections: **Profile overview**, **Security**, **Address**, and **Notifications**. | Field | Required | Description | |-------|----------|-------------| | **First name** | Yes | Customer's first name | | **Last Name** | Yes | Customer's last name | | **Email address** | Yes | Unique email address | | **Phone number** | No | Contact phone number | | **Gender** | No | Male or Female | | **Password** | Yes | Account password. Click **Generate** to fill in a random 12-character password | | **Confirm Password** | Yes | The same password again | | **Street Address** | Yes | First line of the customer's address | | **Apartment, suite, etc.** | No | Second line of the address | | **City** | Yes | City | | **State** | No | State or region | | **Postal / Zip code** | Yes | Postal code | | **Country** | Yes | Country | | **Phone number** (address) | No | Phone number for this address | | **Customer agreed to receive marketing emails.** | No | Records the customer's consent, shown as **Email Marketing** on their profile | | **Send customer credentials.** | No | Emails the customer their email address and password | The customer's email is marked as verified on creation, and you return to the customer list. ## Customer Notification [#customer-notification] The admin sends customers one email: their login credentials. When you create a customer, the **Notifications** section of the form has two checkboxes: With **Send customer credentials.** checked, the customer receives a welcome email ("Welcome to" followed by your store name) with their email address and password, a **Browse the website** button, and a reminder to change the password after logging in. **Customer agreed to receive marketing emails.** sends nothing: it only records consent. Other emails customers expect do not come from the admin: - Order confirmations: not sent by Shopper; your developer adds them to your store - Shipping updates: not sent by Shopper; your developer adds them to your store - Marketing emails: sent from your own email marketing tool, to customers whose profile shows **Email Marketing** enabled - Password resets: sent by the starter kit's login pages, along with the email verification message ## Customer Account (Storefront) [#customer-account-storefront] Customers can manage their own accounts on your storefront. With the starter kit, their account page welcomes them by first name and links to **Orders**, **Addresses**, and **Profile**: They can: - Update personal information (first name, last name, gender, and email) under **Profile** - Manage addresses under **Addresses**: add, remove, and set a default shipping or billing address - View order history under **Orders** - Change password and turn on two-factor authentication in the **Security** settings ## Customer Authentication [#customer-authentication] Customers register and log in through your storefront. With the starter kit, they create an account with their last name, first name, email address, and password (**Create account**), then log in with their email address and password (**Log in**). The login page also offers **Remember me** and a **Forgot your password?** link: ## Best Practices [#best-practices] Handle customer data responsibly and comply with privacy laws. Check the **Email Marketing** consent on each profile to know who agreed to receive your marketing emails. Monitor purchasing patterns to understand your audience. Maintain communication to build loyalty. ## Customer Data Privacy [#customer-data-privacy] If a customer requests their data to be removed (GDPR "right to be forgotten"), you can anonymize their account: 1. Go to the customer's profile page 2. Click **Anonymize customer** 3. Confirm with **Yes, anonymize** This replaces the customer's personal information (name, email, phone, avatar) with anonymous data, clears their birth date and marketing consent, and deletes all their addresses. Order history is preserved for your records, but the customer's identity is removed. Anonymization cannot be undone. The customer's personal data is permanently replaced. Only use this when a customer explicitly requests data removal. Encourage customers to create accounts by offering benefits like faster checkout, order tracking, and exclusive offers. For developer details, see the [Customers documentation](/2.x/customers). # Managing Orders (/2.x/user-guide/sales/orders) When a customer places an order on your store, it appears in the **Orders** section of your admin panel. From here, you manage everything: confirm payment, prepare shipments, track delivery, and handle issues. ## Order List [#order-list] Click **Orders** in the sidebar to see all your orders. The list has the columns **#** (order number), **Date**, **Status**, **Price amount**, **Purchased** (the ordered items), and **Customer**. The **Status** column shows a payment badge and a shipping badge, or a single **Cancelled** or **Archived** badge, so you see where the order stands at a glance. The **Currency**, **Zone**, and **Channel** columns are hidden by default; turn them on from the column selector above the table. ### Tabs [#tabs] The tabs at the top filter orders by their current state: | Tab | What it shows | |-----|---------------| | **All** | Every order in your store | | **Open** | New and processing orders that still need attention | | **Paid** | Orders where payment has been received | | **Fulfilled** | Orders that have been shipped or partially shipped | | **Cancelled** | Orders that were cancelled | | **Archived** | Orders you've archived | ### Filters [#filters] Click the filter icon to narrow down your list. You can filter by order number, customer, order status, payment status, shipping status, date range, zone, channel, or currency. ## Order Detail [#order-detail] Click the eye icon (**View details**) on an order to open its detail page. The page is split into two areas: the main content on the left and customer information on the right. ### Header [#header] The header stays visible as you scroll. It shows: - The **order number** - Three **status badges** for order status, payment status, and shipping status - **Action buttons** for processing the order (see [Actions](#actions) below) - **Previous / Next** arrows to navigate between orders - The **order date**, **customer name** (linked to their profile), and **sales channel** ### Main Content [#main-content] The left side of the page contains three sections: **Fulfillment**. A visual progress bar showing where the order is in the fulfillment process (**New**, **Processing**, **Shipped**, **Completed**). If there are items that haven't been assigned to a shipment yet and the order is not completed, cancelled, or archived, a **Create Shipping Label** button appears here. **Products**. The list of items in the order with their thumbnail, name, quantity, fulfillment status badge, and price. **Summary**. Payment status, payment method, subtotal, shipping carrier and fee, and the order total. ### Sidebar [#sidebar] The right side shows: - **Customer profile**. Name, avatar, and a link to their full profile. Below that, how long they've been a customer and how many orders they've placed. - **Contact information**. Email and phone number. - **Shipping address**. The delivery address for this order. - **Billing address**. Displayed separately, or **Same as shipping address** if it matches the shipping address. - **Private notes**. A text field where you can leave internal comments. Only your team can see these. ## Order Status [#order-status] Every order has three independent statuses that track different aspects of the order. ### Order Status [#order-status-1] The overall state of the order. | Status | Color | Meaning | |--------|-------|---------| | **New** | Blue | Order just came in, hasn't been looked at yet | | **Processing** | Purple | You're actively working on this order | | **Completed** | Teal | Everything is done, paid and delivered | | **Cancelled** | Red | Order was cancelled | | **Archived** | Gray | Order removed from active list | ### Payment Status [#payment-status] Tracks whether you've received the money. | Status | Color | Meaning | |--------|-------|---------| | **Payment pending** | Yellow | Waiting for payment | | **Authorized** | Blue | Funds are held on the customer's card but not yet collected | | **Paid** | Green | Payment received | | **Partially refunded** | Orange | Some of the amount has been refunded | | **Refunded** | Gray | Full amount refunded | | **Voided** | Red | Payment was cancelled before any money was collected | **Authorized** means the payment provider confirmed the customer has funds, but you haven't captured (collected) them yet. This is common for physical goods where you want to verify stock before charging. ### Shipping Status [#shipping-status] Tracks where the physical goods are. | Status | Color | Meaning | |--------|-------|---------| | **Unfulfilled** | Yellow | No items have been shipped yet | | **Partially shipped** | Blue | Some items shipped, others are still waiting | | **Shipped** | Indigo | All items have been shipped | | **Partially delivered** | Purple | Some packages arrived, others still in transit | | **Delivered** | Green | Everything has been delivered | | **Partially returned** | Orange | Some items were returned | | **Returned** | Gray | All items were returned | ## Actions [#actions] The actions available depend on the current state of the order. They appear in the header, some as standalone buttons, others in the **More actions** dropdown. ### Capture Payment [#capture-payment] Appears when the payment status is **Authorized**. Clicking it charges the customer for the authorized amount. A confirmation dialog will appear since this action cannot be undone. After capture, the payment status changes to **Paid** and the button disappears. ### Archive [#archive] Appears when the order is not completed and not paid. Moves the order to the Archived tab. Archiving an order affects your revenue reports. Use this for orders that will never be fulfilled, like spam or test orders. ### More Actions [#more-actions] The dropdown contains context-sensitive actions: | Action | When it appears | What it does | |--------|-----------------|--------------| | **Start processing** | Order is **New** | Changes order status to Processing. The items' fulfillment status does not change | | **Mark as paid** | Payment is **Pending** or **Authorized** | Changes payment status directly to Paid (without going through the payment provider). A **New** order also moves to Processing | | **Mark complete** | Order is **Processing** and payment is **Paid** | Changes order status to Completed | | **Cancel Order** | Order can be cancelled | Cancels the order and records the cancellation date | ## Fulfillment [#fulfillment] Fulfillment is the process of getting the ordered items to the customer. Shopper tracks this at two levels: the **order level** (shipping status) and the **item level** (fulfillment status per product). ### Creating a Shipment [#creating-a-shipment] When an order has items that haven't been shipped yet, the **Create Shipping Label** button appears in the fulfillment section. Clicking it opens the **Create Shipping Label** panel, where you: 1. **Choose the Carrier Service**. Pick one of your enabled carriers. The field starts with the carrier of the shipping option the customer chose 2. **Add tracking info** (optional). Enter a **Tracking number** and a **Tracking URL** 3. **Check the Items to fulfill**. Every item not yet in a shipment is listed with its product, quantity, and price. Remove the items that are not in this package with the trash icon; at least one item must stay The right side of the panel shows the order summary and the shipping address. Click **Save** to create the shipment. Once created, the shipment appears in the **Shipments** page with the status **Label created**, and the selected items are assigned to it. Their fulfillment status stays **Awaiting fulfillment** until the carrier picks up the package. ### Partial Shipments [#partial-shipments] You don't have to ship everything at once. If an order has 5 items and only 3 are ready, create a shipment with those 3 items. The remaining 2 stay as unfulfilled and you can create a second shipment later. The shipping status updates automatically from the shipment events (see [Adding Tracking Events](#adding-tracking-events)), not when you create the shipment: - A shipment is **Picked up** while other items are not shipped yet: **Partially shipped** - Every item is in a shipment that was picked up: **Shipped** - Some items are delivered: **Partially delivered** - Every item is delivered: **Delivered** When the first shipment is picked up, a **New** order also moves to **Processing**. ## Shipments [#shipments] The **Shipments** page gives you a dedicated view of all shipments across your orders. Access it from the sidebar under Orders. Each row shows the **Shipment ID**, the latest **Shipment Event**, the **Status**, **Shipped at**, the **Order Number**, and the **Carrier Service**. ### Tabs [#tabs-1] | Tab | Shows | |-----|-------| | **All** | Every shipment | | **Label created** | Shipments with labels created but not yet picked up | | **In transit** | Shipments that are picked up, in transit, at a sorting center, or out for delivery | | **Delivered** | Shipments that reached their destination | | **Delivery failed** | Shipments where delivery failed | ### Shipment Detail [#shipment-detail] Click the **Manage shipment** icon (sliders) on a shipment to open its detail panel. To change only the carrier service or the tracking details, use the pencil icon (**Edit**) instead. The detail panel shows: **Tracking progress**. A 5-step visual tracker: Shipping label generated, waiting for carrier pickup. Carrier has collected the package. Package is on its way to the destination. Package is with the local delivery driver. Package has been delivered to the customer. **Shipment details**. Shipped date, received date, and tracking number (linked to tracking URL if provided). **Products**. The items included in this shipment with their fulfillment status. **Timeline**. A chronological log of every event for this shipment. Each event records the status, date, location, and an optional description. ### Adding Tracking Events [#adding-tracking-events] Click **Add event** in the shipment detail panel to log a new tracking update. The **Status** list only offers the statuses that can follow the current one (after **Label created**, for example: **Picked up** or **Returned**). Set **Occurred at**, which cannot be earlier than the last event, and optionally add a **Location** and a **Description**. This is useful when you receive updates from your carrier and want to keep the timeline accurate. Once a shipment is **Returned**, no status can follow and the **Add event** button disappears. Recording **Picked up** marks the shipment's items as shipped and updates the order's shipping status. Recording **Delivered** has the same effect as **Mark as delivered** below. ### Marking as Delivered [#marking-as-delivered] When a shipment is **Out for delivery**, a **Mark as delivered** button appears on its row in the **Shipments** table. Click it and confirm. This updates the shipment and its items to Delivered. When every item of the order is delivered and the order is **Processing**, the order automatically moves to **Completed**. ## Typical Order Flow [#typical-order-flow] Here's how a standard order moves through the system: A customer completes checkout. The order appears as **New** with payment **Pending** and shipping **Unfulfilled**. Depending on your payment method, the payment status changes to **Paid** (automatic capture) or **Authorized** (manual capture). If authorized, you capture it when ready. Click **Start processing** to indicate you're preparing the order. The order moves to **Processing**. Click **Create Shipping Label**, check the carrier service, add tracking info, and keep the items to ship. The shipment starts as **Label created**. Add tracking events as the carrier provides updates. When you record **Picked up**, the shipping status changes to **Shipped** (or **Partially shipped** if some items are not in a shipment yet). The shipment timeline shows the package's journey. Mark the shipment as delivered. Once every item is delivered, the order status automatically changes to **Completed**. ## Abandoned Carts [#abandoned-carts] Sometimes customers add items to their cart but leave without completing checkout. Shopper tracks these as abandoned carts, giving you visibility into potential lost sales. A cart is considered abandoned when it has items but no activity for a configurable period (default: 60 minutes). ### Viewing Abandoned Carts [#viewing-abandoned-carts] To see abandoned carts: 1. Go to **Orders** in the sidebar 2. Click **Abandoned Carts**, listed under **Orders**. It opens its own page The abandoned carts list shows each cart's number (**#**), the **Customer** (or **Guest** for shoppers who were not logged in), the number of **Items**, the **Currency**, the **Channel**, when the cart was created (**Created At**), and when it was last active (**Last Activity**). You can filter the list by customer, creation date, or channel. ### Cart Details [#cart-details] Click the eye icon (**View details**) on an abandoned cart to view its contents. The detail panel shows when the cart was created, the customer's name and email (or **Guest**), the channel, the items with their quantity and price, and the shipping and billing addresses if the customer entered them. ### What You Can Learn [#what-you-can-learn] Abandoned carts help you understand: - **Which products are being abandoned** to identify pricing or UX issues - **How far customers got in checkout** to improve your checkout flow: with the starter kit checkout, a cart with a shipping address got past the address step - **Whether logged-in customers abandon more than guests** to target recovery efforts Look for patterns in abandoned carts. If many customers abandon carts with the same product, the price may be too high or the shipping cost may be surprising at checkout. ### Automatic Cleanup [#automatic-cleanup] Shopper includes a cleanup task that deletes unfinished carts not updated for 30 days, to keep your database lean. It runs automatically once your developer schedules it, and they can change the 30-day threshold in the [Cart configuration](/2.x/cart#pruning). For developer details on querying abandoned carts and building recovery email flows, see the [Cart documentation](/2.x/cart#abandoned-carts). For developer details, see the [Orders documentation](/2.x/orders). # Managing Reviews (/2.x/user-guide/sales/reviews) Customer reviews build trust and help other shoppers make purchasing decisions. Shopper allows you to manage and moderate reviews on your products. ## Overview [#overview] The Reviews section allows you to: - View all product reviews - Approve or reject reviews - Respond to customer feedback - Monitor review ratings ## Accessing Reviews [#accessing-reviews] Click on **Reviews** in the sidebar to access review management. ## Review List [#review-list] The review list displays all reviews submitted by customers: | Column | Description | |--------|-------------| | **Product** | The reviewed product | | **Customer** | Who wrote the review | | **Rating** | Star rating (1-5) | | **Status** | Approved, pending, rejected | | **Date** | When the review was submitted | ### Empty State [#empty-state] If you don't have any reviews yet: ## Review Moderation [#review-moderation] ### Review Workflow [#review-workflow] 1. **Customer submits review** - After purchasing a product 2. **Review enters queue** - Pending moderation (if enabled) 3. **Admin reviews** - Approve, edit, or reject 4. **Published** - Approved reviews appear on product pages ### Moderation Actions [#moderation-actions] | Action | Effect | |--------|--------| | **Approve** | Review is published on the product page | | **Reject** | Review is hidden and not displayed | | **Edit** | Modify the review content (use sparingly) | | **Delete** | Permanently remove the review | ## Review Details [#review-details] Each review contains: - **Rating** - Star rating from 1 to 5 - **Title** - Review headline - **Content** - Full review text - **Author** - Customer name or anonymous - **Date** - Submission date - **Verified purchase** - If the customer bought the product ## Responding to Reviews [#responding-to-reviews] You can respond to reviews to: - Thank customers for positive feedback - Address concerns in negative reviews - Provide additional product information - Show that you value customer input ### Response Best Practices [#response-best-practices] Always maintain a professional tone, even for negative reviews. Quick responses show you care about customer feedback. Offer solutions for any issues mentioned in reviews. Appreciate customers who take time to review. ## Review Guidelines [#review-guidelines] Consider establishing review guidelines for your store: ### What to Approve [#what-to-approve] - Honest product feedback (positive or negative) - Helpful information for other shoppers - Verified purchase reviews ### What to Reject [#what-to-reject] - Spam or promotional content - Offensive language or personal attacks - Reviews for wrong products - Fake or misleading reviews - Reviews containing personal information ## Impact of Reviews [#impact-of-reviews] Reviews affect your business in several ways: | Impact | Description | |--------|-------------| | **Trust** | Positive reviews build credibility | | **SEO** | Review content helps search rankings | | **Conversion** | Products with reviews convert better | | **Feedback** | Learn what customers like/dislike | ## Best Practices [#best-practices] Encourage reviews by sending follow-up emails after purchase, making the review process easy, and showing appreciation for customer feedback. - **Enable review reminders** - Automated emails asking for reviews - **Moderate consistently** - Apply the same standards to all reviews - **Learn from feedback** - Use negative reviews to improve products - **Showcase reviews** - Display reviews prominently on product pages - **Respond to all reviews** - Especially negative ones, to show you care For developer details, see the [Reviews documentation](/2.x/reviews). # Shipping Carriers (/2.x/user-guide/store-setup/carriers) Carriers are the shipping providers that deliver your products to customers. You can add carriers like UPS, FedEx, DHL, or your own local delivery service, and configure delivery options with pricing for each [shipping zone](/2.x/user-guide/store-setup/zones). Shopper supports two types of carriers: - **Manual carriers** where you set flat-rate prices for each delivery option - **API-connected carriers** that fetch real-time shipping rates from the carrier's system (UPS, FedEx, USPS) ## Accessing Carriers [#accessing-carriers] 1. Click on **Settings** in the sidebar 2. Select **Carriers** from the settings menu The carriers list shows all your configured carriers with their driver type, status, and last update date. You can enable or disable a carrier directly from the list using the status toggle. ## Adding a Carrier [#adding-a-carrier] To add a new shipping carrier: 1. Click the **Add carrier** button 2. Fill in the carrier details 3. Click **Save** ### Carrier Fields [#carrier-fields] | Field | Required | Description | |-------|----------|-------------| | **Carrier name** | Yes | The carrier's name (e.g., "UPS", "Local Delivery", "Colissimo") | | **Driver** | Yes | How rates are calculated. Defaults to **Manual** (custom rates per zone). Choose a provider like **UPS** for real-time rates | | **Website** | No | The carrier's website URL | | **Description** | No | A short description of the carrier | ### Choosing a Driver [#choosing-a-driver] The driver determines how shipping rates are calculated: | Driver | How it works | When to use | |--------|-------------|-------------| | **Manual** | You set fixed prices for each delivery option | Local delivery, flat-rate shipping, free shipping | | **UPS** | Rates are fetched from the UPS API in real time | You have a UPS account and want dynamic pricing | | **FedEx** | Rates are fetched from the FedEx API in real time | You have a FedEx account and want dynamic pricing | | **USPS** | Rates are fetched from the USPS API in real time | You ship within the United States | API-connected drivers (UPS, FedEx, USPS) require API credentials to be configured by your developer. If a driver shows a "Not configured" badge in the dropdown, the credentials have not been set up yet. See the [Carriers developer documentation](/2.x/carriers) for setup instructions. ## Managing Carriers [#managing-carriers] ### Editing a Carrier [#editing-a-carrier] To update a carrier's information: 1. Click the pencil icon next to the carrier you want to modify 2. Update the fields you want to change 3. Click **Save changes** ### Enabling or Disabling a Carrier [#enabling-or-disabling-a-carrier] You can quickly enable or disable a carrier without editing it by toggling the **Status** switch directly in the carriers list. Disabled carriers are not shown as shipping options during checkout. ### Deleting a Carrier [#deleting-a-carrier] To remove a carrier: 1. Click the trash icon next to the carrier 2. Confirm the deletion Deleting a carrier does not remove its delivery options, and a carrier that still has delivery options cannot be deleted. Remove its options from each zone first. If you have active orders using this carrier's shipping, consider disabling it instead of deleting it. ## Setting Up Delivery Options [#setting-up-delivery-options] After creating a carrier, you need to add delivery options with pricing. Delivery options are configured per [zone](/2.x/user-guide/store-setup/zones), so the same carrier can have different options and prices for different regions. To add a delivery option: 1. Go to **Settings > Zones** 2. Select the zone where you want to add shipping options 3. In the **Shipping Options** section, click **Add Option** 4. In the panel that opens (for example "Shipping Option for the Europe zone"), fill in the delivery details and select the carrier. The **Carriers** list only shows the carriers added to this zone 5. Click **Save** ### Delivery Option Fields [#delivery-option-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | The option name shown at checkout (e.g., "Standard Delivery", "Express 24h"). Each name can be used once per zone | | **Price** | Yes | The shipping price for this option in the zone's currency. Enter 0 for free delivery | | **Carriers** | Yes | The carrier that provides this delivery option, chosen among the carriers added to the zone | | **Description** | No | Details about delivery time, up to 200 characters | | **Visibility** | No | Off by default. Turn it on to make the option available in your store | | **Metadata** | No | Optional key-value data for custom use | Create multiple delivery options for the same carrier to offer different speed/price tiers. For example, a carrier could have "Standard (3-5 days)" at $5.99 and "Express (next day)" at $14.99. ### Viewing Delivery Options [#viewing-delivery-options] All delivery options for a zone are displayed in the zone's detail page under the **Shipping Options** section. Each option shows the carrier logo (when the carrier has one), the option name with an **Enabled** or **Disabled** badge, its description, and its price. ### Editing or Removing Delivery Options [#editing-or-removing-delivery-options] To edit a delivery option, click the pencil icon next to it. To remove it, click the trash icon and confirm. ## Common Setups [#common-setups] Here are typical carrier configurations for different store types: ### Local Business [#local-business] | Carrier | Option | Price | |---------|--------|-------| | Local Delivery | Same-day delivery | $8.00 | | Local Delivery | In-store pickup | Free | ### National Store [#national-store] | Carrier | Option | Price | |---------|--------|-------| | Standard Shipping | 5-7 business days | $5.99 | | Express Shipping | 2-3 business days | $12.99 | | Free Shipping | Free delivery (5-7 business days) | Free | ### International Store [#international-store] | Carrier | Option | Price | |---------|--------|-------| | UPS (API) | Ground, Express, Overnight | Real-time rates | | DHL | International Express | $24.99 | | Free Shipping | Free delivery, added in the domestic zone only | Free | ## Free Shipping [#free-shipping] To offer free shipping: 1. Create a carrier named "Free Shipping" 2. Add this carrier to the zone's **Carriers** (see [Shipping Zones](/2.x/user-guide/store-setup/zones)) 3. Add a delivery option with a **Price** of **0** and use the description to say what it includes (e.g., "Delivered in 5-7 business days") A delivery option has no minimum order amount: a free option is offered on every order in its zone. To limit free shipping to some regions, add the free option only in those zones. You can combine free shipping with paid options. Customers see all available options at checkout and choose the one they prefer. ## Best Practices [#best-practices] Use descriptive names that include delivery time: "Standard (3-5 days)" is better than just "Standard". Set different prices for different zones. Domestic shipping is usually cheaper than international. Give customers at least 2 shipping options: a budget option and a faster option. After setting up carriers, place a test order to verify shipping options appear correctly. For developer details on carriers, shipping drivers, and custom driver integration, see the [Carriers documentation](/2.x/carriers). # Currencies (/2.x/user-guide/store-setup/currencies) Currencies define what monetary units your store uses for pricing and transactions. Proper currency configuration is essential for displaying correct prices to your customers. ## Accessing Currency Settings [#accessing-currency-settings] Currencies are managed in two places: - **Settings > Currencies** lists every currency available in Shopper. This is where you enable or disable currencies and set their exchange rates. - **Settings > General**, in the **Store currency** section, is where you pick the currencies your products are sold in and your default currency (see [General Settings](/2.x/user-guide/store-setup/general-settings#store-currency)). To pick your store currencies: 1. Click on **Settings** in the sidebar 2. Select **General** from the settings menu 3. Scroll to the **Store currency** section, select your currencies in **Currencies**, choose your **Default currency**, then click **Save** ## Default Currency [#default-currency] Your store has one default currency, chosen in the **Default currency** field of the **Store currency** section. It is used for: - Product pricing - Order totals - Reports and analytics - Default display currency Choose your default currency carefully during initial setup, as changing it later may affect existing product prices and orders. ## Currency Configuration [#currency-configuration] Click **Currencies** in the settings menu to see the table of all currencies available in Shopper: | Column | Description | |--------|-------------| | **Name** | The currency name (e.g., Euro, US Dollar) | | **Code** | The ISO 4217 code (e.g., USD, EUR, GBP) | | **Symbol** | The currency symbol (e.g., $, €, £) | | **Exchange rate** | The rate relative to your store's default currency. Leave it at 1 for the default currency | | **Status** | A toggle that enables or disables the currency | The exchange rate is the only value you can edit: click the edit icon on a currency's row, enter the rate in the **Edit exchange rate** window, then click **Save changes**. The name, code and symbol come from the currency list built into Shopper and cannot be changed. There are no symbol position, separator or decimal settings. The admin formats amounts according to the admin language, and the number of decimals follows the currency: currencies without cents, such as JPY or XAF, are shown without decimals. ## Common Currency Formats [#common-currency-formats] Here are some examples of how different currencies are typically formatted in their home markets. In the admin, the format follows the admin language instead: | Currency | Code | Format Example | |----------|------|----------------| | US Dollar | USD | $1,234.56 | | Euro | EUR | €1.234,56 | | British Pound | GBP | £1,234.56 | | Japanese Yen | JPY | ¥1,234 | ## Enabling Additional Currencies [#enabling-additional-currencies] If your store serves international customers, you may want to sell in additional currencies. All currencies are enabled on a new install, so you only need to pick yours: 1. Click on **Settings** in the sidebar, then **Currencies** 2. Check that the currencies you want to support have their **Status** toggle on. To enable or disable several at once, select their rows, open **Bulk actions** and choose **Enable** or **Disable** 3. Set the exchange rates if applicable, with the edit icon on each row 4. Go to **Settings > General** and add the currencies to the **Currencies** field of the **Store currency** section, then click **Save** You cannot add a new currency from the admin: the list is the one built into Shopper. A disabled currency no longer appears in the **Currencies** and **Default currency** choices of the General settings. Exchange rates are not updated automatically. If you rely on them, update them regularly, or ask your developer to keep them in sync with a currency conversion service. ## How Currencies Work with Zones [#how-currencies-work-with-zones] Each [zone](/2.x/user-guide/store-setup/zones) is assigned one currency. When a customer checks out from a zone, they see prices and pay in that zone's currency. This means: - A product can have different prices in different currencies (e.g., $29.99 USD in the US zone, 27.99 EUR in the Europe zone) - You set prices per currency on each product from the [product edit page](/2.x/user-guide/catalog/products/managing-products) - The zone determines which currency the customer sees at checkout Shopper does not automatically convert prices between currencies. You set each price manually per currency. This gives you full control over pricing strategy in each market. For developer details, see the [Currencies documentation](/2.x/currencies). # General Settings (/2.x/user-guide/store-setup/general-settings) The General Settings page allows you to configure your store's basic information. This is one of the first things you should set up when starting with Shopper. ## Accessing General Settings [#accessing-general-settings] 1. Click on **Settings** in the sidebar 2. Select **General** from the settings menu The page opens with the title **Store Setting**. ## Store Information [#store-information] ### Store Details [#store-details] Configure the basic information about your store: | Field | Description | |-------|-------------| | **Store name** | The name of your store as it will appear to customers (required) | | **Email address** | The main contact email for your store, used by customers who need to reach you (required) | | **Phone number** | Contact phone number for customers who want to call you (optional) | ### Assets [#assets] | Field | Description | |-------|-------------| | **Logo** | Your store logo, available to your storefront. JPEG, PNG, WebP or AVIF, up to 1 MB | | **Cover photo** | A cover image for your store. Same formats and size limit as the logo | ### Store Address [#store-address] Set your store's legal name and physical address. This information may be used for: - Invoice generation - Shipping calculations - Legal compliance | Field | Description | |-------|-------------| | **Legal name of the company** | The registered name of your business (required) | | **About** | A description of your store, written in a rich text editor (optional) | | **Street Address** | Street and number (required) | | **City** | City (required) | | **Postal / Zip code** | Postal code (required) | | **State** | State, region or province (optional) | | **Country** | Country, picked from a searchable list (optional) | ### Store Currency [#store-currency] | Field | Description | |-------|-------------| | **Currencies** | The currencies your products are sold in. Pick at least one. Only the currencies enabled on the [Currencies](/2.x/user-guide/store-setup/currencies) settings page are listed | | **Default currency** | The main currency displayed on your store, chosen among the currencies selected above (required) | ### Social Links [#social-links] Add the full URL of your **Facebook**, **Instagram** and **Twitter** pages so customers can find your official accounts. Each field is optional. ## Store Initialization [#store-initialization] When you first set up Shopper, you'll go through an initialization wizard that helps you configure the essential settings. ### Step 1 - Store Information [#step-1---store-information] The **Information** tab, titled **Step 1 - Shop information** on screen. Fill in the **Store name** and **Email address**, then the **Country** (optional), the **Currencies** your store sells in and the **Default currency**, and click **Next**. ### Step 2 - Address Setup [#step-2---address-setup] The **Address** tab, titled **Step 2 - Address information** on screen. Fill in the **Street Address**, **Postal / Zip code** and **City**, and optionally the **State** and **Phone number**, then click **Next**. This address also becomes your default inventory location. ### Step 3 - Social Links [#step-3---social-links] The **Social Links** tab, titled **Step 3 - Social links** on screen. Add the full URL of your **Facebook**, **Instagram** and **Twitter** pages if you want to, then click **Save** to finish the setup and open the dashboard. ## Saving Changes [#saving-changes] After making any changes to your settings: 1. Review your changes 2. Click the **Save** button at the bottom of the form 3. A confirmation message will appear when your changes are saved Make sure to keep your store information up to date, especially your contact email, as this is how customers and the system will reach you. For developer details, see the [Setup Store documentation](/2.x/setup-store). # Legal Pages (/2.x/user-guide/store-setup/legal) Legal pages are essential for any e-commerce store. They protect both you and your customers by clearly outlining the rules and policies of your business. ## Why Legal Pages Matter [#why-legal-pages-matter] Legal pages help you: - Comply with local and international regulations (GDPR, CCPA, etc.) - Protect your business from liability - Build trust with customers - Define clear terms for transactions ## Accessing Legal Settings [#accessing-legal-settings] 1. Click on **Settings** in the sidebar 2. Select **Legal** from the settings menu ## Available Legal Pages [#available-legal-pages] Shopper allows you to configure the following legal documents, each in its own tab on the **Legal policy** page: | Page | Purpose | |------|---------| | **Privacy policy** | Explains how you collect, use, and protect customer data | | **Terms of use** | Defines the rules and guidelines for using your store | | **Shipping policy** | Details your shipping methods, times, and costs | | **Refund policy** | Outlines your return and refund procedures | ## Editing Legal Content [#editing-legal-content] To edit a legal page: 1. Click the tab of the policy you want to edit: **Privacy policy**, **Terms of use**, **Shipping policy** or **Refund policy** 2. Turn on **Enabled** when the policy is ready to be shown to customers 3. Write or paste your text in the **Content** editor (required) 4. Click **Save** to store your changes Each tab has its own **Save** button, which saves only the policy of that tab. ## Writing Your Legal Pages [#writing-your-legal-pages] ### Terms of Service [#terms-of-service] Your terms, written in the **Terms of use** tab, should include: - Acceptance of terms - User responsibilities - Prohibited activities - Intellectual property rights - Limitation of liability - Dispute resolution ### Privacy Policy [#privacy-policy] Your Privacy Policy should cover: - What data you collect - How you use the data - How you protect customer data - Cookie usage - Third-party services - Customer rights regarding their data ### Refund Policy [#refund-policy] Your Refund Policy should explain: - Eligibility for refunds - Timeframe for requesting refunds - Refund process - Exceptions - Exchange options Consider consulting with a legal professional to ensure your policies comply with applicable laws in your jurisdiction and the regions where you sell. ## Displaying Legal Pages on Your Storefront [#displaying-legal-pages-on-your-storefront] Shopper stores the content of your legal pages, but does not create the storefront routes automatically. Your developer needs to set up the pages on your website to display this content. Once configured, legal pages are typically: - Linked in your website footer - Shown during checkout when required - Accessible from customer account pages Legal pages are not published to your storefront automatically. Ask your developer to create the routes and views to display them. See the [Legal developer documentation](/2.x/legal) for implementation details. For developer details, see the [Legal documentation](/2.x/legal). # Inventory Locations (/2.x/user-guide/store-setup/locations) Locations in Shopper represent physical places where you store your inventory. This could be warehouses, retail stores, or any other location where you keep products. ## Why Use Multiple Locations? [#why-use-multiple-locations] Managing inventory across multiple locations allows you to: - Track stock levels at different warehouses - Choose which location supplies stock first when an order is placed - Manage inventory for physical retail stores - Keep accurate stock counts across your business ## Accessing Locations [#accessing-locations] 1. Click on **Settings** in the sidebar 2. Select **Inventories** from the settings menu ## Default Inventory [#default-inventory] When you set up Shopper, a default inventory location is created for you. It is marked **Default** in the list and receives the initial stock you enter when you create a product. ## Creating a New Location [#creating-a-new-location] To add a new inventory location: 1. Click the **New location** button on the Locations page 2. Fill in the location details 3. Click **Save** ### Location Fields [#location-fields] The form has two sections: **Details** and **Location address**. | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | A descriptive name for the location (e.g., "Main Warehouse"). You see this name in areas like products | | **Email address** | Yes | Contact email for this location. Each location needs its own email address | | **Description** | No | Additional notes about the location | | **Set as default location** | No | Makes this location the default one (see [Setting a Default Location](#setting-a-default-location)) | | **Priority** | Yes | A number, 0 by default. When an order takes stock from several locations, lower values are used first | | **Street Address** | Yes | Physical address of the location | | **Apartment, suite, etc.** | No | Additional address line | | **City** | Yes | City where the location is situated | | **State** | No | State, province, or region | | **Postal / Zip code** | Yes | Postal or ZIP code | | **Country** | Yes | Country selection | | **Phone number** | No | Contact phone number | ## Editing a Location [#editing-a-location] To modify an existing location: 1. Click the pencil icon next to the location in the list 2. Update the desired fields 3. Click **Save** to apply changes ## Setting a Default Location [#setting-a-default-location] One location is the default. It is marked **Default** in the locations list. The default location: - Receives the initial stock you enter when you create a product or a variant - Cannot be deleted: the delete icon is hidden for it To change the default location, edit another location, turn on **Set as default location**, and click **Save**. The previous default location stops being the default. Keep your location information accurate, especially addresses, as they may be used for shipping calculations and customer communications. For developer details, see the [Locations documentation](/2.x/locations). # Payment Methods (/2.x/user-guide/store-setup/payment-methods) Payment methods define how customers can pay at checkout. You can offer credit card payments via Stripe, cash on delivery, bank transfers, or mobile money, and restrict each method to specific [zones](/2.x/user-guide/store-setup/zones). ## Accessing Payment Methods [#accessing-payment-methods] 1. Click on **Settings** in the sidebar 2. Select **Payment methods** from the settings menu The payment methods list shows all configured methods with their driver, status, and last update date. ## Adding a Payment Method [#adding-a-payment-method] To add a new payment method: 1. Click the **Add payment method** button 2. Fill in the payment method details 3. Click **Save** ### Payment Method Fields [#payment-method-fields] | Field | Required | Description | |-------|----------|-------------| | **Provider** | Yes | The name shown to customers at checkout (e.g., "Credit Card", "PayPal"). Shopper creates the method's identifier from it | | **Driver** | Yes | The payment provider that processes this method. Defaults to **Manual** for offline payments; choose a provider such as **Stripe** for online processing | | **Provider Documentation URL** | No | External URL for the payment provider | | **Additional details** | No | Shown to customers when they choose a payment method | | **Provider instructions** | No | Shown to customers after they place an order with this method (e.g., bank transfer details) | ### Understanding Drivers [#understanding-drivers] The driver connects a payment method to a payment provider: | Driver | How it works | Example | |--------|-------------|---------| | **Manual** | No online processing. You handle payment outside of Shopper | Cash on delivery, bank transfer, check | | **Stripe** | Payments processed via Stripe (requires API keys) | Credit cards, Apple Pay, Google Pay | Only **Manual** is built in. Stripe appears in the **Driver** list once your developer has installed the Stripe package, and it requires API credentials configured by your developer. If a driver shows "Not configured" in the dropdown, the API keys have not been set up yet. See the [Payments developer documentation](/2.x/payments) for setup instructions. ## Assigning to Zones [#assigning-to-zones] Payment methods are assigned to [zones](/2.x/user-guide/store-setup/zones) when creating or editing a zone. A payment method only appears at checkout if it belongs to the customer's zone. To make a payment method available in a zone: 1. Go to **Settings > Zones** 2. Select the zone and click the pencil icon at the top right of its details 3. In the **Providers** section, select the payment method in the **Payment Methods** field 4. Click **Save** ## Managing Payment Methods [#managing-payment-methods] ### Editing a Payment Method [#editing-a-payment-method] Click the pencil icon next to a method, update the fields, and click **Save changes**. ### Enabling or Disabling [#enabling-or-disabling] Toggle the **Status** switch in the list to quickly enable or disable a payment method. Disabled methods are not shown at checkout. ### Deleting a Payment Method [#deleting-a-payment-method] Click the trash icon and confirm. Orders that used this method are kept, but they no longer show a payment method. ## Common Setups [#common-setups] | Payment Method | Driver | Best For | |----------------|--------|----------| | Credit Card | Stripe | Online stores accepting card payments | | Cash on Delivery | Manual | Local deliveries where customers pay on receipt | | Bank Transfer | Manual | B2B orders or high-value purchases | | Mobile Money | Manual | Markets where mobile payments are common (Africa, Asia) | ## Best Practices [#best-practices] Customers are more likely to complete checkout when they see a payment method they trust. Some methods work only in certain regions. Assign them to the right zones. For manual methods like bank transfers, provide clear payment instructions so customers know what to do after ordering. Use your payment provider's test/sandbox mode to verify the checkout flow before going live. For developer details on payment drivers, custom providers, and transaction management, see the [Payments documentation](/2.x/payments). # Taxes (/2.x/user-guide/store-setup/taxes) Taxes are calculated automatically at checkout based on where the customer's order is being shipped. You define tax zones (geographic regions), set percentage rates for each zone, and Shopper handles the calculation for every order. Shopper supports both **tax-inclusive pricing** (VAT, common in Europe where tax is included in the displayed price) and **tax-exclusive pricing** (sales tax, common in the US where tax is added at checkout). ## Accessing Tax Settings [#accessing-tax-settings] 1. Click on **Settings** in the sidebar 2. Select **Taxes** from the settings menu ## Creating a Tax Zone [#creating-a-tax-zone] A tax zone maps to a country (and optionally a province/state). To create one: 1. Click the **plus icon** next to the **Taxes** heading. The **Add tax zone** panel opens 2. Select the **Country** 3. Optionally enter a **Province / State code** in ISO 3166-2 format (e.g., "US-CA" for California) 4. Turn on **Incl. tax** if your prices include tax (**tax-inclusive**), or leave it off if tax is added at checkout (**tax-exclusive**) 5. Click **Save** ### Tax Zone Fields [#tax-zone-fields] | Field | Required | Description | |-------|----------|-------------| | **Country** | Yes | The country this tax zone applies to | | **Province / State code** | No | A province or state code in ISO 3166-2 format, country code first (e.g., "US-CA", "US-NY", "FR-IDF"). Leave empty for country-wide rules | | **Name** | No | A display name for this zone (e.g., "California", "Île-de-France") | | **Incl. tax** | No | If ON, prices already include tax (VAT). If OFF, tax is added at checkout (sales tax). The tax zones list shows an **Incl. tax** or **Excl. tax** badge | | **Tax provider** | No | Leave on **System (default)** to use the rates you set below. Other providers appear here once your developer has enabled them | | **Metadata** | No | Optional key-value data for custom use | ### Tax-Inclusive vs Tax-Exclusive [#tax-inclusive-vs-tax-exclusive] | Setting | How it works | Common in | |---------|-------------|-----------| | **Incl. tax** ON | A product listed at 100 EUR already includes tax. The tax amount is extracted from the price. | Europe (VAT), Australia (GST) | | **Incl. tax** OFF (**Excl. tax**) | A product listed at $100 has tax added on top at checkout (e.g., $100 + $10 tax = $110). | United States, Canada | ## Adding Tax Rates [#adding-tax-rates] Each tax zone needs at least one tax rate. The **default rate** applies to all products in the zone unless a more specific override exists. To add a rate: 1. Select a tax zone from the list 2. Click **Add Rate** above the **Tax Rates** table. A panel titled with the tax zone (e.g., "Tax rate for France") opens 3. Enter the **Name**, **Code**, and **Rate** 4. Turn on **Default** if this is the zone's primary rate 5. Click **Save** ### Tax Rate Fields [#tax-rate-fields] | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | Rate name shown on invoices (e.g., "TVA 20%", "State Sales Tax") | | **Code** | No | Machine-readable identifier (e.g., "FR_VAT_STANDARD") | | **Rate** | Yes | The percentage (e.g., 20 for 20%, 5.5 for 5.5%) | | **Default** | No | If ON, this rate applies to all products that don't match a specific override | | **Combinable** | No | Shown as "Allow this rate to stack with parent zone rates." The built-in tax calculation applies one rate per product, so this setting has no effect unless your developer has connected a tax provider that uses it | | **Metadata** | No | Optional key-value data for custom use | The **Tax Rates** table lists each rate with its **Name**, **Code**, **Rate**, **Default**, **Targets** (the number of override targets), and **Combinable** columns. Use the pencil icon to edit a rate and the trash icon to delete it. ### Multiple Rates per Zone [#multiple-rates-per-zone] Some countries have different tax rates for different types of products. For example, France has: | Rate | Percentage | Applies to | |------|-----------|------------| | Standard VAT | 20% | Most products | | Reduced VAT | 5.5% | Food, books | | Zero VAT | 0% | Certain essential goods | Create each rate in the same zone. Create the standard rate with **Add Rate** and turn on **Default**: it applies to all products. Create each other rate as a **rate override** and pick the products, product types, or categories it applies to. A rate that is neither the default nor linked to targets is never applied. ## Rate Overrides [#rate-overrides] Overrides let you apply a non-default tax rate to specific products, product types, or categories. For example, you can set food products to use the 5.5% reduced rate instead of the default 20%. To create an override: 1. Select a tax zone from the list 2. Click **Create Override** above the **Tax Rates** table. A panel titled with the tax zone (e.g., "Override rate for France") opens 3. Enter the **Name** and **Rate**, and optionally a **Code**. An override is never the default rate, so the form has no **Default** toggle 4. Under **Targets**, click **Add target**, then choose a **Target type** and a **Target value**. Add as many targets as you need 5. Click **Save** ### Override Types [#override-types] | Type | What it targets | Example | |------|----------------|---------| | **Product types** | All products of a type (Standard, Virtual, External) | Virtual products with digital tax rate | | **Products** | A specific product | A book with zero-rated VAT | | **Categories** | All products in a category | Food category with reduced rate | ## Best Practices [#best-practices] Set up one default rate per zone. Add overrides only when needed for specific product categories. Tax rules vary by country. Consult your accountant or tax advisor for the correct rates. Test checkout with both tax-inclusive (VAT) and tax-exclusive (sales tax) zones to verify prices display correctly. Give each rate a clear code (e.g., "FR_VAT_20") for easy identification in reports and invoices. For developer details on tax calculation, custom tax providers, and the tax pipeline, see the [Taxes documentation](/2.x/taxes). # Shipping Zones (/2.x/user-guide/store-setup/zones) A shipping zone is a group of countries that share the same currency, payment methods, and delivery options. For example, you might have a "Europe" zone with EUR currency and Colissimo/DHL delivery, and a "North America" zone with USD currency and UPS/FedEx delivery. Zones are central to how your store operates. When a customer checks out, Shopper matches their shipping address to a zone and uses it to determine: - Which **currency** to charge in - Which **payment methods** to show (Stripe, PayPal, Cash on Delivery) - Which **delivery options** are available and at what price Tax rules do not come from the zone: they follow the customer's country and state, as set in [Taxes](/2.x/user-guide/store-setup/taxes). You need at least one enabled zone before customers can complete checkout. ## Accessing Zones [#accessing-zones] 1. Click on **Settings** in the sidebar 2. Select **Zones** from the settings menu The zones page lists your zones on the left. Each zone shows its name and code, an **Enabled** or **Disabled** badge, and its carriers and countries. Select a zone to show its details and shipping options on the right. ## Creating a Zone [#creating-a-zone] To create a new zone: 1. Click the **plus icon** next to the **Zones** heading. The **Add zone** panel opens 2. Fill in the zone details 3. Click **Save**. The zones page opens with the new zone selected ### Zone Fields [#zone-fields] **Payment Methods** and **Carriers** sit in the **Providers** section of the form, where you add the delivery and payment methods available in the zone. | Field | Required | Description | |-------|----------|-------------| | **Name** | Yes | A descriptive name (e.g., "Europe", "North America", "Africa") | | **Code** | No | A short identifier code (e.g., "EU", "NA", "AF") | | **Countries** | Yes | The countries included in this zone. A country can only belong to one zone. | | **Currency** | Yes | The currency used for pricing and checkout in this zone, chosen among the currencies configured for your store. Each zone has exactly one currency. | | **Visibility** | No | Whether this zone is active for customers. Disabled zones are not matched during checkout. | | **Payment Methods** | Yes | Which payment methods are available in this zone (e.g., Stripe, Cash on Delivery) | | **Carriers** | Yes | Which shipping carriers serve this zone (e.g., UPS, Colissimo, Local Delivery) | | **Metadata** | No | Optional key-value data for custom use | Countries already assigned to another zone are grayed out in the country selector. Each country can only belong to one zone. ## Zone Detail Page [#zone-detail-page] Select a zone in the zones list to show its details on the same page. The header shows the zone's name and code, with a pencil icon to edit it and a trash icon to delete it. Below come its currency, countries, payment methods, carriers, and metadata, then the **Shipping Options** section with its delivery options. ## Editing a Zone [#editing-a-zone] To update a zone's settings: 1. Select the zone in the zones list 2. Click the pencil icon at the top right of the zone details 3. Modify the fields you want to change 4. Click **Save** You can change the zone's name, code, countries, currency, payment methods, and carriers at any time. Changing a zone's currency affects how prices are displayed to customers in that region. Make sure you have [prices](/2.x/user-guide/marketing/pricing) configured in the new currency before switching. ## What's Configured Inside a Zone [#whats-configured-inside-a-zone] Each zone connects three things together for a region: | What | Purpose | Where to manage | |------|---------|-----------------| | **Countries** | Which countries belong to this zone | Zone form | | **Currency** | What currency customers pay in | Zone form | | **Payment methods** | How customers can pay (Stripe, Cash on Delivery, etc.) | Zone form (select from available methods) | | **Carriers** | Which shipping providers serve this zone | Zone form (select from available carriers) | | **Shipping options** | Specific delivery options with pricing | **Shipping Options** section of the zone (see [Carriers](/2.x/user-guide/store-setup/carriers)) | | **Tax rules** | Tax rates applied at checkout. Not part of the zone: they follow the customer's country and state | Managed separately in [tax settings](/2.x/user-guide/store-setup/taxes) | You need to create [carriers](/2.x/user-guide/store-setup/carriers) and payment methods before you can assign them to a zone. Set those up first, then create your zones. ## Zones in Orders [#zones-in-orders] The orders list can show which zone applies to each order. This helps you understand which shipping and payment rules were used. The **Zone** column is hidden by default: turn it on from the **Column manager** above the table. To see only the orders of one zone, open **Filter** and pick a **Zone**. ## Common Zone Setups [#common-zone-setups] ### Single-Country Store [#single-country-store] If you only sell domestically, create one zone: | Zone | Countries | Currency | Carriers | |------|-----------|----------|----------| | Domestic | Your country | Your currency | Local carriers | ### Multi-Region Store [#multi-region-store] For stores selling across regions: | Zone | Countries | Currency | Carriers | |------|-----------|----------|----------| | Domestic | France | EUR | Colissimo, Chronopost | | Europe | Germany, Belgium, Spain, Italy | EUR | DHL, UPS | | North America | United States, Canada | USD | FedEx, UPS | | Africa | Cameroon, Senegal, Ivory Coast | XAF | DHL Express | ### Global Store with Few Zones [#global-store-with-few-zones] Keep it simple with broad zones: | Zone | Countries | Currency | |------|-----------|----------| | Domestic | Your country | Your currency | | International | All others | USD | ## Best Practices [#best-practices] Begin with a domestic zone and expand to international zones as your business grows. Countries with similar shipping costs should share a zone to simplify pricing. Each zone uses one currency. If you sell in EUR and USD, you need separate zones. After configuring zones, place test orders from different countries to verify everything works. ## Related Pages [#related-pages] Set up shipping carriers and configure delivery options. Manage the currencies available in your store. Developer reference for zones, relationships, and configuration. # Extending the Admin Panel (/3.x/addons/admin-panel) An add-on extends the admin panel from its `register()` method, through the `addon*` methods of the `Shopper\ShopperPanel` instance it receives. Each method returns the panel, so the calls chain. A [disabled](/3.x/addons#disabling-an-addon) add-on is never registered, so nothing on this page applies to it. The examples continue the `acme/loyalty` add-on of [Creating an Add-on](/3.x/addons/creating), built on the skeleton: its views and translations use the `shopper-loyalty` namespace, and its permissions start with `loyalty.`. ## What an Add-on Can Register [#what-an-addon-can-register] The panel keeps what each add-on registers, then applies it at three different moments: | Method | Registers | Applied | |--------|-----------|---------| | `addonRoutes(Closure $routes)` | Routes inside the admin route group | When Shopper boots, before the add-ons' `boot()` | | `addonLivewireComponents(array $components)` | Livewire components, under a `shopper-` alias | When Shopper boots | | `addonSidebar(string $sidebarClass)` | A class that adds groups and entries to the sidebar | When Shopper boots | | `addonViews(string $namespace, string $path)` | A Blade view namespace | When Shopper boots | | `addonSettingItems(array $items)` | Entries of the settings screen | When Shopper boots | | `addonProductSections(array $sections)` | Tabs of the product edit page | When Shopper boots | | `addonStyles(array $styles)` | Stylesheets in the `` of every admin page | On each page render | | `addonScripts(array $scripts)` | Scripts at the end of every admin page | On each page render | | `renderHook(string $hook, Closure $callback)` | HTML at a named place of the layout or of a page | On each page render | Call all of them from `register()`. Shopper's service provider loads the routes while it boots, before it calls the add-ons' `boot()` methods, so `addonRoutes()` called from `boot()` is ignored. The other methods still apply when called from `boot()`. ### Routes [#routes] `addonRoutes()` takes a closure that declares routes with the `Route` facade. Shopper loads it inside its admin route group, after its own routes and the store's [custom route file](/3.x/configuration#custom-routes): ```php title="src/LoyaltyAddon.php" use Acme\Loyalty\Livewire\LoyaltyIndex; use Illuminate\Support\Facades\Route; use Shopper\ShopperPanel; public function register(ShopperPanel $panel): void { $panel->addonRoutes(function (): void { Route::prefix('loyalty') ->as('loyalty.') ->group(function (): void { Route::get('/', LoyaltyIndex::class)->name('index'); }); }); } ``` Do not add the admin prefix, the `shopper.` name prefix or the admin middleware yourself: each route already gets them. The route above answers at `/cpanel/loyalty` and is named `shopper.loyalty.index`. In detail, every add-on route gets: - The admin domain and prefix, from `shopper.admin.domain` and `shopper.admin.prefix` (`cpanel` by default). - The `shopper.` prefix on its name. - The middleware of the admin pages: cookies, session, CSRF protection and route model binding, Shopper's serving and locale middleware, authentication with the Shopper guard, the dashboard check, the sidebar resolver and the ones listed in `shopper.routes.middleware` (see [Middleware](/3.x/configuration#middleware)). The dashboard check sends users who cannot access the admin panel to its forbidden page, and everyone to the setup screen until the store has an email and an address. The routes do not check any permission. Each page checks its own, the way the skeleton's `LoyaltyIndex` calls `$this->authorize('loyalty.browse')` in `mount()`: a failed check sends the user to the admin panel's forbidden page. To check a permission on a group of routes instead, add the `can:` middleware, as the product sections below do. Keep your URLs and route names under your add-on's ID, so they do not collide with Shopper's or another add-on's. Two kinds of pages follow Shopper's own paths instead, so that its layouts recognize them: [settings pages](#settings-items) under `setting/`, and [product sections](#product-sections) under `products/{product}/edit/`. Shopper reads the add-on routes when it loads its own routes. With cached routes, the cache keeps the routes that existed when it was built, so run `php artisan optimize` (or `php artisan route:cache`) again after adding, enabling or disabling an add-on. ### Livewire Components [#livewire-components] `addonLivewireComponents()` registers Livewire components, keyed by name. Shopper registers each one with a `shopper-` prefix, like its own components: ```php title="src/LoyaltyAddon.php" use Acme\Loyalty\Livewire\LoyaltyForm; use Acme\Loyalty\Livewire\LoyaltyIndex; $panel->addonLivewireComponents([ 'loyalty.index' => LoyaltyIndex::class, 'loyalty.form' => LoyaltyForm::class, ]); ``` A view renders the second one with ``. Give every name your add-on's ID as its first segment, for the same reason as the routes. The admin panel opens forms in slide-over panels. A slide-over is a component that extends `Laravelcm\LivewireSlideOvers\SlideOverComponent`, and any component opens it by its registered name, with the arguments of its `mount()` method: ```php title="src/Livewire/LoyaltyIndex.php" $this->dispatch('openPanel', 'shopper-loyalty.form', ['memberId' => $member->id]); ``` Page components extend `Shopper\Livewire\Pages\AbstractPageComponent`, which renders them inside the admin layout, with the header and the sidebar. Settings pages and product sections use their own layouts, shown below. Leave your components open to extension, without `final`, so that a store can [replace one](/3.x/addons#customizing-an-addons-screens) with a subclass. ### Sidebar Navigation [#sidebar-navigation] `addonSidebar()` takes a class that extends `Shopper\Sidebar\AbstractAdminSidebar`. Shopper calls its `extendWith()` method with the menu each time it builds the sidebar of an admin page, and `$this->user` holds the signed-in user: ```php title="src/LoyaltyAddon.php" use Acme\Loyalty\Sidebar\LoyaltySidebar; $panel->addonSidebar(LoyaltySidebar::class); ``` The skeleton's sidebar class adds a **Loyalty** group of its own, as shown in [Creating an Add-on](/3.x/addons/creating#from-the-skeleton-to-an-admin-page). The menu merges groups and entries by label: `$menu->group()` with the label of an existing group adds to that group, and `$group->item()` with the label of an existing entry changes that entry. To place your entry in a group of Shopper, use the translation key Shopper uses for that group's label: ```php title="src/Sidebar/LoyaltySidebar.php" namespace Acme\Loyalty\Sidebar; use Shopper\Sidebar\AbstractAdminSidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; final class LoyaltySidebar extends AbstractAdminSidebar { public function extendWith(Menu $menu): Menu { $menu->group(__('shopper::pages/customers.menu'), function (Group $group): void { $group->item(__('shopper-loyalty::messages.menu'), function (Item $item): void { $item->weight(3); $item->setAuthorized($this->user->can('loyalty.browse')); $item->route('shopper.loyalty.index'); $item->setIcon('phosphor-gift'); $item->useSpa(); }); }); return $menu; } } ``` The entry now sits in the **Customers** group, after Shopper's own entries. Weights order the groups and the entries in them, lowest first: Shopper gives its groups 1 (Dashboard), 2 (Catalog), 3 (Sales and Customers) and 10 (Settings). `route()` takes the full route name, `shopper.` included, and `useSpa()` opens the page without a full reload. Hide entries with `setAuthorized()` and `can()`. `hasPermissionTo()` throws an exception when the permission does not exist yet, which breaks every admin page between the deployment of the add-on and its install command. ### Blade Views [#blade-views] `addonViews()` registers a view namespace while the add-on is enabled: ```php title="src/LoyaltyAddon.php" $panel->addonViews('loyalty', __DIR__.'/../resources/views'); ``` `view('loyalty::dashboard.top-members')` then renders `resources/views/dashboard/top-members.blade.php`. An add-on built on the skeleton does not need it: its service provider already registers the `resources/views` folder under the `shopper-loyalty` namespace, as described in [Translations and Config](#translations-and-config). That namespace exists whether the add-on is enabled or not, since the provider always runs. Use `addonViews()` for views that only make sense while the add-on is enabled, under a namespace of their own. ### Settings Items [#settings-items] `addonSettingItems()` adds entries to the settings screen. Each entry is a class that extends `Shopper\Navigation\Setting\Setting`, as described in [Adding a Settings Page](/3.x/configuration#adding-a-settings-page): ```php title="src/Navigation/LoyaltySetting.php" namespace Acme\Loyalty\Navigation; use BackedEnum; use Mckenziearts\Icons\Untitledui\Enums\Untitledui; use Shopper\Enum\SettingGroup; use Shopper\Navigation\Setting\Setting; final class LoyaltySetting extends Setting { public function name(): string { return __('shopper-loyalty::messages.settings.menu'); } public function description(): string { return __('shopper-loyalty::messages.settings.description'); } public function icon(): BackedEnum { return Untitledui::Gift; } public function url(): string { return route('shopper.settings.loyalty'); } public function order(): int { return 50; } public function group(): string { return SettingGroup::Selling->value; } } ``` `group()` returns one of the `SettingGroup` values (`store`, `selling`, `shipping` and `team`) or a string of your own, and `order()` sorts the entries of a group, lowest first. Add a `permission()` method that returns a permission name to hide the entry from users who do not hold it. Register the class with `true`, and the page's route under the `setting` prefix and the `settings.` name prefix, like Shopper's own settings pages. The entry of the main sidebar then stays highlighted on your page: ```php title="src/LoyaltyAddon.php" use Acme\Loyalty\Livewire\LoyaltySettings; use Acme\Loyalty\Navigation\LoyaltySetting; use Illuminate\Support\Facades\Route; $panel ->addonSettingItems([ LoyaltySetting::class => true, ]) ->addonRoutes(function (): void { Route::prefix('setting') ->as('settings.') ->group(function (): void { Route::get('/loyalty', LoyaltySettings::class)->name('loyalty'); }); }); ``` The boolean is the entry's initial state: `false` registers the entry hidden, and `Shopper\Navigation\Setting\SettingManager` shows it later with `enable()`. The page answers at `/cpanel/setting/loyalty`. Its component uses the settings layout, which lists every settings page next to yours, and a trait that adds the Settings breadcrumb: ```php title="src/Livewire/LoyaltySettings.php" namespace Acme\Loyalty\Livewire; use Illuminate\Contracts\View\View; use Livewire\Attributes\Layout; use Livewire\Component; use Shopper\Livewire\Concerns\WithSettingsBreadcrumbs; use Shopper\Sidebar\Breadcrumbs\Breadcrumb; use Shopper\Traits\HandlesAuthorizationExceptions; #[Layout('shopper::components.layouts.setting')] class LoyaltySettings extends Component { use HandlesAuthorizationExceptions; use WithSettingsBreadcrumbs; public function settingsPageBreadcrumbs(): array { return [ new Breadcrumb(text: __('shopper-loyalty::messages.settings.menu')), ]; } public function mount(): void { $this->authorize('system.settings'); } public function render(): View { return view('shopper-loyalty::livewire.pages.loyalty-settings') ->title(__('shopper-loyalty::messages.settings.menu')); } } ``` Shopper's settings pages require the `system.settings` permission, and so does this one. The `HandlesAuthorizationExceptions` trait turns a failed check in a later action into an "Unauthorized" notification instead of an error page. ### Product Sections [#product-sections] `addonProductSections()` adds tabs to the product edit page, next to Shopper's own (Pricing, Inventory, SEO and the others). Each tab is a class that extends `Shopper\Navigation\Product\AbstractProductSection`, and its `url()` method receives the product: ```php title="src/Navigation/PointsSection.php" namespace Acme\Loyalty\Navigation; use BackedEnum; use Mckenziearts\Icons\Untitledui\Enums\Untitledui; use Shopper\Core\Models\Contracts\Product; use Shopper\Enum\ProductSectionGroup; use Shopper\Navigation\Product\AbstractProductSection; final class PointsSection extends AbstractProductSection { public function name(): string { return __('shopper-loyalty::messages.points'); } public function icon(): BackedEnum { return Untitledui::Gift; } public function group(): string { return ProductSectionGroup::Marketing->value; } public function order(): int { return 30; } public function url(Product $product): string { return route('shopper.products.edit.points', ['product' => $product]); } } ``` `group()` returns one of the `ProductSectionGroup` values (`product`, `inventory`, `sales` and `marketing`), and `order()` sorts the tabs of a group: Shopper's SEO and Related Products tabs are in `marketing` with orders 10 and 20, so this one comes after them. Override `visible()` to hide the tab for some products, the way Shopper only shows the Files tab for virtual products. `permission()` hides it from users without that permission, like a settings entry. Register the class and the page's route. The route lives under `products/{product}/edit/` and keeps the `{product}` parameter: the product layout reads that parameter to show the product's header and tabs, and highlights the tab whose URL has the same segment after `edit/` as the current page. Shopper's product pages require the `products.edit` permission through the `can:` middleware: ```php title="src/LoyaltyAddon.php" use Acme\Loyalty\Livewire\ProductPoints; use Acme\Loyalty\Navigation\PointsSection; use Illuminate\Support\Facades\Route; $panel ->addonProductSections([ PointsSection::class => true, ]) ->addonRoutes(function (): void { Route::middleware('can:products.edit')->group(function (): void { Route::get('products/{product}/edit/points', ProductPoints::class) ->name('products.edit.points'); }); }); ``` The page answers at `/cpanel/products/{product}/edit/points`. Its component uses the product layout and receives the product in a `Product` property, which Livewire resolves from the route to the product model configured in Shopper. `#[Locked]` stops the browser from changing it: ```php title="src/Livewire/ProductPoints.php" namespace Acme\Loyalty\Livewire; use Illuminate\Contracts\View\View; use Livewire\Attributes\Layout; use Livewire\Attributes\Locked; use Livewire\Component; use Shopper\Core\Models\Contracts\Product; use Shopper\Traits\HandlesAuthorizationExceptions; #[Layout('shopper::components.layouts.product')] class ProductPoints extends Component { use HandlesAuthorizationExceptions; #[Locked] public Product $product; public function render(): View { return view('shopper-loyalty::livewire.pages.product-points') ->title($this->product->name); } } ``` Livewire applies the route's `can:` middleware again to each action of the page, so the actions are covered too. A check in `mount()` only runs when the page opens, so components that check there check again in each action that changes data. ### Permissions [#permissions] In 3.x, an add-on creates its permissions in the database. The skeleton's install command does it with `Permission::generate()`, which creates the five permissions of a resource (`browse`, `read`, `create`, `edit` and `delete`), described in [Generating Permissions](/3.x/acl#generating-permissions). The second argument is the group the role page lists them under, such as `customers`: ```php title="src/Console/InstallCommand.php" use Shopper\Models\Permission; use Shopper\Models\Role; Permission::generate('loyalty', 'customers'); Role::findByName(config('shopper.admin.roles.admin'))->givePermissionTo([ 'loyalty.browse', 'loyalty.read', 'loyalty.create', 'loyalty.edit', 'loyalty.delete', ]); ``` Shopper does not bypass permission checks for administrators, so give the new permissions to the administrator role, or administrators cannot open your pages either. Other roles get them from the role page of the admin panel. Without a group, `generate()` uses the resource name, and the role page lists the permissions under `loyalty`. `Permission::generate()` looks for each permission by its name, its group and its display name and description, translated in the current locale, and creates it when it finds no match. Called again under another application locale, or after an administrator generated the same permissions from a role page in another language, it finds no match and fails on the unique permission name. Run your install command under the same locale each time. Check the permissions wherever a user reaches your feature, as described in [Checking Permissions](/3.x/acl#checking-permissions): | Where | Check | |-------|-------| | A page component | `$this->authorize('loyalty.browse')` in `mount()`, and before each action that changes data | | A group of routes | `Route::middleware('can:loyalty.edit')` | | A sidebar entry | `$item->setAuthorized($this->user->can('loyalty.browse'))` | | A settings entry or a product tab | A `permission()` method that returns the permission name | | A Filament action | `Action::make('adjust')->authorize('loyalty.edit')` | | A Blade view | `@can('loyalty.edit')` | ### Render Hooks [#render-hooks] `renderHook()` adds HTML at a named place of the admin panel. The closure takes no arguments and returns a string or a view. Several hooks on the same place render in the order they were registered: ```php title="src/LoyaltyAddon.php" use Illuminate\Contracts\View\View; use Shopper\View\LayoutRenderHook; $panel->renderHook( LayoutRenderHook::HEADER_END, fn (): View => view('shopper-loyalty::components.points-badge'), ); ``` `Shopper\View\LayoutRenderHook` names the places of the layout: | Constant | Renders | |----------|---------| | `HEAD_START`, `HEAD_END` | At the start and end of ``, on every page, sign-in pages included | | `BODY_START`, `BODY_END` | At the start and end of ``, on every page, sign-in pages included | | `BEFORE_HEADER`, `AFTER_HEADER` | Above and below the top bar | | `HEADER_START`, `HEADER_END` | In the top bar, before its buttons | | `SIDEBAR_START`, `SIDEBAR_END` | At the top and bottom of the sidebar | | `CONTENT_START`, `CONTENT_END` | Above and below the content of each page | | `CONTENT_ASIDE` | Next to the content, for a side panel | | `DASHBOARD_START`, `DASHBOARD_END` | At the top and bottom of the dashboard, as described in [Adding Content with Render Hooks](/3.x/dashboard#adding-content-with-render-hooks) | | `ACCOUNT_START`, `ACCOUNT_END` | At the top and bottom of the account page | Pages have hooks of their own, in `CatalogRenderHook`, `CollectionRenderHook`, `CustomerRenderHook`, `OrderRenderHook`, `ProductRenderHook` and `SalesRenderHook` of the same namespace: before and after the table of most list pages, around some create and edit forms, and in the header, the tabs, the content and the sidebar of the customer, product and order pages. `CustomerRenderHook::SHOW_SIDEBAR_AFTER` renders below the sidebar of a customer's page, for example. The closure receives no context: a hook on a customer's page does not know which customer it renders for. The `HEAD` and `BODY` hooks also render on the sign-in pages, so check `shopper()->auth()->check()` before rendering content meant for signed-in users. Hooks inside a Livewire page, such as the dashboard hooks, run again each time the page re-renders: keep their queries short. ### Styles and Scripts [#styles-and-scripts] `addonStyles()` adds stylesheets to the `` of every admin page, after Shopper's and the theme's, and `addonScripts()` adds scripts at the end of the ``, after Shopper's and Filament's. A value that starts with `http://` or `https://` is used as is. Any other value goes through `asset()`, so it is a path under the application's `public` directory: ```php title="src/LoyaltyAddon.php" $panel ->addonStyles(['vendor/shopper-loyalty/loyalty.css']) ->addonScripts(['vendor/shopper-loyalty/loyalty.js']); ``` A package cannot write to the application's `public` directory by itself. Put your compiled files in `resources/dist` and call `hasAssets()` on the package in your service provider: the store then copies them to `public/vendor/shopper-loyalty` with Laravel's publish command, and again after each update of your add-on: ```bash php artisan vendor:publish --tag=shopper-loyalty-assets --force ``` The files load on every admin page, sign-in pages included, so scope your CSS to your own markup. To load Filament-style assets instead, register them with `FilamentAsset::register()` in your add-on's `boot()` method: the admin panel outputs Filament's registered styles and scripts on every page, and the store copies them to `public` with `php artisan filament:assets`. ### Translations and Config [#translations-and-config] Translations, views, configuration and migrations come from the add-on's service provider, so they stay available when the store disables the add-on. The skeleton's provider registers them as follows: | File | Registered by | Used as | Store copy | |------|---------------|---------|------------| | `resources/lang/en/messages.php` | `hasTranslations()` | `__('shopper-loyalty::messages.menu')` | `vendor:publish --tag=shopper-loyalty-translations` | | `resources/views/livewire/pages/loyalty-index.blade.php` | `hasViews()` | `view('shopper-loyalty::livewire.pages.loyalty-index')` | `vendor:publish --tag=shopper-loyalty-views` | | `config/loyalty.php` | `$configFiles` and `registerConfigFiles()` | `config('shopper.loyalty.points_per_order')` | `vendor:publish --provider="Acme\Loyalty\LoyaltyServiceProvider" --tag=shopper-config` | | `database/migrations/*` | `registerDatabase()` | `php artisan migrate` | None, they run from the package | Add a language with a folder next to `en`, such as `resources/lang/fr/messages.php`. Each key of `config/loyalty.php` is read under `shopper.loyalty`, and the store's copy lands in `config/shopper/loyalty.php`, next to Shopper's own configuration files: ```php title="config/loyalty.php" return [ 'points_per_order' => 10, ]; ``` The configuration is merged with Laravel's `mergeConfigFrom()`, which only fills top-level keys: when the store publishes the file, a key you add to a nested array in a later release does not reach it. Prefer top-level keys, or read nested ones with a default value. ## Full Example: A Loyalty Points Add-on [#full-example-a-loyalty-points-addon] This add-on class brings the pieces of this page together: a loyalty page with its sidebar entry, a settings page, a tab on each product, and a block on the dashboard. It keeps the skeleton's `usingLivewireComponents()` method, so a store can replace each of its pages: ```php title="src/LoyaltyAddon.php" namespace Acme\Loyalty; use Acme\Loyalty\Livewire\LoyaltyIndex; use Acme\Loyalty\Livewire\LoyaltySettings; use Acme\Loyalty\Livewire\ProductPoints; use Acme\Loyalty\Navigation\LoyaltySetting; use Acme\Loyalty\Navigation\PointsSection; use Acme\Loyalty\Sidebar\LoyaltySidebar; use Illuminate\Support\Facades\Route; use Shopper\Addon\BaseAddon; use Shopper\ShopperPanel; use Shopper\View\LayoutRenderHook; final class LoyaltyAddon extends BaseAddon { /** @var array */ private array $componentOverrides = []; public function getId(): string { return 'loyalty'; } /** * @param array $components */ public function usingLivewireComponents(array $components): static { $this->componentOverrides = array_merge($this->componentOverrides, $components); return $this; } public function register(ShopperPanel $panel): void { $components = $this->livewireComponents(); $panel ->addonLivewireComponents($components) ->addonSidebar(LoyaltySidebar::class) ->addonSettingItems([ LoyaltySetting::class => true, ]) ->addonProductSections([ PointsSection::class => true, ]) ->addonRoutes(function () use ($components): void { Route::prefix('loyalty') ->as('loyalty.') ->group(function () use ($components): void { Route::get('/', $components['loyalty.index'])->name('index'); }); Route::prefix('setting') ->as('settings.') ->group(function () use ($components): void { Route::get('/loyalty', $components['loyalty.settings'])->name('loyalty'); }); Route::middleware('can:products.edit')->group(function () use ($components): void { Route::get('products/{product}/edit/points', $components['loyalty.product-points']) ->name('products.edit.points'); }); }) ->renderHook( LayoutRenderHook::DASHBOARD_START, fn (): string => shopper()->auth()->user()?->can('loyalty.browse') ? view('shopper-loyalty::dashboard.top-members')->render() : '', ); } /** * @return array */ private function livewireComponents(): array { $components = [ 'loyalty.index' => LoyaltyIndex::class, 'loyalty.settings' => LoyaltySettings::class, 'loyalty.product-points' => ProductPoints::class, ]; return array_merge($components, array_intersect_key($this->componentOverrides, $components)); } } ``` Once the store registers the add-on, the admin panel gains these pages: | URL | Route name | Component | Required permission | |-----|------------|-----------|---------------------| | `/cpanel/loyalty` | `shopper.loyalty.index` | `shopper-loyalty.index` | `loyalty.browse` | | `/cpanel/setting/loyalty` | `shopper.settings.loyalty` | `shopper-loyalty.settings` | `system.settings` | | `/cpanel/products/{product}/edit/points` | `shopper.products.edit.points` | `shopper-loyalty.product-points` | `products.edit` | The other classes are on this page: `LoyaltySidebar` in [Sidebar Navigation](#sidebar-navigation), `LoyaltySetting` and `LoyaltySettings` in [Settings Items](#settings-items), `PointsSection` and `ProductPoints` in [Product Sections](#product-sections). The install command creates the `loyalty.*` permissions as shown in [Permissions](#permissions), and the dashboard block only shows to users who hold `loyalty.browse`. To show the data of the add-on on a storefront, [Extending the Store API](/3.x/addons/store-api) adds it to the products of the Store API or gives it its own routes. Before you publish the add-on, [Publishing an Add-on](/3.x/addons/publishing) covers versions, releases and the listing on the Shopper website. # Creating an Add-on (/3.x/addons/creating) A Shopper add-on is a Laravel package. The [add-on skeleton](https://github.com/shopperlabs/addon-skeleton) gives you a working one to start from: an add-on class, a service provider, an admin page with its sidebar entry, a permission set, an install command, tests and GitHub workflows. This page builds `acme/loyalty`, a loyalty points add-on, from that skeleton. [Extending the Admin Panel](/3.x/addons/admin-panel) then covers what the add-on can register, and [Publishing an Add-on](/3.x/addons/publishing) how to release it. ## Creating the Repository [#creating-the-repository] The skeleton is a GitHub repository with placeholders in place of your names. You clone it into a new repository of your own, then run a script that fills the placeholders in. On GitHub, create an empty repository named after your package, `loyalty` in this example, without a README or a license. Clone the skeleton into a folder with the same name, start a new Git history and point `origin` to your repository. The configuration script reads the folder name and the `origin` remote to suggest the package name and your GitHub username. ```bash git clone https://github.com/shopperlabs/addon-skeleton.git loyalty cd loyalty rm -rf .git git init -b main git remote add origin git@github.com:acme/loyalty.git ``` Clone it rather than downloading the ZIP archive from GitHub: the archive leaves out `configure.php`, the tests and the workflows. The script asks for the author, the vendor and the package name, then renames the files and namespaces of the skeleton after the add-on: ```bash php ./configure.php ``` The script needs PHP 8.4 or later. Once it is done, commit the files and push them to `origin`. ## Configuring the Skeleton [#configuring-the-skeleton] `configure.php` asks eight questions. Each one suggests a default between parentheses: press Enter to keep it. | Prompt | Default | Used for | |--------|---------|----------| | Author name | `git config user.name` | `composer.json` authors, `LICENSE.md`, README credits | | Author email | `git config user.email` | `composer.json` authors, `LICENSE.md` | | Author username | The owner of the `origin` remote | The GitHub link in the README credits | | Vendor name | The author username | The Composer vendor (`acme` in `acme/loyalty`) and the GitHub URLs in `composer.json` and the README badges | | Vendor namespace | The vendor name, capitalized | The root namespace, `Acme` in `Acme\Loyalty` | | Package name | The folder name | The Composer package name, the add-on ID, the route prefix, the install command, the view and translation namespace, the table, the permissions and the configuration file | | Class name | The package name in StudlyCase | The second namespace segment (`Loyalty` in `Acme\Loyalty`), the class and file names (`LoyaltyAddon`, `LoyaltyServiceProvider`, `LoyaltyIndex`, `LoyaltySidebar`), and the menu label and page title in the translations | | Package description | `The {package name} addon for Shopper` | The `composer.json` description and the README title | The script prints a summary and asks to modify the files. It then replaces the placeholders in every file of the project except `vendor` and itself, and renames the files that carry them: `src/SkeletonAddon.php` becomes `src/LoyaltyAddon.php`, `config/skeleton_snake.php` becomes `config/loyalty.php`, and so on. It removes the skeleton instructions from the README, offers to run `composer install`, and deletes itself. The package name gives two forms. Its slug, `loyalty` (or `loyalty-points` for "Loyalty Points"), is used for the Composer package name, the add-on ID, the route prefix, the `shopper:loyalty:install` command and the `shopper-loyalty` view and translation namespace. Its snake form, `loyalty` (or `loyalty_points`), is used for the configuration file, the table and the `loyalty.*` permissions. Check both in the summary before you confirm: the script runs once, and it deletes itself unless you answer no to the last question. ## Package Structure [#package-structure] After configuration, the package contains: ```text loyalty/ .github/ dependabot.yml workflows/ quality.yml tests.yml update-changelog.yml config/ loyalty.php database/ factories/ ModelFactory.php migrations/ 2026_07_15_000001_create_loyalty_table.php resources/ lang/ en/messages.php fr/messages.php views/ livewire/pages/loyalty-index.blade.php src/ Console/ InstallCommand.php Livewire/ LoyaltyIndex.php Models/ Sidebar/ LoyaltySidebar.php LoyaltyAddon.php LoyaltyServiceProvider.php tests/ Feature/ InstallCommandTest.php Pest.php TestCase.php CHANGELOG.md composer.json LICENSE.md README.md phpstan.neon phpunit.xml pint.json ``` `LoyaltyAddon` is what the store registers on the admin panel, and `LoyaltyServiceProvider` is what Laravel loads. The migration creates the `sh_loyalty` table, with the table prefix set in `config('shopper.core.table_prefix')`. `ModelFactory.php` is a commented-out factory to adapt once you add a model in `src/Models`. ## The composer.json File [#the-composerjson-file] The skeleton's `composer.json` requires PHP 8.3 or later, `shopper/framework` and `spatie/laravel-package-tools`: ```json title="composer.json" { "name": "acme/loyalty", "require": { "php": "^8.3", "shopper/framework": "^3.0.0-rc.4", "spatie/laravel-package-tools": "^1.15" }, "extra": { "laravel": { "providers": [ "Acme\\Loyalty\\LoyaltyServiceProvider" ] } } } ``` The `shopper/framework` constraint decides which Shopper versions can install your add-on. [Publishing an Add-on](/3.x/addons/publishing#versioning) explains how to set it for a release. The `extra.laravel.providers` entry lets Laravel discover the service provider, so the store never registers it by hand. The development dependencies include Testbench, Pest with its Laravel and Livewire plugins, Larastan and Pint, and four scripts run them: | Script | Runs | |--------|------| | `composer test` | The Pest suite, in parallel | | `composer test:types` | PHPStan with Larastan, at level 5 on `src` | | `composer test:lint` | Pint in check mode, without changing files | | `composer lint` | Pint, which fixes the code style | ## The Service Provider [#the-service-provider] The service provider loads the package into Laravel. It extends `PackageServiceProvider` from `spatie/laravel-package-tools`, and uses a Shopper trait for the configuration and the migrations: ```php title="src/LoyaltyServiceProvider.php" namespace Acme\Loyalty; use Acme\Loyalty\Console\InstallCommand; use Shopper\Core\Traits\HasRegisterConfigAndMigrationFiles; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; final class LoyaltyServiceProvider extends PackageServiceProvider { use HasRegisterConfigAndMigrationFiles; protected string $root = __DIR__.'/..'; /** @var list */ protected array $configFiles = [ 'loyalty', ]; public function configurePackage(Package $package): void { $package ->name('shopper-loyalty') ->hasTranslations() ->hasViews() ->hasCommand(InstallCommand::class); } public function packageRegistered(): void { $this->registerConfigFiles(); $this->registerDatabase(); } } ``` The provider registers the translations and views under the `shopper-loyalty` namespace, the install command, the configuration file under `shopper.loyalty`, and the migrations of `database/migrations`. It runs whenever the package is installed, even when the store has not registered or has [disabled](/3.x/addons#disabling-an-addon) the add-on. [Translations and Config](/3.x/addons/admin-panel#translations-and-config) covers each of them. ## The Add-on Class [#the-add-on-class] The add-on class is what the store registers with `Shopper::addons()`. It implements `Shopper\Contracts\ShopperAddon`, usually by extending `Shopper\Addon\BaseAddon`: | Method | Purpose | In `BaseAddon` | |--------|---------|----------------| | `getId(): string` | A unique ID, also the key that disables the add-on in `config/shopper/addons.php` | Not implemented | | `getName(): string` | A readable name | The ID in title case, hyphens replaced by spaces | | `register(ShopperPanel $panel): void` | Registers the add-on's routes, pages, navigation and assets on the panel | Not implemented | | `boot(ShopperPanel $panel): void` | Runs once Shopper boots, after every add-on is registered | Does nothing | | `isEnabled(): bool` | `false` skips the add-on entirely | `false` when `config('shopper.addons.{id}')` is `false` | The skeleton's add-on registers a Livewire page, a sidebar entry and a route, and lets the store [replace its Livewire components](/3.x/addons#customizing-an-addons-screens): ```php title="src/LoyaltyAddon.php" namespace Acme\Loyalty; use Acme\Loyalty\Livewire\LoyaltyIndex; use Acme\Loyalty\Sidebar\LoyaltySidebar; use Illuminate\Support\Facades\Route; use Shopper\Addon\BaseAddon; use Shopper\ShopperPanel; final class LoyaltyAddon extends BaseAddon { /** @var array */ private array $componentOverrides = []; public function getId(): string { return 'loyalty'; } /** * @param array $components */ public function usingLivewireComponents(array $components): static { $this->componentOverrides = array_merge($this->componentOverrides, $components); return $this; } public function register(ShopperPanel $panel): void { $components = $this->livewireComponents(); $panel ->addonLivewireComponents($components) ->addonSidebar(LoyaltySidebar::class) ->addonRoutes(function () use ($components): void { Route::prefix('loyalty') ->as('loyalty.') ->group(function () use ($components): void { Route::get('/', $components['loyalty.index'])->name('index'); }); }); } /** * @return array */ private function livewireComponents(): array { $components = [ 'loyalty.index' => LoyaltyIndex::class, ]; return array_merge($components, array_intersect_key($this->componentOverrides, $components)); } } ``` `register()` runs as soon as the store calls `Shopper::addons()`, inside the `register()` method of its service provider. Other service providers have not booted yet at that point, so keep `register()` to the `addon*` calls of the panel. `boot()` runs when Shopper's own service provider boots, after every add-on is registered: use it for work that needs booted services, such as registering Filament assets. Shopper has already loaded its routes by then, so `addonRoutes()` called from `boot()` is ignored. The other `addon*` methods still apply. ## The Install Command [#the-install-command] The skeleton ships `shopper:loyalty:install`, which a store runs once after `composer require`: ```bash php artisan shopper:loyalty:install ``` The command runs three tasks in order: 1. It runs `php artisan migrate --force`, which applies every pending migration of the application, yours included. 2. It creates the `loyalty.browse`, `loyalty.read`, `loyalty.create`, `loyalty.edit` and `loyalty.delete` permissions with `Permission::generate('loyalty')`, then gives them to the administrator role named in `config('shopper.admin.roles.admin')`. 3. It adds `use Acme\Loyalty\LoyaltyAddon;` and `new LoyaltyAddon` to `app/Providers/AppServiceProvider.php`. When the file already calls `Shopper::addons([`, the add-on joins that call. Otherwise a new call goes at the top of the `register()` method. When neither works, the command prints the line for the developer to add. The command can run again: the registration is skipped when `AppServiceProvider` already contains `LoyaltyAddon`, and the role keeps the permissions it has. `Permission::generate()` looks each permission up by its name, its group and its display name and description, translated in the current locale, and only creates the ones without a match. Run the command under the same application locale each time: under another one the lookup finds nothing, and the insert fails on the unique permission name. The skeleton's `InstallCommandTest` checks that a second run leaves `AppServiceProvider` unchanged. Extend the command as your add-on grows, for example to seed default data, and keep each task safe to repeat. ## Developing Against a Local Application [#developing-against-a-local-application] Develop the add-on inside a real Shopper application with a Composer path repository. Composer then links the package folder into the application's `vendor` directory, and every change you save shows up in the admin panel. From the application, with the add-on cloned next to it in `../loyalty`: ```bash composer config repositories.loyalty path ../loyalty composer require acme/loyalty:@dev php artisan shopper:loyalty:install ``` The `@dev` flag lets Composer install the untagged package into an application that only accepts stable versions. The application must run a Shopper version that matches your `shopper/framework` constraint. Remove the repository with `composer config --unset repositories.loyalty` before you require the published package. ## Testing [#testing] The skeleton tests with Pest on top of Orchestra Testbench, which boots a Laravel application for the package. `tests/Pest.php` applies the `TestCase` class to every test in `tests`, and `tests/TestCase.php` loads the providers the install command needs: ```php title="tests/TestCase.php" namespace Acme\Loyalty\Tests; use Acme\Loyalty\LoyaltyServiceProvider; use Illuminate\Foundation\Testing\RefreshDatabase; use Orchestra\Testbench\TestCase as BaseTestCase; use Shopper\Core\CoreServiceProvider; use Shopper\Core\Database\Seeders\CurrenciesTableSeeder; use Spatie\Permission\PermissionServiceProvider; abstract class TestCase extends BaseTestCase { use RefreshDatabase; protected bool $seed = true; protected string $seeder = CurrenciesTableSeeder::class; protected function getPackageProviders($app): array { return [ PermissionServiceProvider::class, CoreServiceProvider::class, LoyaltyServiceProvider::class, ]; } protected function defineEnvironment($app): void { $app['config']->set('database.default', 'testing'); $app->afterResolving('migrator', function ($migrator): void { $migrator->path(\Orchestra\Testbench\default_migration_path()); }); } } ``` Run the suite with `composer test`, and the type and style checks with `composer test:types` and `composer test:lint`. ### Testing Admin Pages [#testing-admin-pages] A test that renders an admin page needs the admin panel itself: its service providers, the Livewire and Filament providers it depends on, a user model that implements `Shopper\Models\Contracts\ShopperUser`, and your add-on registered on the panel. Register the add-on in a `booting` callback, so it is in place before Shopper's service provider boots: ```php title="tests/TestCase.php" namespace Acme\Loyalty\Tests; use Acme\Loyalty\LoyaltyAddon; use Acme\Loyalty\LoyaltyServiceProvider; use Acme\Loyalty\Tests\Stubs\User; use BladeUI\Heroicons\BladeHeroiconsServiceProvider; use BladeUI\Icons\BladeIconsServiceProvider; use Filament\Actions\ActionsServiceProvider; use Filament\FilamentServiceProvider; use Filament\Forms\FormsServiceProvider; use Filament\Infolists\InfolistsServiceProvider; use Filament\Notifications\NotificationsServiceProvider; use Filament\Schemas\SchemasServiceProvider; use Filament\Support\SupportServiceProvider; use Filament\Tables\TablesServiceProvider; use Filament\Widgets\WidgetsServiceProvider; use Illuminate\Contracts\Foundation\Application; use Illuminate\Foundation\Testing\RefreshDatabase; use Laravelcm\LivewireSlideOvers\LivewireSlideOverServiceProvider; use Livewire\LivewireServiceProvider; use Mckenziearts\BladeUntitledUIIcons\BladeUntitledUIIconsServiceProvider; use Orchestra\Testbench\TestCase as BaseTestCase; use Shopper\Cart\CartServiceProvider; use Shopper\Core\CoreServiceProvider; use Shopper\Core\Database\Seeders\CurrenciesTableSeeder; use Shopper\Payment\PaymentServiceProvider; use Shopper\ShopperServiceProvider; use Shopper\Sidebar\SidebarServiceProvider; use Spatie\MediaLibrary\MediaLibraryServiceProvider; use Spatie\Permission\PermissionServiceProvider; use TailwindMerge\Laravel\TailwindMergeServiceProvider; use function Orchestra\Testbench\default_migration_path; abstract class TestCase extends BaseTestCase { use RefreshDatabase; protected bool $seed = true; protected string $seeder = CurrenciesTableSeeder::class; protected function getPackageProviders($app): array { return [ BladeIconsServiceProvider::class, BladeHeroiconsServiceProvider::class, BladeUntitledUIIconsServiceProvider::class, LivewireServiceProvider::class, LivewireSlideOverServiceProvider::class, SupportServiceProvider::class, ActionsServiceProvider::class, FormsServiceProvider::class, InfolistsServiceProvider::class, NotificationsServiceProvider::class, SchemasServiceProvider::class, TablesServiceProvider::class, WidgetsServiceProvider::class, FilamentServiceProvider::class, PermissionServiceProvider::class, TailwindMergeServiceProvider::class, MediaLibraryServiceProvider::class, CoreServiceProvider::class, ShopperServiceProvider::class, SidebarServiceProvider::class, CartServiceProvider::class, PaymentServiceProvider::class, LoyaltyServiceProvider::class, ]; } protected function defineEnvironment($app): void { $app['config']->set('auth.providers.users.model', User::class); $app['config']->set('database.default', 'testing'); $app->afterResolving('migrator', function ($migrator): void { $migrator->path(default_migration_path()); }); $app->booting(function (Application $app): void { $app->make('shopper')->addons([new LoyaltyAddon]); }); } } ``` The user model only needs Shopper's contract and trait: ```php title="tests/Stubs/User.php" namespace Acme\Loyalty\Tests\Stubs; use Illuminate\Foundation\Auth\User as Authenticatable; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; class User extends Authenticatable implements ShopperUser { use InteractsWithShopper; protected $guarded = []; } ``` A test then signs a user in and renders the page with Livewire. `Gate::before()` grants every permission, so the test does not depend on the permission set. Its callback takes no user, which Laravel only calls for a signed-in user, so `actingAs()` is required: ```php title="tests/Feature/LoyaltyIndexTest.php" use Acme\Loyalty\Livewire\LoyaltyIndex; use Acme\Loyalty\Tests\Stubs\User; use Illuminate\Support\Facades\Gate; use Livewire\Livewire; beforeEach(function (): void { Gate::before(fn (): bool => true); $this->actingAs(User::query()->create([ 'first_name' => 'Jane', 'last_name' => 'Doe', 'email' => 'jane@example.com', 'gender' => 'female', ])); }); it('renders the loyalty page', function (): void { Livewire::test(LoyaltyIndex::class)->assertOk(); }); ``` ### Continuous Integration [#continuous-integration] The skeleton ships three GitHub Actions workflows in `.github/workflows`. They do not run on the skeleton repository itself, only on the repositories created from it. | Workflow | Runs on | Does | |----------|---------|------| | `tests.yml` | Every push and pull request | `composer test` on PHP 8.3, 8.4 and 8.5, against Laravel 12 and 13 | | `quality.yml` | Every push and pull request | `composer test:types` and `composer test:lint` on PHP 8.4 | | `update-changelog.yml` | Each published release | Adds the release notes to `CHANGELOG.md`, as described in [Publishing an Add-on](/3.x/addons/publishing#changelog) | ## From the Skeleton to an Admin Page [#from-the-skeleton-to-an-admin-page] With the steps above, the add-on already has a page in the admin panel. This walk-through takes it from the configured skeleton to that page, then makes the page your own. From your Shopper application, add the path repository, require the package and run its install command: ```bash composer config repositories.loyalty path ../loyalty composer require acme/loyalty:@dev php artisan shopper:loyalty:install ``` The command creates the `sh_loyalty` table and the `loyalty.*` permissions, gives them to the administrator role and registers `LoyaltyAddon` in `AppServiceProvider`. Sign in to the admin panel as an administrator. The sidebar shows a **Loyalty** group, between the core groups and **Settings**, and its **Loyalty** entry opens `/cpanel/loyalty`, the route named `shopper.loyalty.index`. The page renders `resources/views/livewire/pages/loyalty-index.blade.php`, with the title and the description of `resources/lang/en/messages.php`. A user without the `loyalty.browse` permission sees neither the entry nor the page. The skeleton's sidebar checks the permission with `hasPermissionTo()`, which throws an exception when the permission does not exist yet. A store that deploys the add-on registration before running the install command would get an error on every admin page. Check it with `can()` instead, which returns `false`: ```php title="src/Sidebar/LoyaltySidebar.php" namespace Acme\Loyalty\Sidebar; use Shopper\Sidebar\AbstractAdminSidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; final class LoyaltySidebar extends AbstractAdminSidebar { public function extendWith(Menu $menu): Menu { $menu->group(__('shopper-loyalty::messages.menu'), function (Group $group): void { $group->weight(6); $group->setAuthorized($this->user->can('loyalty.browse')); $group->item(__('shopper-loyalty::messages.menu'), function (Item $item): void { $item->weight(1); $item->setAuthorized($this->user->can('loyalty.browse')); $item->route('shopper.loyalty.index'); $item->setIcon('phosphor-gift'); $item->useSpa(); }); }); return $menu; } } ``` Add your columns to the migration, roll it back and run it again in your application, then build the page in `LoyaltyIndex` and its view. Edit `resources/lang/en/messages.php` and `resources/lang/fr/messages.php` for the menu label, the page title and the description. The next page, [Extending the Admin Panel](/3.x/addons/admin-panel), covers the settings pages, product sections, render hooks and assets an add-on can add. # Add-ons (/3.x/addons) An add-on is a Composer package that extends the Shopper admin panel. Its entry point is a class that implements `Shopper\Contracts\ShopperAddon`, which you register on the admin panel from your application. Once registered, the add-on adds its own pages, sidebar entries, settings pages, product sections, styles and scripts, and you can turn it off with one line of configuration. This page is for store developers who install add-ons. To build one, start with [Creating an Add-on](/3.x/addons/creating), then [Extending the Admin Panel](/3.x/addons/admin-panel) and [Publishing an Add-on](/3.x/addons/publishing). ## Finding Add-ons [#finding-add-ons] The Shopper website lists the add-ons you can install: the official ones, published under the `shopper/*` vendor on Packagist, and the ones the community publishes. A free add-on shows its README as the overview, its changelog as release notes, and the `composer require` line for the Shopper major you select. A paid add-on shows its highlights and a link to buy a license. ## Installing an Add-on [#installing-an-add-on] An add-on installs with Composer, like any Laravel package. Laravel discovers its service provider, so you do not register the provider yourself. Most add-ons that add admin pages also ship an install command that prepares the database and registers the add-on for you. Its name and what it does are in the add-on's README. ### Free Add-ons [#free-add-ons] Require the package, then run its install command. The examples on this page use `acme/loyalty`, an add-on built on the [add-on skeleton](/3.x/addons/creating): ```bash composer require acme/loyalty php artisan shopper:loyalty:install ``` The install command of an add-on built on the skeleton does three things: - It runs `php artisan migrate --force`, which applies every pending migration of the application, the add-on's included. - It creates the add-on's permissions (`loyalty.browse`, `loyalty.read`, `loyalty.create`, `loyalty.edit` and `loyalty.delete`) and gives them to the administrator role named in `config('shopper.admin.roles.admin')`. Other roles get them from the role page of the admin panel, as described in [Roles and Permissions](/3.x/acl). - It adds the add-on to `Shopper::addons()` in the `register()` method of `app/Providers/AppServiceProvider.php`, as shown in [Registering an Add-on](#registering-an-addon). When it cannot edit the file, it prints the line to add yourself. Running the command again skips the registration when `AppServiceProvider` already names the add-on class, and only creates the permissions it does not find. It looks them up by their translated labels, so run it under the same application locale each time: under another locale, it tries to create them again and fails. Commit the change to `AppServiceProvider`, then run the command on each environment where you would run `php artisan migrate`, since the tables and permissions live in that environment's database. ### Paid Add-ons [#paid-add-ons] A paid add-on is not on Packagist. Its vendor serves it from a private Composer repository, and the license you buy gives the repository address and the credentials to read it. Add the repository and the credentials to your project, then require the package: ```bash composer config repositories.acme composer https://composer.example.com composer config http-basic.composer.example.com LICENSE-USERNAME LICENSE-KEY composer require acme/loyalty-pro ``` Replace the address, the username and the key with the values of your license. The second command stores the credentials in an `auth.json` file at the root of your project. Keep that file out of version control: add it to `.gitignore`, and give the credentials to servers and CI through the `COMPOSER_AUTH` environment variable instead: ```bash COMPOSER_AUTH='{"http-basic": {"composer.example.com": {"username": "LICENSE-USERNAME", "password": "LICENSE-KEY"}}}' ``` Once the package is installed, run its install command as you would for a free add-on. ## Registering an Add-on [#registering-an-addon] An add-on only runs once you register it on the admin panel. Pass an instance of its add-on class to `Shopper::addons()` in the `register()` method of a service provider of your application: ```php title="app/Providers/AppServiceProvider.php" namespace App\Providers; use Acme\Loyalty\LoyaltyAddon; use Illuminate\Support\ServiceProvider; use Shopper\Facades\Shopper; class AppServiceProvider extends ServiceProvider { public function register(): void { Shopper::addons([ new LoyaltyAddon, ]); } } ``` `Shopper::addon(new LoyaltyAddon)` registers a single add-on. Registering calls the add-on's own `register()` method right away, unless the add-on is [disabled](#disabling-an-addon). Each add-on has an ID, and registering two enabled add-ons with the same ID throws a `LogicException`. The install command of a skeleton-based add-on writes this registration for you. When `AppServiceProvider` already calls `Shopper::addons([`, it adds the new add-on to that call. Shopper reads the registered add-ons once, when its own service provider boots: it loads their routes, calls each add-on's `boot()` method, then registers their sidebar entries, Livewire components, views, settings pages and product sections. Laravel boots package service providers before your application's providers, so an add-on registered in `AppServiceProvider::boot()` comes too late: all of these are skipped, without any error. Register add-ons in `register()`. ## Disabling an Add-on [#disabling-an-addon] Set the add-on's ID to `false` in `config/shopper/addons.php`. `php artisan shopper:install` publishes this file, and the add-on's README gives its ID: ```php title="config/shopper/addons.php" return [ 'loyalty' => false, ]; ``` A disabled add-on stays in your `Shopper::addons()` call, but Shopper neither keeps it nor calls its `register()` and `boot()` methods. Everything the add-on registers on the admin panel is gone: its routes, Livewire components, sidebar entries, view namespaces, settings pages, product sections, styles, scripts and render hooks. `Shopper::hasAddon('loyalty')` returns `false`. When your configuration and routes are cached, run `php artisan optimize` again for the change to apply. Disabling does not uninstall the package. Laravel still loads its service provider, so its configuration, migrations, translations, views and Artisan commands stay registered. To remove an add-on, delete it from the `Shopper::addons()` call, then run `composer remove` with its package name. Its tables and permissions stay in the database until you drop them. ## Checking if an Add-on is Active [#checking-if-an-addon-is-active] Your code can depend on an add-on that may be missing or disabled. Check it by ID before you use it: ```php use Shopper\Facades\Shopper; if (Shopper::hasAddon('loyalty')) { $addon = Shopper::getAddon('loyalty'); $addon->getName(); } ``` `hasAddon()` returns `false` for an add-on that is disabled or was never registered, and `getAddon()` throws a `LogicException` for it. `Shopper::addonManager()->all()` returns the active add-ons as a collection keyed by ID. ## Customizing an Add-on's Screens [#customizing-an-addons-screens] Each add-on decides what you can change in it. Most publish their views, translations and configuration with Laravel's `vendor:publish` command, under the tags listed in their README. For `acme/loyalty`, built on the skeleton: ```bash php artisan vendor:publish --tag=shopper-loyalty-views php artisan vendor:publish --tag=shopper-loyalty-translations php artisan vendor:publish --provider="Acme\Loyalty\LoyaltyServiceProvider" --tag=shopper-config ``` The views land in `resources/views/vendor/shopper-loyalty`, the translations in `lang/vendor/shopper-loyalty` and the configuration in `config/shopper/loyalty.php`. Your copies win over the package files, and no longer follow the changes the add-on makes to them in later releases. Add-ons built on the skeleton also accept your own Livewire components in place of theirs. Pass them to `usingLivewireComponents()` when you register the add-on, keyed by the name the add-on gives each component: ```php title="app/Providers/AppServiceProvider.php" use Acme\Loyalty\LoyaltyAddon; use App\Livewire\LoyaltyIndex; use Shopper\Facades\Shopper; public function register(): void { Shopper::addons([ (new LoyaltyAddon)->usingLivewireComponents([ 'loyalty.index' => LoyaltyIndex::class, ]), ]); } ``` Your component replaces the add-on's everywhere, including on the route that serves the page, so `/cpanel/loyalty` now renders `App\Livewire\LoyaltyIndex`. Extend the add-on's class to keep its behavior and change only what you need. A key the add-on does not know is ignored. `usingLivewireComponents()` comes from the skeleton and is absent from the add-on contract: an add-on that is not built on it may offer another way, or none. ## Payment and Shipping Drivers [#payment-and-shipping-drivers] The Stripe, FedEx, UPS and USPS packages are drivers, not add-ons. Each one registers a driver on the payment or the shipping manager from its service provider and adds no page to the admin panel: you require it with Composer and set its credentials, with no `Shopper::addons()` call. `shopper/framework` requires none of them. Their documentation sits with the feature they extend: [Payments](/3.x/payments) for `shopper/stripe`, [Carriers](/3.x/carriers) for `shopper/fedex`, `shopper/ups` and `shopper/usps`. ## Building an Add-on [#building-an-add-on] The next four pages walk through an add-on from the first commit to its listing on the Shopper website. Start from the skeleton, configure it, develop against a local application and test it. Routes, Livewire pages, sidebar entries, settings pages, product sections, permissions and assets. Add attributes to the products of the Store API and register routes a storefront calls. Version, release and list a free or paid add-on. # Publishing an Add-on (/3.x/addons/publishing) A free add-on reaches stores through Packagist, the registry Composer installs from, and through the Shopper website, which lists the add-ons stores can install. This page releases `acme/loyalty`, the add-on built in [Creating an Add-on](/3.x/addons/creating), and covers what changes for a paid add-on. ## Versioning [#versioning] Composer reads your add-on's versions from the Git tags of its repository. Number them with [semantic versioning](https://semver.org): a patch version (`1.0.1`) fixes bugs, a minor version (`1.1.0`) adds features, and a major version (`2.0.0`) breaks something a store relies on. For an add-on, that covers a Livewire component name or a `usingLivewireComponents()` key, a route name, a configuration key, a permission name, a published view that changes its variables, and the end of support for a Shopper major. The `shopper/framework` constraint in `composer.json` decides which Shopper versions your add-on installs on. Composer refuses to install the add-on in a store whose Shopper version does not match it: ```json title="composer.json" "require": { "php": "^8.3", "shopper/framework": "^3.0", "spatie/laravel-package-tools": "^1.15" } ``` The skeleton ships `^3.0.0-rc.4`, a release candidate of Shopper 3. Replace it with `^3.0`, the constraint Shopper's own installation uses, and raise the minimum when the add-on starts to use a feature of a later minor version, such as `^3.2`. When a new Shopper major comes out, test the add-on against it before you widen the constraint to `^3.0|^4.0`. If supporting it means breaking changes, release a new major of the add-on that requires only the new Shopper major, and keep fixing the previous one on its own branch. ## Tagging a Release [#tagging-a-release] Publish each version as a GitHub release, from the **Releases** page of the repository: Create a tag named after the version, such as `v1.0.0` or `1.0.0`. Composer accepts both forms: pick one and keep it. Give the release the same name as the tag. The changelog workflow uses the release name as the version heading in `CHANGELOG.md`. List what changed for the stores that install the add-on. GitHub's **Generate release notes** button drafts them from the merged pull requests. Publish the release. Check **This is a pre-release** for a version such as `1.1.0-beta.1`. Composer reads the stability from the `-beta.1` suffix, not from that checkbox, and only installs it in a store that accepts unstable versions. Packagist picks up the new tag within minutes when it is [connected to GitHub](#publishing-on-packagist). ## Changelog [#changelog] The skeleton's `update-changelog.yml` workflow keeps `CHANGELOG.md` in step with your releases. It runs when a release is published, except a pre-release, and when a pre-release is turned into a full release. It adds the release notes to `CHANGELOG.md` under a heading made of the release name and the date, then commits the file to the `main` branch with the message "Update CHANGELOG". The Shopper website shows this file as the add-on's release notes, so write the release notes for the people who install the add-on. The file the skeleton ships has an intro line and a placeholder entry, `## 1.0.0 - 202X-XX-XX`. Delete the placeholder entry before your first release, so the first real entry is the one the workflow writes. When your default branch has another name, change the two `main` values in the workflow, the branch it checks out and the branch it commits to. ## Publishing on Packagist [#publishing-on-packagist] Packagist makes the package installable with `composer require`. Push the configured skeleton to a public GitHub repository, sign in on [Packagist](https://packagist.org) with your GitHub account, and submit the repository URL. Packagist reads the package name from the `name` key of `composer.json`, so the name stores require is `acme/loyalty`. When your Packagist account is connected to GitHub, Packagist updates the package on each push and each new tag. Without that connection, Packagist checks the package once a week, or when you trigger an update from the package page. Packagist lists each branch as a development version (`dev-main`) and each tag as a release. The Shopper website does not show a free add-on until Packagist has a version for it, so tag a release first. ## Writing the README [#writing-the-readme] The Shopper website shows the README of a free add-on as its overview, so the README is the add-on's page as much as its documentation. The configure script removes the skeleton's own instructions and keeps a draft with the badges, an installation section, a usage section with the `usingLivewireComponents()` example, testing, changelog, credits and license. Replace the description paragraph, then document what a store developer needs to install and adapt the add-on: - What the add-on adds to the admin panel, with screenshots. - The Shopper and PHP versions it requires. - The `composer require` line and the install command, with what the command does. - The add-on ID, which [disables](/3.x/addons#disabling-an-addon) the add-on in `config/shopper/addons.php`. - The permissions it creates, so administrators know what to give to other roles. - Its configuration keys, and the `vendor:publish` tags of its views, translations and configuration. - The keys `usingLivewireComponents()` accepts, if you keep that method. - The attributes and routes it adds to the Store API, as [Documenting the API in the README](/3.x/addons/store-api#documenting-the-api-in-the-readme) lists. The usage example of the skeleton shows `Shopper::addons()` without its imports: add the `use` lines for `Shopper\Facades\Shopper` and your add-on class. The README is read outside GitHub too, so give images and links their full URL. ## Listing on the Shopper Website [#listing-on-the-shopper-website] The Shopper website lists official add-ons, published under the `shopper/*` vendor, and community add-ons. It does not read the keywords or the type of your `composer.json`: an add-on appears only once it is submitted with the website's form and approved. Sign in on the Shopper website with your GitHub account. For a free add-on, that account needs push access to the add-on's repository. Describe the add-on with the fields listed below. A moderator reviews each entry before it appears on the website. The form asks for these fields for every add-on: | Field | Value | |-------|-------| | Package | The Composer name, `vendor/name` | | GitHub repository | For a free add-on, the repository Packagist publishes the package from | | Free or paid | Whether the add-on is sold with a license | | Name, description and type | The add-on's name, a short description and its type | | Tags | 1 to 4 among Admin, Catalog, Customers, Inventory, Orders, Payments, Pricing, Retail, Search, Shipping and Taxes | | Cover | A 16:9 image of at least 1280x720 | | Screenshots | Images of the add-on in the admin panel | Once approved, a free add-on's page shows the README as its overview, `CHANGELOG.md` as its release notes, and the `composer require` line for the Shopper major the visitor selects. ## Paid Add-ons [#paid-add-ons] A paid add-on is not on Packagist. Its licenses are sold through a sales platform, and it installs from a private Composer repository: each license gives its customer the repository address and a key to read it, and the customer installs the add-on as described in [Paid Add-ons](/3.x/addons#paid-add-ons) of the overview. Version and tag it like a free add-on. How a new tag reaches the private repository depends on your sales platform. To list a paid add-on, fill the same form, choose paid, and add these fields: | Field | Value | |-------|-------| | Price and currency | The price of a license | | Sales platform | Anystack, Privato, Pukau or Other | | Product ID | The product's ID on that platform | | Checkout URL | The page where a customer buys a license | | Supported Shopper majors | 2.x, 3.x or both | A paid add-on's page on the Shopper website shows its highlights and a "Buy a license" link. A moderator approves it like a free one. # Extending the Store API (/3.x/addons/store-api) An add-on that stores data in the admin panel often has something to show on the storefront: the points a product earns, the products pinned on a product image. A storefront reads the shop through the [Store API](/3.x/store-api), and an add-on reaches it in two ways. When its data belongs to a product, it adds attributes to the product the API already returns. When its data stands on its own, it registers its own routes. Media Hotspots, the add-on that pins other products on the images of a product, takes the first way, and this page uses its code as the example. The routes continue the `acme/loyalty` add-on of [Creating an Add-on](/3.x/addons/creating) and [Extending the Admin Panel](/3.x/addons/admin-panel). ## Adding Attributes to a Product [#adding-attributes-to-a-product] A storefront that shows a product with its hotspots wants them in the product it already loads, not in one more request per image. The Store API serializes every product with one resource class, `Shopper\Api\Http\Resources\ProductResource`, and a store [replaces that class](/3.x/store-api/json-api#replacing-a-resource) with its own to add attributes. A resource takes one replacement only: the last `ApiResource::replace()` call wins. An add-on that called it would drop the replacement of the store, or the one of another add-on, so an add-on never calls it. It ships a trait instead, and the store adds the trait to its own resource class. The trait of Media Hotspots, `Shopper\MediaHotspots\Concerns\SerializesMediaHotspots`, gives the resource an `imagesWithHotspots()` method, which returns the images of the product, each with the hotspots pinned on it. This resource of the store sends them as the `images` attribute, in place of the images without hotspots: ```php title="app/Http/Resources/StoreProductResource.php" namespace App\Http\Resources; use Illuminate\Http\Request; use Shopper\Api\Http\Resources\ProductResource; use Shopper\MediaHotspots\Concerns\SerializesMediaHotspots; class StoreProductResource extends ProductResource { use SerializesMediaHotspots; public function toAttributes(Request $request): array { return [ ...parent::toAttributes($request), 'images' => $this->imagesWithHotspots(), ]; } } ``` The store registers its class in the `boot` method of a service provider, as for any replacement: ```php title="app/Providers/AppServiceProvider.php" use App\Http\Resources\StoreProductResource; use Shopper\Api\Facades\ApiResource; use Shopper\Api\Http\Resources\ProductResource; public function boot(): void { ApiResource::replace(ProductResource::class, StoreProductResource::class); } ``` Inside the trait, `$this->resource` is the product model, so the methods of the trait read the product the resource serializes. When a second add-on ships a trait, the store uses both in the same class, `use SerializesMediaHotspots, SerializesLoyaltyPoints;`, and merges the attributes of each in `toAttributes()`. PHP refuses a class whose traits declare the same method, so name the methods of your trait after what your add-on adds, as `imagesWithHotspots()` does. ## Loading the Relations [#loading-the-relations] The trait reads the hotspots through a relation of the product. On a listing of 24 products, reading that relation on each product runs 24 queries. The Store API loads the relations a resource lists in its static `eagerLoads()` method together with the products it returns: the product listing, a single product, the related products, the products a category, a collection, a brand or a tag includes, and the products of the cart lines. The store keeps the replacement of `ProductResource` for itself, so an add-on does not override that method: it registers its relations with `ApiResource::eagerLoad()`, and the 24 products then load their hotspots in one query. Call it from the `boot()` method of the add-on class. Shopper calls `boot()` only for an enabled add-on, so the relations stop loading when the store disables the add-on. This is the `boot()` method of Media Hotspots: ```php title="src/MediaHotspotsAddon.php" use Shopper\Api\Facades\ApiResource; use Shopper\Api\Http\Resources\ProductResource; use Shopper\ShopperPanel; public function boot(ShopperPanel $panel): void { if (class_exists(ApiResource::class)) { ApiResource::eagerLoad(ProductResource::class, [ 'mediaHotspots.product.media', 'mediaHotspots.product.prices.currency', 'mediaHotspots.product.channels', ]); } } ``` Each path follows the relations of the product with dots, as Laravel's `with()` does: the hotspots, the product each hotspot points to, and the images, prices and sales channels of that product, which decide what the hotspot shows. The Store API ships in its own package, `shopper/api`, so the `class_exists()` check keeps the add-on working in a store that does not install it. `eagerLoad()` registers the paths on the stock `ProductResource` class, and the Store API loads them for the replacement of the store too, whichever of `replace()` and `eagerLoad()` runs first. The calls of several add-ons add up, and a path registered twice loads once. The method takes paths only, not closures that constrain the query. A store adds its own relations by overriding `eagerLoads()` in its replacement, as [Loading Relations](/3.x/store-api/json-api#loading-relations) shows. The relation must exist on the product model. Media Hotspots declares it in the `boot` method of its service provider, with `resolveRelationUsing()` on the class that `config('shopper.models.product')` names, so the relation also exists when a store replaces the product model. The trait checks `relationLoaded('mediaHotspots')` before it reads the relation, and runs its own query when the relation is not loaded, such as for a product serialized outside the Store API. ## Registering Routes [#registering-routes] The loyalty add-on lets a storefront show how many points a product earns, and how many points the customer holds. That data belongs to no resource of the Store API, so the add-on registers its own routes with the `ShopperApi` facade, the one an application uses in [Adding Your Own Routes](/3.x/store-api#adding-your-own-routes). Each route then gets the prefix, the rate limit, the zone, the channel and the error format of the built-in routes. Register them in the `boot()` method of the add-on class, for the same reason as the relations: a disabled add-on is never booted, so its routes stop answering. The service provider of the package runs even for a disabled add-on, so routes registered there would keep answering. This `boot()` method registers a public route and a route of the authenticated group: ```php title="src/LoyaltyAddon.php" use Acme\Loyalty\Http\Controllers\CustomerPointsController; use Acme\Loyalty\Http\Controllers\ProductRewardController; use Illuminate\Support\Facades\Route; use Shopper\Http\Facades\ShopperApi; use Shopper\ShopperPanel; public function boot(ShopperPanel $panel): void { ShopperApi::store(function (): void { Route::get('/products/{slug}/loyalty-rewards', ProductRewardController::class); }); ShopperApi::authenticated(function (): void { Route::get('/customers/me/loyalty', CustomerPointsController::class); }); } ``` The routes answer at `/store/products/{slug}/loyalty-rewards` and `/store/customers/me/loyalty`, or under the prefix the store configured. Pick paths the Store API does not use already: `php artisan route:list --path=store` lists them. The admin routes of the add-on stay in `addonRoutes()`, called from `register()`: Shopper ignores `addonRoutes()` called from `boot()`. ## Looking Up a Product [#looking-up-a-product] The groups of the Store API do not include `SubstituteBindings`, so `{slug}` reaches the controller as a string, and the controller looks the product up itself. It must find only the products a visitor can see, as `GET /store/products/{slug}` does. The `publish()` scope keeps the published products, and the `applyChannelScope()` method of the `Shopper\Api\Concerns\ResolvesChannel` trait keeps the products of the sales channel of the request, when the request names one. `firstOrFail()` then answers a missing product with a `404` in the [error format](/3.x/store-api/errors) of the Store API, as for any exception under the API prefix. This controller returns the points a product earns: ```php title="src/Http/Controllers/ProductRewardController.php" namespace Acme\Loyalty\Http\Controllers; use Acme\Loyalty\Http\Resources\ProductRewardResource; use Acme\Loyalty\Models\ProductReward; use Shopper\Api\Concerns\ResolvesChannel; use Shopper\Core\Models\Contracts\Product; final class ProductRewardController { use ResolvesChannel; public function __invoke(string $slug): ProductRewardResource { $product = $this->applyChannelScope( resolve(Product::class)::query()->publish()->where('slug', $slug) )->firstOrFail(); return ProductRewardResource::make( ProductReward::query()->where('product_id', $product->getKey())->firstOrFail() ); } } ``` `resolve(Product::class)` returns the product model the store configured, so the lookup works on a replaced model too. The controller of `/customers/me/loyalty` has nothing to look up: in the authenticated group, `$request->user()` returns the customer of the token, so the controller reads the points of that customer and never takes a customer ID from the request. ## Returning JSON:API [#returning-jsonapi] The SDK reads every response as a JSON:API document, so a route returns a resource built on Laravel's `JsonApiResource`, the class the Shopper resources extend, as [Returning JSON:API From Your Routes](/3.x/sdk/custom-endpoints#returning-jsonapi-from-your-routes) explains. This resource gives each reward the `loyalty-rewards` type and sends its points: ```php title="src/Http/Resources/ProductRewardResource.php" namespace Acme\Loyalty\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\JsonApi\JsonApiResource; class ProductRewardResource extends JsonApiResource { public function toType(Request $request): string { return 'loyalty-rewards'; } public function toAttributes(Request $request): array { return [ 'points' => $this->points, ]; } } ``` Start the type with the name of the add-on, as `loyalty-rewards` does, so that it never matches a type of the Store API or of another add-on. ## Calling the Routes From a Storefront [#calling-the-routes-from-a-storefront] The SDK has no method for the routes of an add-on, so a storefront calls them with [`store.fetch()`](/3.x/sdk/custom-endpoints), which sends the customer token, the zone and channel headers and the language, as the built-in methods do. This call reads the points the product of the page earns: ```ts import { sdk } from '@/lib/shopper' type LoyaltyReward = { id: string points: number } const { data } = await sdk.store.fetch(`/products/${product.slug}/loyalty-rewards`) const reward = data as LoyaltyReward ``` The attributes an add-on adds to a product need no call of their own: they come with the products that `sdk.store.product.retrieve()` and `sdk.store.product.list()` return. The `Product` type of the SDK does not declare them, so extend it with the shape the README of the add-on gives. This type adds the hotspots of Media Hotspots to the images of a product: ```ts import type { Media, Product } from '@shopperlabs/shopper-sdk' type Hotspot = { x: number y: number product: { id: string; name: string; slug: string } } type ProductWithHotspots = Omit & { images: Array } const product = (await sdk.store.product.retrieve('classic-leather-sneaker')) as ProductWithHotspots ``` ## Documenting the API in the README [#documenting-the-api-in-the-readme] The Shopper documentation does not list the attributes and routes of each add-on: a store developer finds them in the README of the add-on, next to its installation steps. The README of Media Hotspots has a Store API section with its trait, the resource of the store and the `replace()` call. Give yours one too. Besides what [Writing the README](/3.x/addons/publishing#writing-the-readme) lists, it gives: - The trait, the methods a store calls and the attributes they return, with the resource class of the store. - The relations the add-on registers with `ApiResource::eagerLoad()`. - Each route: its method and path, its group, its parameters and the attributes of its resource. - The `store.fetch()` call and the TypeScript type of the response. Before you publish the add-on, [Publishing an Add-on](/3.x/addons/publishing) covers versions, releases and the listing on the Shopper website. # Permissions (/3.x/acl) Shopper controls access to the admin panel with [spatie/laravel-permission](https://spatie.be/docs/laravel-permission) 7. Each team member has one or more roles, and each role holds permissions named in dot notation, `resource.action`: `orders.browse` opens the order list, `products.edit` opens the product editor, `system.settings` opens the settings pages. Spatie registers its check on Laravel's gate, so `can()`, `@can`, `$this->authorize()` and the `can:` route middleware all accept these names. The [User Guide](/3.x/user-guide) shows how merchants add team members and edit roles from the admin panel. ## Roles [#roles] Shopper relies on three roles. Their names are set in `config/shopper/admin.php`: ```php title="config/shopper/admin.php" 'roles' => [ 'admin' => 'administrator', 'manager' => 'manager', 'user' => 'user', ], ``` `php artisan shopper:install` creates the three roles and the permissions when you accept to run the seeders: | Role | Display name | Access | |------|--------------|--------| | `administrator` | Administrator | Opens the admin panel and receives every seeded permission. Only an administrator can manage the administrator role, create or delete permissions, and delete team members. | | `manager` | Manager | Opens the admin panel. The seeder gives it no permission: grant the ones the team needs from the role page or in code. | | `user` | User | The customer role. The Team screen does not list it, and it cannot be given to a team member from the admin panel. | The seeder creates the three roles with `can_be_removed` set to `false`, so the admin panel never offers to delete them. Any other role, such as a "Fulfillment" role for the warehouse team, opens the admin panel only when it holds the `system.dashboard` permission. Keep these names once users hold the roles. `isAdmin()` compares the role name with `config('shopper.admin.roles.admin')`: renaming the administrator role, in the config file or from its role page, removes administrator rights from everyone who holds it. The role page shows a warning when you open the administrator role for this reason. ## Models [#models] Both models extend the Spatie models, so every Spatie method works on them. Their tables are named by Spatie's `permission.table_names` configuration, `roles` and `permissions` by default, without the Shopper table prefix. ### Role [#role] `Shopper\Models\Role` adds a display name, a description and a removal flag to Spatie's role: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | | Role name, such as `administrator`. Unique per guard. | | `guard_name` | string | no | | Filled by Spatie with the default guard | | `display_name` | string | yes | null | Name shown in the admin panel | | `description` | text | yes | null | Description shown on the role page | | `can_be_removed` | boolean | no | true | `false` hides the delete action of the role | `isAdmin()` tells whether a role is the administrator role: ```php use Shopper\Models\Role; $role = Role::findByName(config('shopper.admin.roles.admin')); $role->isAdmin(); ``` ### Permission [#permission] `Shopper\Models\Permission` adds a group, a display name, a description and the same removal flag to Spatie's permission: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `name` | string | no | | Permission name in dot notation, such as `orders.browse`. Unique per guard. | | `guard_name` | string | no | | Filled by Spatie with the default guard | | `group_name` | string | yes | null | Group the role page lists the permission under | | `display_name` | string | yes | null | Label shown next to the checkbox on the role page | | `description` | string | yes | null | Description of the permission | | `can_be_removed` | boolean | no | true | `false` blocks the deletion of the permission | ### Permission Groups [#permission-groups] The role page lists permissions by group. `Permission::groups()` returns the built-in groups, keyed by the value stored in `group_name`: ```php use Shopper\Models\Permission; Permission::groups(); ``` | Key | Label | |-----|-------| | `system` | System | | `catalog` | Catalog | | `products` | Products | | `sales` | Sales | | `customers` | Customers | | `inventory` | Inventory | The forms that create permissions on the role page offer these groups. The role page lists each permission under its group key, such as `catalog`, not the label, and a permission without a group under "Custom permission". ## Seeded Permissions [#seeded-permissions] `Shopper\Database\Seeders\AuthTableSeeder` creates the three roles, then 73 permissions, then gives every permission to the administrator role. None of these permissions can be deleted from the admin panel. ### System Permissions [#system-permissions] The `system` group holds the three permissions that cover the panel itself: | Permission | Display name | Allows | |------------|--------------|--------| | `system.dashboard` | Access Dashboard | Opening the admin panel, for a user who is neither administrator nor manager | | `system.settings` | Access Settings | Opening and changing the settings pages, including the roles and permissions of the Team screen | | `system.users` | View Users | Opening the Team screen, viewing roles and team members, and adding a team member | ### Resource Permissions [#resource-permissions] Each resource has five permissions: `browse` (the list page), `read` (a single record), `create`, `edit` and `delete`. The name of a permission is the resource followed by the action, such as `brands.create` or `products.variants.edit`: | Resource | Group | Admin section | |----------|-------|---------------| | `brands` | Catalog | Brands | | `categories` | Catalog | Categories | | `collections` | Catalog | Collections | | `products` | Products | Products | | `products.variants` | Products | Variants of a product | | `attributes` | Products | Attributes | | `suppliers` | Products | Suppliers | | `tags` | Products | Tags | | `reviews` | Products | Reviews | | `orders` | Sales | Orders, shipments and abandoned carts | | `discounts` | Sales | Discounts | | `campaigns` | Sales | Campaigns | | `customers` | Customers | Customers | | `inventories` | Inventory | Inventory locations, in the settings | ## Access by Section [#access-by-section] Every page of the admin panel checks its permission when it loads, and the actions on the page check theirs again when they run, so a hidden button is never the only protection. A user who fails the check when a page loads lands on the forbidden page. | Section | Permissions checked | |---------|---------------------| | Admin panel, every page | Administrator or manager role, or `system.dashboard` | | Dashboard widgets | `orders.browse`, `products.browse`, `customers.browse`, as listed on the [Dashboard](/3.x/dashboard#widgets) page | | Products | `products.browse` for the list, `products.create` to add a product or import a CSV file, `products.edit` for every tab of the product editor, `products.delete`, `attributes.delete` to remove an attribute from a product | | Variants | `products.edit` to open the variant page, `products.variants.create` to add variants, `products.variants.edit` to generate variants and to change a variant, its stock, its media and its prices, `products.variants.delete` | | Brands, categories, collections, attributes, suppliers, tags | `{resource}.browse` for the list, then `{resource}.create`, `{resource}.edit` and `{resource}.delete` for the matching actions | | Reviews | `reviews.browse` for the list, `reviews.edit` to approve or reject a review, `reviews.delete` | | Orders | `orders.browse` for the orders, shipments and abandoned carts lists, `orders.read` for an order or a shipment, `orders.edit` for every action on an order: status changes, notes, shipping labels, shipment events | | Customers | `customers.browse` for the list, `customers.read` for a customer, `customers.create`, `customers.delete` to anonymize a customer | | Discounts | `discounts.browse` for the list, `discounts.create` to add or duplicate a discount, `discounts.edit`, `discounts.delete` | | Campaigns | `campaigns.browse` for the list, then `campaigns.create`, `campaigns.edit` and `campaigns.delete` | | Settings, Locations | `inventories.browse`, `inventories.create`, `inventories.edit`, `inventories.delete` | | Settings, Team | `system.users` and `system.settings`, as described in [Team Management Safeguards](#team-management-safeguards) | | Every other settings page, and the store setup wizard | `system.settings` | The admin panel does not check the following seeded permissions: `brands.read`, `categories.read`, `collections.read`, `products.read`, `products.variants.browse`, `products.variants.read`, `attributes.read`, `suppliers.read`, `tags.read`, `reviews.read`, `reviews.create`, `orders.create`, `orders.delete`, `discounts.read`, `campaigns.read`, `customers.edit` and `inventories.read`. They exist in the database, and your own code can check them. ## Team Management Safeguards [#team-management-safeguards] The Team screen relies on two system permissions. `system.users` opens it, lists the roles and the team members, opens a role and adds a team member. `system.settings` creates, renames and deletes roles, and grants or revokes permissions. Holding `system.settings` does not make a user an administrator. A merchant can give it to a staff member who configures shipping and taxes without handing over the access control system, because four rules apply to every user who is not an administrator: | Rule | Effect | |------|--------| | The administrator role is out of reach | A non-administrator cannot open the administrator role, change it, or give it to a new team member. | | Grant only what you hold | Granting a permission to a role requires holding that permission. Revoking a permission has no such condition. | | Permission definitions are administrator only | Creating, generating and deleting permissions requires the administrator role. | | Deleting team members is administrator only | An administrator can delete any team member except their own account and the last administrator. Deleting a team member deletes the user. | The rules run on the server, in the Livewire actions, so a forged request fails like a click in the interface. Roles and permissions with `can_be_removed` set to `false` are protected the same way: the server refuses to delete them. The grant rule covers permissions given to a role. Adding a team member with an existing role only requires `system.users`, so a user who holds it can give a new member any role except administrator, whatever permissions that role holds. ## Generating Permissions [#generating-permissions] `Permission::generate()` creates the five permissions of a resource in one call: `browse`, `read`, `create`, `edit` and `delete`. The first argument is the resource, the second the group. Without a group, the resource name is used as the group. Running it again for a resource it already created adds nothing, as long as the group and the application locale are the same as on the first run: it looks each permission up by all its columns, translated labels included. Shopper does not bypass the gate for administrators: they hold the seeded permissions because the seeder gave them every permission at install time. A permission created later belongs to no role until you give it, so give it to the administrator role as well, or administrators fail the check like everyone else. A seeder for a subscriptions feature of your store creates its permissions in the Sales group and gives them to the administrator role: ```php title="database/seeders/SubscriptionPermissionSeeder.php" namespace Database\Seeders; use Illuminate\Database\Seeder; use Shopper\Models\Permission; use Shopper\Models\Role; final class SubscriptionPermissionSeeder extends Seeder { public function run(): void { Permission::generate('subscriptions', 'sales'); Role::findByName(config('shopper.admin.roles.admin'))->givePermissionTo([ 'subscriptions.browse', 'subscriptions.read', 'subscriptions.create', 'subscriptions.edit', 'subscriptions.delete', ]); } } ``` Run it on each environment after the Shopper seeders: ```bash php artisan db:seed --class=SubscriptionPermissionSeeder ``` Generated permissions have `can_be_removed` set to `false`, so they cannot be deleted from the admin panel. Administrators can also generate permissions from a role page with the "Generate permissions" button: the five permissions go to the role being edited only. ## Working with Roles [#working-with-roles] Roles are created and assigned with Spatie's methods, and checked with the helpers that Shopper adds to your `User` model. ### Creating Roles [#creating-roles] A role for the warehouse team that prepares and ships orders needs `system.dashboard` to open the admin panel, then the permissions of the sections it works in: ```php use Shopper\Models\Role; $role = Role::query()->create([ 'name' => 'fulfillment', 'display_name' => 'Fulfillment', 'description' => 'Prepares and ships orders.', ]); $role->givePermissionTo([ 'system.dashboard', 'orders.browse', 'orders.read', 'orders.edit', 'customers.browse', 'customers.read', ]); ``` Creating a role from the Team screen of the admin panel requires `system.settings`. ### Assigning Roles [#assigning-roles] `assignRole()` adds a role to a user, and `syncRoles()` replaces all of their roles: ```php $user->assignRole('fulfillment'); $user->syncRoles([config('shopper.admin.roles.manager')]); ``` Read the role names from `config('shopper.admin.roles')` rather than writing `administrator` or `manager`, so your code follows the configuration. ### Checking Roles [#checking-roles] The `Shopper\Traits\InteractsWithShopper` trait on your `User` model brings Spatie's `HasRoles` trait and three methods built on the roles configuration: ```php $user->isAdmin(); $user->isManager(); $user->canAccessDashboard(); $user->hasRole('fulfillment'); ``` `isAdmin()` and `isManager()` check the administrator and manager roles. `canAccessDashboard()` is the check that guards every admin page: it is true for an administrator, a manager, or a user who holds `system.dashboard`. `hasRole()` comes from Spatie and accepts any role name. The trait also adds an `administrators()` query scope, which returns the users with the administrator or manager role: ```php use App\Models\User; $team = User::query()->administrators()->get(); ``` ## Working with Permissions [#working-with-permissions] Permissions go through Laravel's gate, so you check them with the authorization tools you already use, and you add your own next to the ones Shopper seeds. ### Checking Permissions [#checking-permissions] Spatie's gate hook grants an ability when the user holds a permission of that name, through a role or directly. Otherwise it gives no answer, and Laravel goes on to your own gates and policies, so permissions and policies work side by side. ```php $user->can('orders.edit'); $user->hasPermissionTo('orders.edit'); ``` `can()` returns `false` for a name that matches no permission. `hasPermissionTo()` throws a `Spatie\Permission\Exceptions\PermissionDoesNotExist` exception instead, which surfaces a typo in a permission name. In Blade: ```blade @can('orders.export') {{ __('Export orders') }} @endcan ``` Livewire components call `authorize()` when the page loads, the way every Shopper page does: ```php title="app/Livewire/Shopper/Subscriptions.php" public function mount(): void { $this->authorize('subscriptions.browse'); } ``` Filament actions take the permission with `authorize()`, which hides the action from a user who lacks it and checks it again when the action runs: ```php use Filament\Actions\Action; Action::make('cancel') ->authorize('subscriptions.edit'); ``` The routes of your [custom route file](/3.x/configuration#custom-routes) take the `can:` middleware: ```php title="routes/shopper.php" use App\Livewire\Shopper\Subscriptions; use Illuminate\Support\Facades\Route; Route::livewire('subscriptions', Subscriptions::class) ->middleware('can:subscriptions.browse') ->name('subscriptions.index'); ``` Inside the admin panel, a failed check sends the user to the forbidden page. In a component that uses the `Shopper\Traits\HandlesAuthorizationExceptions` trait, a check that fails after the page has loaded shows an "Unauthorized" notification instead, and the user stays on the page. ### Creating Custom Permissions [#creating-custom-permissions] For a single permission, create it with `Permission::query()->create()` and give it to the roles that need it, the administrator role included: ```php use Shopper\Models\Permission; use Shopper\Models\Role; $permission = Permission::query()->create([ 'name' => 'orders.export', 'group_name' => 'sales', 'display_name' => 'Export orders', 'description' => 'Allows downloading the order list as a CSV file.', ]); Role::findByName(config('shopper.admin.roles.admin'))->givePermissionTo($permission); Role::findByName('fulfillment')->givePermissionTo($permission); ``` A permission created this way keeps the default `can_be_removed` value of `true`, so an administrator can delete it from the role page. Administrators can also create a permission from a role page with the "Create permission" button, which gives it to that role. ### Revoking Permissions [#revoking-permissions] `revokePermissionTo()` removes a permission from a role: ```php use Shopper\Models\Role; Role::findByName('fulfillment')->revokePermissionTo('orders.edit'); ``` ## Upgrading from 2.x [#upgrading-from-2x] Shopper 2.x named permissions with an action prefix, such as `browse_products` or `add_brands`. The `php artisan shopper:upgrade` command renames them in the database as one of its steps. To run that step alone, preview it first: ```bash php artisan shopper:upgrade:permissions --dry-run ``` The command maps each 2.x action prefix to a 3.x suffix (`add_` becomes `.create`, the others keep their name), renames `product_variants` to `products.variants`, renames `access_dashboard`, `access_setting` and `view_users` to `system.dashboard`, `system.settings` and `system.users`, and moves each permission to its 3.x group. A permission whose 3.x name already exists is skipped. The command records that it ran and does nothing on the next run unless you pass `--force`. The roles keep their permissions, since only the names change. The command writes to the table directly, so Spatie keeps the 2.x names in its cache: clear it once the rename is done. ```bash php artisan permission:cache-reset ``` Rename the permission checks in your own code as well: the [upgrade guide](/3.x/upgrade) lists the changes, and the `shopper-upgrade-permissions` [upgrade skill](/3.x/ai-tools#upgrade-skills) applies them. The `campaigns` resource is new in 3.x, and the rename does not create its permissions. Generate them with `Permission::generate('campaigns', 'sales')` and give them to the administrator role, as shown in [Generating Permissions](#generating-permissions), or nobody can open the Campaigns section. ## Admin User Creation [#admin-user-creation] The `shopper:user` command creates a user with the administrator role: ```bash php artisan shopper:user ``` It asks for an email address, a first name, a last name and a password of at least 6 characters, and marks the email as verified. It stops with an error when the administrator role does not exist yet: run `php artisan db:seed --class="Shopper\Database\Seeders\AuthTableSeeder"` first. To make an existing user an administrator in code, assign the role: ```php $user->assignRole(config('shopper.admin.roles.admin')); ``` ## Components [#components] The Team screen is part of the `setting` components. Publish them to replace a page or a component with your own Livewire class, as described in [Components](/3.x/configuration#components): ```bash php artisan shopper:component:publish setting ``` The entries that build the Team screen in `config/shopper/components/setting.php`: ```php title="config/shopper/components/setting.php" use Shopper\Livewire; use Shopper\Livewire\Components; use Shopper\Livewire\Pages; return [ 'pages' => [ 'team-index' => Pages\Settings\Team\Index::class, 'team-roles' => Pages\Settings\Team\RolePermission::class, ], 'components' => [ 'settings.team.administrators' => Components\Settings\Team\AdministratorsList::class, 'settings.team.permissions' => Components\Settings\Team\Permissions::class, 'slide-overs.create-team-member' => Livewire\SlideOvers\CreateTeamMember::class, ], ]; ``` A replacement page or component keeps the safeguards only if it applies them: extend the Shopper class, or use the `Shopper\Traits\AuthorizesTeamManagement` trait the built-in components use. # Using Shopper with AI Tools (/3.x/ai-tools) A coding agent knows Laravel well, but it does not know how Shopper registers an admin page, which contract to implement for a custom model, or which config key turns off a feature. Shopper gives agents that context in two ways: guidelines and skills shipped inside the Shopper packages for [Laravel Boost](https://laravel.com/docs/boost), and this documentation served as Markdown. ## Laravel Boost [#laravel-boost] Laravel Boost writes guidelines and skills into the instruction files of your agent, such as `CLAUDE.md` or `AGENTS.md`, based on the packages installed in your application. It also runs an MCP server through which the agent reads your database schema, the application logs and the browser errors. Install it as a development dependency: ```bash composer require laravel/boost --dev php artisan boost:install ``` The installer asks which Boost features to install, which third-party packages to take guidelines and skills from (select `shopper/framework`), and which agents you use. Livewire and Filament guidelines are added only when your `composer.json` requires those packages directly. If Boost was already installed before you added Shopper, run the update command. It lists the packages you require directly that ship Boost guidelines or skills and are not in your Boost configuration yet, and asks which ones to add: ```bash php artisan boost:update ``` The prompt only appears when the command runs in a terminal. Run `boost:update` again after each Shopper upgrade so that the files your agent reads follow the installed version. ### Guidelines [#guidelines] Guidelines are loaded at the start of every agent session. The Shopper guidelines cover the conventions an agent needs for most tasks in a Shopper application: - the installation and the configuration files - custom admin pages, routes and sidebar navigation - the model architecture, custom models, product types, stock, pricing, categories and orders - events, overriding the panel's Livewire components, permissions and feature flags - helper functions, Artisan commands, media, Blade components and database tables - testing an application that uses Shopper ### Skills [#skills] A skill is loaded only when the task needs it, which keeps the agent's context small. `shopper/framework` ships one skill: | Skill | What it covers | |-------|----------------| | `shopper-customization` | Customizing Shopper in your application: sidebar navigation, component overrides, event listeners, and features such as stock, pricing and media. | ## Upgrade Skills [#upgrade-skills] The `shopper/upgrade` package ships nine more skills, each for a change that needs a decision rather than a search and replace. Install the package as a development dependency when the [upgrade guide](/3.x/upgrade) asks for it, run `php artisan shopper:upgrade`, then let Boost add the skills: ```bash php artisan boost:update ``` Five skills cover the move to 3.x: | Skill | When the agent uses it | |-------|------------------------| | `shopper-upgrade-permissions` | Moving permission names from underscores (`read_orders`) to dot notation (`orders.read`). | | `shopper-upgrade-config` | Reconciling the published config files with the 3.x ones: admin notifications, campaigns, themes, cart pipelines, the promotions limit, shipping rates cache, carrier driver packages and discount components. | | `shopper-upgrade-contracts` | Moving the `ShopperUser`, `Cart` and `CartLine` contracts to their new packages, and adding the methods now required on the `PaymentDriver` and `Order` contracts. | | `shopper-upgrade-product-edit` | Moving overrides of the product edit screen from Livewire form components to pages, and registering sections in `config/shopper/components/product.php`. | | `shopper-upgrade-settings-namespace` | Moving custom settings pages from `Shopper\Settings\*` to `Shopper\Navigation\Setting\*`, and updating a published `config/shopper/settings.php`. | The other four cover changes made during the 2.x releases, for a store that upgrades from an older 2.x version: | Skill | When the agent uses it | |-------|------------------------| | `shopper-upgrade-money-storage` | Moving storefront code to amounts stored in cents (Shopper 2.7). | | `shopper-upgrade-filament-schemas` | Moving custom Filament components from `InteractsWithForms` to `InteractsWithSchemas`. | | `shopper-upgrade-slide-overs` | Moving custom slide-over components from Shopper's `SlideOverComponent` to the `laravelcm/livewire-slide-overs` package. | | `shopper-upgrade-two-factor-auth` | Replacing the `TwoFactorAuthenticatable` trait on the User model with the new two-factor interfaces. | Remove `shopper/upgrade` once the upgrade is done. ## Documentation as Markdown [#documentation-as-markdown] Every page of this documentation is also served as Markdown, which an agent reads with fewer tokens than the HTML page: | URL | What it returns | |-----|-----------------| | [`/llms.txt`](https://docs.laravelshopper.dev/llms.txt) | The list of every page with its summary, for an agent to choose what to read. | | [`/llms-full.txt`](https://docs.laravelshopper.dev/llms-full.txt) | The whole documentation in one Markdown file. | | `/3.x/installation.md` | One page as Markdown: add `.md` to the URL of any page. | A request for a page URL with the `Accept: text/markdown` header also returns the Markdown version, so an agent that fetches `https://docs.laravelshopper.dev/3.x/installation` with that header gets Markdown without a different URL. `llms.txt` and `llms-full.txt` cover every version of the documentation. Each page title carries its path, such as `/3.x/installation` or `/2.x/installation`: tell your agent to read the `/3.x` pages. The menu at the top of each page copies the page as Markdown, or opens it in ChatGPT, Claude, Cursor or Scira AI with the page as context, to ask a question about it. # Architecture and Packages (/3.x/architecture) Shopper 3 is split into 13 Composer packages and 2 npm packages. They are developed together in the [shopperlabs/shopper](https://github.com/shopperlabs/shopper) repository, as the [Contributing](/3.x/contributing) page explains. Each release tags the Composer packages and `@shopperlabs/shopper-types` at the same version; `@shopperlabs/shopper-sdk` is published with a version number of its own. Your application requires `shopper/framework`, then adds the Store API, a payment driver or a carrier driver when the store needs one. ## Packages [#packages] Each package has one job. The last column tells whether Composer installs the package as a dependency of another one, or whether you require it yourself. | Package | Role | Installed by | |---------|------|--------------| | `shopper/framework` | The admin panel: Livewire pages and components, roles and permissions, media on the catalog models, the `shopper:install` and `shopper:user` commands | You | | `shopper/core` | The e-commerce engine: models and their contracts, migrations, enums, observers, stock, prices, channels, search, outgoing webhooks | `shopper/framework` | | `shopper/cart` | Carts and their totals pipeline (lines, automatic promotions, discount codes, taxes), and the creation of an order from a cart | `shopper/framework` | | `shopper/payment` | The payment manager and its `manual` driver, payment transactions, payment provider events, reconciliation of pending payments | `shopper/framework` | | `shopper/shipping` | The shipping manager and its `manual` driver, carrier rates, shipment tracking sync | `shopper/framework` | | `shopper/sidebar` | The navigation builder behind the admin panel sidebar | `shopper/framework` | | `shopper/api` | The Store API: catalog, cart, checkout, customer and order endpoints as JSON:API under `/store`, and the `shopper:api:install` command | You | | `shopper/http` | The HTTP layer of the Store API: route groups, rate limiters, CORS, and the middleware that resolves the channel, zone, locale and customer of a request | `shopper/api` | | `shopper/stripe` | The `stripe` payment driver | You | | `shopper/fedex` | The `fedex` carrier driver: live rates and tracking | You | | `shopper/ups` | The `ups` carrier driver: live rates and tracking | You | | `shopper/usps` | The `usps` carrier driver: live rates | You | | `shopper/upgrade` | The `shopper:upgrade` command that moves a 2.x store to 3.x, required as a dev dependency and removed after the upgrade | You | | `@shopperlabs/shopper-sdk` | The JavaScript client of the Store API | You (npm) | | `@shopperlabs/shopper-types` | The TypeScript types of the Store API resources | `@shopperlabs/shopper-sdk` | `shopper/core`, `shopper/cart`, `shopper/payment`, `shopper/shipping` and `shopper/http` are not meant to be required on their own. Core binds its model contracts to the classes listed in `config/shopper/models.php`, a file that `shopper/framework` ships, so an application always starts from `shopper/framework`. `shopper/sidebar` is the exception: it does not depend on any other Shopper package and works in any Laravel application that runs Livewire 4. ## Dependencies [#dependencies] Every Shopper Composer package requires its Shopper dependencies at `self.version`, so Composer keeps all the Shopper packages of an application on the same version. | Package | Shopper packages it requires | Main third-party packages | |---------|------------------------------|---------------------------| | `shopper/framework` | core, cart, payment, shipping, sidebar | `filament/filament`, `spatie/laravel-medialibrary`, `spatie/laravel-permission`, `laravel/passkeys` | | `shopper/core` | None | `laravel/scout`, `league/csv`, `staudenmeir/laravel-adjacency-list`, `giggsey/libphonenumber-for-php` | | `shopper/cart` | core | None | | `shopper/payment` | core | None | | `shopper/shipping` | core | None | | `shopper/sidebar` | None | `livewire/livewire` | | `shopper/api` | core, cart, payment, shipping, http | `spatie/laravel-query-builder`, `spatie/laravel-medialibrary` | | `shopper/http` | core | `laravel/sanctum` | | `shopper/stripe` | payment | `stripe/stripe-php` | | `shopper/fedex` | core, shipping | None | | `shopper/ups` | core, shipping | None | | `shopper/usps` | shipping | None | | `shopper/upgrade` | None | `rector/rector` | `shopper/api` does not list `shopper/framework` in its `composer.json`, but it runs next to it: the customer endpoints need the `Shopper\Traits\InteractsWithShopper` trait on your `User` model, which `shopper/framework` provides. Install the Store API in an application where `shopper/framework` is already installed and migrated. On the npm side, `@shopperlabs/shopper-sdk` depends on `@shopperlabs/shopper-types` and re-exports its types, so a storefront installs the SDK only. `@shopperlabs/shopper-types` has no dependency and can be installed alone in a project that calls the Store API with its own HTTP client. ## What shopper/framework Installs [#what-shopperframework-installs] `composer require shopper/framework` installs the admin panel and five Shopper packages: core, cart, payment, shipping and sidebar. It also brings Filament 5, Livewire 4, Spatie Media Library and Spatie Laravel Permission, along with smaller packages for two-factor authentication, passkeys, charts and barcodes. With this single package, a store has its admin panel, its catalog, carts and orders, the `manual` payment driver and the `manual` shipping driver. These packages are not installed until you require them: - `shopper/api` and `shopper/http`, for a storefront that runs outside your Laravel application; - `shopper/stripe`, to take card payments with Stripe; - `shopper/fedex`, `shopper/ups` and `shopper/usps`, for live carrier rates; - `shopper/upgrade`, to move a 2.x store to 3.x. The [Installation](/3.x/installation) page installs `shopper/framework` and the Store API, and the [Payments](/3.x/payments) and [Carriers](/3.x/carriers) pages cover the drivers. ## Service Providers [#service-providers] Every Composer package registers one service provider through Laravel package discovery, declared under `extra.laravel.providers` in its `composer.json`. You have nothing to add to `bootstrap/providers.php`. | Service provider | Package | What it registers | |------------------|---------|-------------------| | `Shopper\ShopperServiceProvider` | `shopper/framework` | The admin routes, the Livewire pages and components, the sidebar, the settings and themes, the admin commands | | `Shopper\Core\CoreServiceProvider` | `shopper/core` | The model contract bindings, the morph map, the observers, the price, stock and channel services, the order reclaim and webhook redispatch tasks | | `Shopper\Cart\CartServiceProvider` | `shopper/cart` | The `Cart` and `CartLine` bindings, the cart pipeline, the promotion and discount services, the `shopper:prune-carts` task | | `Shopper\Payment\PaymentServiceProvider` | `shopper/payment` | The `Payment` manager, the payment session gateway, the `shopper:payments:reconcile` task | | `Shopper\Shipping\ShippingServiceProvider` | `shopper/shipping` | The `Shipping` manager, the carrier rate service, the `shopper:shipments:sync-tracking` task | | `Shopper\Sidebar\SidebarServiceProvider` | `shopper/sidebar` | The `sidebar` Livewire component and its assets | | `Shopper\Api\ApiServiceProvider` | `shopper/api` | The `/store` routes, the `shopper:api:install` command, the daily `sanctum:prune-expired` task | | `Shopper\Http\HttpServiceProvider` | `shopper/http` | The `shopper:store`, `shopper:store-auth` and `shopper:store-webhook` middleware groups, the rate limiters, the zone and channel resolvers, the CORS paths, the JSON:API error renderer | | `Shopper\Stripe\StripeServiceProvider` | `shopper/stripe` | The `stripe` payment driver | | `Shopper\FedEx\FedExServiceProvider` | `shopper/fedex` | The `fedex` shipping driver | | `Shopper\Ups\UpsServiceProvider` | `shopper/ups` | The `ups` shipping driver | | `Shopper\Usps\UspsServiceProvider` | `shopper/usps` | The `usps` shipping driver | | `Shopper\Upgrade\UpgradeServiceProvider` | `shopper/upgrade` | The `shopper:upgrade` command and its steps | The providers of framework, core, cart and payment load their migrations from the package: `php artisan migrate` runs them from `vendor/`, and they are never published. The installers publish only the migrations of third-party packages: `shopper:install` the Spatie Media Library one, `shopper:api:install` the Laravel Sanctum one. Payment and carrier drivers plug into two Laravel managers. `Shopper\Payment\PaymentManager` and `Shopper\Shipping\ShippingManager` each provide a `manual` driver. `shopper/stripe` adds the `stripe` driver with `Payment::extend()`, and the carrier packages add `fedex`, `ups` and `usps` with `Shipping::extend()`. A driver of your own registers the same way, as [Custom Drivers](/3.x/payments#custom-drivers) and [Custom Shipping Drivers](/3.x/carriers#custom-shipping-drivers) show. ## Configuration Files [#configuration-files] Each package merges its configuration under the `shopper` key, one file per key: `config/shopper/cart.php` is read with `config('shopper.cart')`. The `shopper-config` publish tag groups the files of every installed Shopper package, which is why `php artisan shopper:install` also publishes `api.php` and `http.php` once `shopper/api` is installed. Drivers use a tag of their own, so their file is published only when you ask for it. | Package | Files in `config/shopper/` | Publish tag | |---------|----------------------------|-------------| | `shopper/framework` | `addons.php`, `admin.php`, `auth.php`, `features.php`, `media.php`, `models.php`, `routes.php`, `settings.php`, `themes.php` | `shopper-config` | | `shopper/core` | `core.php`, `orders.php`, `search.php`, `webhooks.php` | `shopper-config` | | `shopper/cart` | `cart.php` | `shopper-config` | | `shopper/payment` | `payment.php` | `shopper-config` | | `shopper/shipping` | `shipping.php` | `shopper-config` | | `shopper/api` | `api.php` | `shopper-config` | | `shopper/http` | `http.php` | `shopper-config` | | `shopper/stripe` | `stripe.php` | `shopper-stripe-config` | | `shopper/fedex` | `fedex.php` | `shopper-fedex-config` | | `shopper/ups` | `ups.php` | `shopper-ups-config` | | `shopper/usps` | `usps.php` | `shopper-usps-config` | `shopper/sidebar` keeps its file outside this folder: `config/sidebar.php`, read with `config('sidebar')` and published with the `sidebar-config` tag. `shopper:install` does not publish it. `shopper/upgrade` has no configuration file. `shopper/framework` also writes the component files of the admin panel to `config/shopper/components/` when you run `php artisan shopper:component:publish`, as described in [Components](/3.x/configuration#components). The [Configuration](/3.x/configuration#configuration-files) page describes what each file holds. ## Reading Store Data [#reading-store-data] A storefront reaches the store data in one of two ways, depending on where it runs: inside your Laravel application, or as a separate application that calls the Store API. ### From Your Laravel Application [#from-your-laravel-application] A storefront rendered by the same Laravel application, with Blade, Livewire or Inertia, queries the Shopper models with Eloquent and needs no extra package. Resolve a model through its contract, so the class you set in `config/shopper/models.php` is the one queried: ```php title="app/Http/Controllers/ShopController.php" namespace App\Http\Controllers; use Illuminate\Contracts\View\View; use Shopper\Core\Models\Contracts\Product; final class ShopController extends Controller { public function index(): View { $products = resolve(Product::class)::query() ->publish() ->with('brand') ->latest('published_at') ->paginate(24); return view('shop.index', ['products' => $products]); } } ``` The `publish` scope keeps the products that are visible and whose publication date has passed. The [Models](/3.x/models) page lists every model with its contract. The visitor's cart lives in the session: the `Shopper\Cart\Facades\Cart` facade returns it with `Cart::current()`, or `null` while the visitor has no cart and `shopper.cart.session.auto_create` is off, its default. The [Cart](/3.x/cart) page covers the cart in detail. The routes that receive payment and carrier webhooks, `POST /store/webhooks/{driver}` and `POST /store/webhooks/shipping/{driver}`, are registered by `shopper/api`. Without that package, a payment provider such as Stripe has no route to notify your store. ### Through the Store API [#through-the-store-api] A storefront that runs elsewhere, such as a Next.js or Nuxt site or a mobile app, calls the Store API. `shopper/api` serves the catalog, carts, checkout, customer accounts and orders as [JSON:API](https://jsonapi.org) documents under `/store`. `shopper/http` holds the layer around these endpoints: the route groups, the rate limiters, CORS on the store routes, and the middleware that resolves the channel from the `X-Shopper-Channel` header, the zone from `X-Shopper-Zone`, the locale from `Accept-Language` and the customer from a Laravel Sanctum token. The prefix comes from `config('shopper.http.prefix')`, which reads the `SHOPPER_API_PREFIX` environment variable. The [Installation](/3.x/installation#install-the-store-api) page installs the Store API. The JavaScript SDK wraps these endpoints and returns the nested objects described by `@shopperlabs/shopper-types`. It runs wherever `fetch` exists: browsers, Node.js 18+, React Native and edge runtimes. ```bash npm install @shopperlabs/shopper-sdk ``` This script creates a client for the store and lists the 12 newest products whose name contains "t-shirt": ```typescript import Shopper from '@shopperlabs/shopper-sdk' const sdk = new Shopper({ baseUrl: 'https://shop.example.com' }) const { data: products } = await sdk.store.product.list({ filter: { name: 't-shirt' }, sort: ['-published_at'], page: { size: 12 }, }) ``` The SDK calls `/store` by default; set its `storePrefix` option when you change the API prefix. The [Storefront](/3.x/storefront) section covers the endpoints, and the [JavaScript SDK](/3.x/sdk) pages the client in detail. # Attributes (/3.x/attributes) Attributes describe the characteristics of a product: the color and size of a T-shirt, the material of a jacket, the care instructions of a sweater. An attribute such as "Color" holds a list of values ("Navy", "White", "Heather Grey") that products pick from, or takes a free value typed for each product, such as "100% organic cotton". The same attributes serve two purposes. On any product, they are specifications that a storefront displays and filters on. On a variant product, the values picked from an attribute become the options of its variants: a "Classic T-Shirt" with three colors and four sizes has twelve variants, each linked to one color and one size. ## Models [#models] Shopper uses three models for attributes: | Model | Table | Purpose | |-------|-------|---------| | `Shopper\Core\Models\Attribute` | `sh_attributes` | The attribute definition: Color, Size, Material | | `Shopper\Core\Models\AttributeValue` | `sh_attribute_values` | A value an attribute offers: Navy, Large | | `Shopper\Models\AttributeProduct` | `sh_attribute_product` | One row per value a product has, or its free value | Each model implements the contract of the same name in `Shopper\Core\Models\Contracts`. Two traits of the `Attribute` model change what you can do with it: - `HasSlug` turns the `slug` you assign into a URL-safe value and appends `-1`, `-2` and so on when it is already taken. The slug is not derived from the name: the admin form fills it from the name, and your code passes one. - `HasPublicId` fills `public_id` with a ULID when the attribute is created. The Store API returns it as the attribute `id`. `Attribute` and `AttributeValue` have no configuration key, so they are always loaded with their own class, as described in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). Query them with `Attribute::query()` and `AttributeValue::query()`. The pivot model is swappable through the `attribute_product` key of `config/shopper/models.php`. Its default, `Shopper\Models\AttributeProduct`, extends `Shopper\Core\Models\AttributeProduct` and adds the Spatie Media Library methods that store the swatch image of a value. To add your own methods, extend the admin class: ```php title="app/Models/AttributeProduct.php" attribute->slug === 'color'; } } ``` Then point the key to your class: ```php title="config/shopper/models.php" 'attribute_product' => App\Models\AttributeProduct::class, ``` The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ## Database Schema [#database-schema] Attributes use four tables. The names below use `sh_`, the default [table prefix](/3.x/configuration#database-table-prefix). ### Attribute Table [#attribute-table] The `sh_attributes` table holds one row per attribute: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Attribute name | | `slug` | string | yes | null | URL identifier, unique | | `description` | string | yes | null | Short description, 100 characters in the admin form | | `type` | string | no | - | Field type, cast to `FieldType` | | `icon` | string | yes | null | Icon name, shown in the admin panel and returned by the Store API | | `is_enabled` | boolean | no | `false` | Offered when attributes are chosen for a product, and exposed by the Store API | | `is_searchable` | boolean | no | `false` | Marks the attribute as searchable, see [Searchable and Filterable Attributes](#searchable-and-filterable-attributes) | | `is_filterable` | boolean | no | `false` | Marks the attribute as a storefront filter | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### AttributeValue Table [#attributevalue-table] The `sh_attribute_values` table holds the values of the attributes that offer a list. It has no timestamps: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `value` | string(50) | no | - | Label shown to customers, indexed | | `key` | string | no | - | Identifier, unique within the attribute. A hex code such as `#1e3a8a` for a color | | `position` | smallint | yes | `1` | Display order | | `attribute_id` | bigint | no | - | Attribute, deleted with it | The `key` is unique per attribute: a "Size" and a "Shoe Size" attribute can both have a `large` value. ### AttributeProduct Table (Pivot) [#attributeproduct-table-pivot] The `sh_attribute_product` table links a product to its attributes. It has no timestamps: | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `attribute_id` | bigint | no | Attribute, row deleted with it | | `product_id` | bigint | no | Product, row deleted with it | | `attribute_value_id` | bigint | yes | Selected value, row deleted with it | | `attribute_custom_value` | longtext | yes | Free value of a text, number, date or rich text attribute | A product with three colors has three rows for the "Color" attribute, one per value. A free-text attribute has one row, with `attribute_value_id` left empty. ### Variant Value Table (Pivot) [#variant-value-table-pivot] The `sh_attribute_value_product_variant` table links each variant to its option values, with a `value_id` and a `variant_id` column. Both foreign keys cascade: deleting a value or a variant deletes the link. ## Field Types [#field-types] The `type` column is cast to the `Shopper\Core\Enum\FieldType` enum. The type decides whether the attribute offers a list of values or takes a free value per product, and which input the admin panel shows: | Case | Value | Admin label | Values | Per product | |------|-------|-------------|--------|-------------| | `FieldType::Checkbox` | `checkbox` | Checkbox | List | One or more values | | `FieldType::ColorPicker` | `colorpicker` | Color picker | List, with a hex code as key | One or more values | | `FieldType::Select` | `select` | Select | List | One value | | `FieldType::Text` | `text` | Text field (input) | Free | A line of text | | `FieldType::Number` | `number` | Text field (number) | Free | A number, stored as text | | `FieldType::DatePicker` | `datepicker` | Date picker | Free | A date, stored as text | | `FieldType::RichText` | `richtext` | Rich text | Free | HTML | The admin panel lets you change the type of an existing attribute, but its values and product rows stay as they were. Choose the type before you assign the attribute to products. ### Type Checking Methods [#type-checking-methods] Four methods group the types by behavior: ```php use Shopper\Core\Models\Attribute; $attribute->hasMultipleValues(); $attribute->hasSingleValue(); $attribute->hasTextValue(); Attribute::fieldsWithValues(); ``` `hasMultipleValues()` returns `true` for Checkbox and ColorPicker, `hasSingleValue()` for Select, and `hasTextValue()` for Text, Number, RichText and DatePicker. The static `fieldsWithValues()` returns the three types that offer a list of values: `[FieldType::Checkbox, FieldType::ColorPicker, FieldType::Select]`. ## Relationships [#relationships] An attribute has many values and belongs to many products. A value belongs to one attribute and to many variants. ### Values [#values] The `values()` relationship returns the `AttributeValue` models of the attribute: ```php $attribute->values; $attribute->values()->create([ 'value' => 'Navy', 'key' => '#1e3a8a', 'position' => 1, ]); ``` To add several values at once: ```php $size->values()->createMany([ ['value' => 'Small', 'key' => 'small', 'position' => 1], ['value' => 'Medium', 'key' => 'medium', 'position' => 2], ['value' => 'Large', 'key' => 'large', 'position' => 3], ]); ``` The admin panel stores keys in lowercase and does not set the position, so values added there keep a position of `1`. The `options` include of the Store API sorts the values of a product by position, then by ID, while `GET /store/attributes` returns them in database order. `$value->attribute` returns the attribute of a value. ### Products [#products] The `products()` relationship returns the products that use the attribute, with the `attribute_value_id` and `attribute_custom_value` pivot columns. It reads the product class from `config('shopper.models.product')`: ```php $attribute->products; $color->products()->attach($product->id, [ 'attribute_value_id' => $navy->id, ]); $material->products()->attach($product->id, [ 'attribute_custom_value' => '100% organic cotton', ]); ``` From the product side, the same rows are read through `options()` and `attributeProducts()`, as shown in [Assigning Attributes to Products](#assigning-attributes-to-products). ### Variants (AttributeValue) [#variants-attributevalue] The `variants()` relationship of a value returns the variants that carry it, read from `config('shopper.models.variant')`. Its inverse is `values()` on the variant: ```php $navy->variants; $variant->values; $variant->values()->attach([$navy->id, $large->id]); ``` The admin panel creates these links when it generates the variants of a product. The [Product Variants](/3.x/product-variants) page covers variant generation. ## Slug & Lookup [#slug--lookup] `findBySlug()` returns the attribute with that slug and throws a `ModelNotFoundException` when none matches. `findByPublicId()` returns `null` instead: ```php use Shopper\Core\Models\Attribute; $color = Attribute::findBySlug('color'); $color = Attribute::findByPublicId('01JBX3M5D7R8K2C9P4W6Y0T1QE'); ``` Neither method checks whether the attribute is enabled. ## Query Scopes [#query-scopes] Three scopes filter attributes by their flags: ```php use Shopper\Core\Models\Attribute; Attribute::query()->enabled()->get(); Attribute::query()->isFilterable()->get(); Attribute::query()->isSearchable()->get(); ``` Scopes can be combined: ```php Attribute::query() ->enabled() ->isFilterable() ->with('values') ->get(); ``` ## Status Management [#status-management] `updateStatus()` enables or disables an attribute. It saves the `is_enabled` column right away: ```php $attribute->updateStatus(); $attribute->updateStatus(false); ``` The status argument defaults to `true`. The Enable and Disable bulk actions of the admin panel call the same method. ## Display Helpers [#display-helpers] `type_formatted` returns the translated label of the attribute type, such as "Color picker". The static `typesFields()` returns every type label keyed by its value, which is what the admin form offers in its type select: ```php use Shopper\Core\Models\Attribute; $attribute->type_formatted; Attribute::typesFields(); ``` ## Working with AttributeProduct [#working-with-attributeproduct] `attributeProducts()` on a product returns its pivot rows as models of the configured `AttributeProduct` class. Each row has its `attribute`, `product` and `value` relationships, and a `real_value` accessor that returns the free value when the row has one, or the label of the selected value: ```php use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $specifications = $product->attributeProducts() ->with(['attribute', 'value']) ->get() ->mapToGroups(fn ($row): array => [$row->attribute->name => $row->real_value]); ``` For a T-shirt in two colors, `$specifications` holds `['Color' => ['Navy', 'White'], 'Material' => ['100% organic cotton']]`. Each row can also hold a swatch: an image shown in place of the color, such as a photo of the fabric, that belongs to this product only. It is stored in the `swatch` media collection, which keeps a single JPEG, PNG, WebP or AVIF file on the media disk. The admin panel uploads it from the Swatch image action of the product attributes table: ```php $swatchUrl = $row->getFirstMediaUrl('swatch'); ``` The [Media](/3.x/media) page covers disks and conversions. ## Product Attributes and Variant Options [#product-attributes-and-variant-options] Standard, variant and virtual products can have attributes; external products cannot. `canUseAttributes()` on the product tells which. The attributes of a product are read through two relationships over the same `sh_attribute_product` rows: - `options()` returns `Attribute` models with the `attribute_value_id` and `attribute_custom_value` pivot columns. An attribute with three selected values appears three times. - `attributeProducts()` returns the rows themselves, as described in [Working with AttributeProduct](#working-with-attributeproduct). On a standard or virtual product, these rows are specifications. A storefront lists them on the product page and filters the catalog on their values. On a variant product, the values picked from the Checkbox, ColorPicker and Select attributes are also the options of its variants. The admin panel builds the variant combinations from them: a T-shirt with Navy and White for "Color" and Medium and Large for "Size" gets four combinations, and each variant is linked to one value per attribute through `sh_attribute_value_product_variant`. Free-value attributes, such as a "Care Instructions" rich text, never take part in the combinations. Every value attribute attached to a variant product does, even with a single value, so give descriptive attributes of a variant product a free-value type. The Generate button of the Variants section only appears once the product has attributes. The [Product Variants](/3.x/product-variants) page covers generation, SKUs and stock per variant. The `option` scope of the product model finds the products that carry a value, among the attribute rows of the product or the values of its variants. It matches the `key` or the `value` of the attribute value, in any attribute. Values passed to one call match any of them, and chained calls must all match: ```php use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::query() ->publish() ->option('#1e3a8a') ->option('medium', 'large') ->paginate(12); ``` The [Products](/3.x/products) page lists the other catalog scopes. ## Searchable and Filterable Attributes [#searchable-and-filterable-attributes] An attribute has three flags. Each one is read in specific places, and none of them changes the data already attached to products: | Flag | Read by | |------|---------| | `is_enabled` | The admin panel only offers enabled attributes when attributes are chosen for a product. The Store API only returns enabled attributes, in `GET /store/attributes` and in the `options` of a product | | `is_filterable` | `GET /store/attributes` lists the enabled, filterable attributes that offer values, so a storefront can build its filter menu from it. Your own code reads it with the `isFilterable()` scope | | `is_searchable` | Nothing in Shopper. The product search index does not contain attribute values. Use the `isSearchable()` scope to pick the attributes your own indexer sends, as described in [Search](/3.x/search) | Disabling an attribute keeps it on the products that already have it: the product editor still lists it, the variant generator still uses its values, and the `option` scope still matches them. The `option` scope and the `filter[option]` parameter of the Store API ignore `is_filterable` as well. ## Configuration [#configuration] Attributes have a feature flag and a set of admin components. The only swappable model is the pivot, as described in [Models](#models). ### Disabling Attribute Feature [#disabling-attribute-feature] Attributes are enabled on a fresh install. To turn them off, set the `attribute` key of the feature flags: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'attribute' => FeatureState::Disabled, ]; ``` When the flag is disabled, the admin panel hides the Attributes item of the Products menu, the attributes page and the Attributes section of the product editor. Without that section, a merchant cannot add attributes to a variant product, and therefore cannot generate its variants: keep the flag on if you sell variant products. The Store API keeps serving attributes. See [Feature Flags](/3.x/configuration#feature-flags). ### Components [#components] The attribute screens belong to the product components of the admin panel. To replace one of them with your own Livewire component, publish the product component file: ```bash php artisan shopper:component:publish product ``` The command creates `config/shopper/components/product.php`. The keys for attributes are the Attributes section of the product editor, its page, the attributes list and three slide-overs: ```php title="config/shopper/components/product.php" use Shopper\Livewire; use Shopper\Navigation\Product\Sections; return [ 'sections' => [ Sections\AttributesSection::class => true, ], 'pages' => [ 'product-attributes' => Livewire\Pages\Product\Attributes::class, 'attribute-index' => Livewire\Pages\Attribute\Browse::class, ], 'components' => [ 'slide-overs.attribute-form' => Livewire\SlideOvers\AttributeForm::class, 'slide-overs.choose-product-attributes' => Livewire\SlideOvers\ChooseProductAttributes::class, 'slide-overs.attribute-values' => Livewire\SlideOvers\AttributeValues::class, ], ]; ``` The published file keeps every other product key. The [Configuration](/3.x/configuration#components) page covers component files. ## Usage [#usage] The examples below set up a T-shirt catalog: a Color and a Size attribute that drive variants and filters, and free-value attributes for product specifications. ### Creating Attributes [#creating-attributes] Pass the type as a `FieldType` case and a slug, then add the values. #### Attribute with Predefined Values [#attribute-with-predefined-values] A color attribute stores the hex code of each color as its key: ```php use Shopper\Core\Enum\FieldType; use Shopper\Core\Models\Attribute; $color = Attribute::query()->create([ 'name' => 'Color', 'slug' => 'color', 'type' => FieldType::ColorPicker, 'is_enabled' => true, 'is_filterable' => true, ]); $color->values()->createMany([ ['value' => 'Navy', 'key' => '#1e3a8a', 'position' => 1], ['value' => 'White', 'key' => '#ffffff', 'position' => 2], ['value' => 'Heather Grey', 'key' => '#9ca3af', 'position' => 3], ]); ``` Keep each `value` within 50 characters, the size of the column. #### Attribute with Free Text [#attribute-with-free-text] A free-value attribute needs no values: ```php $careInstructions = Attribute::query()->create([ 'name' => 'Care Instructions', 'slug' => 'care-instructions', 'type' => FieldType::RichText, 'is_enabled' => true, ]); ``` ### Assigning Attributes to Products [#assigning-attributes-to-products] Attach an attribute through the `options()` relationship of the product, once per value. A free-value attribute takes its value in `attribute_custom_value`: ```php use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $navy = $color->values()->where('key', '#1e3a8a')->first(); $white = $color->values()->where('key', '#ffffff')->first(); $product->options()->attach([ $color->id => ['attribute_value_id' => $navy->id], ]); $product->options()->attach($color->id, ['attribute_value_id' => $white->id]); $product->options()->attach($careInstructions->id, [ 'attribute_custom_value' => '

    Machine wash at 30 degrees.

    ', ]); ``` The admin panel allows one value for a Select attribute and several for Checkbox and ColorPicker. The model does not check it, so your code decides how many values it attaches. Each attribute of `$product->options` carries its row in `pivot`: ```php foreach ($product->options as $attribute) { $valueId = $attribute->pivot->attribute_value_id; $customValue = $attribute->pivot->attribute_custom_value; } ``` To remove one value, delete its row through `attributeProducts()`, one model at a time so its swatch image is deleted with it (a query delete leaves the file behind). On a variant product, also detach the value from the variants that carry it, as the admin panel does: ```php $product->attributeProducts() ->where('attribute_value_id', $white->id) ->get() ->each ->delete(); $product->variants->each(fn ($variant) => $variant->values()->detach($white->id)); ``` ### Retrieving Attributes [#retrieving-attributes] Load the values with the attributes, and sort them by position where the order matters: ```php use Shopper\Core\Models\Attribute; $attributes = Attribute::query() ->enabled() ->with('values') ->get(); $filters = Attribute::query() ->enabled() ->isFilterable() ->whereIn('type', Attribute::fieldsWithValues()) ->with(['values' => fn ($query) => $query->orderBy('position')]) ->get(); $size = Attribute::findBySlug('size')->load('values'); ``` ### Storefront Example [#storefront-example] A catalog page builds its filter menu from the filterable attributes, then narrows the products with one `option()` call per attribute, so a T-shirt must match every chosen attribute and any chosen value within one: ```php title="app/Http/Controllers/ProductFilterController.php" enabled() ->isFilterable() ->whereIn('type', Attribute::fieldsWithValues()) ->with(['values' => fn ($query) => $query->orderBy('position')]) ->get(); $products = resolve(Product::class)::query()->publish(); foreach ((array) $request->input('filters', []) as $keys) { $products->option($keys); } return view('products.index', [ 'filters' => $filters, 'products' => $products->paginate(12)->withQueryString(), ]); } } ``` The form of the filter menu sends the keys of the checked values per attribute slug, such as `filters[size][]=medium&filters[size][]=large`. ### Use Cases [#use-cases] Each field type fits a kind of product information: | Field type | Example | Use case | |------------|---------|----------| | Checkbox | Size | Sizes of a clothing product, one variant per size | | ColorPicker | Color | Colors with a swatch, one variant per color | | Select | Fit | One value per product, such as Slim or Regular, used as a filter | | Text | Country of Origin | A line of text per product | | Number | Thread Count | A numeric specification per product | | DatePicker | Release Date | The launch date of a sneaker drop | | RichText | Care Instructions | Formatted washing and care instructions | ## Events [#events] Shopper dispatches no attribute event of its own. Listen to the Eloquent events of `Shopper\Core\Models\Attribute` and `Shopper\Core\Models\AttributeValue`, for example to clear a cached filter menu: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Attribute; public function boot(): void { Attribute::saved(fn () => Cache::forget('storefront.filters')); Attribute::deleted(fn () => Cache::forget('storefront.filters')); } ``` Adding or removing the attributes of a product does not dispatch `ProductUpdated`, as noted on the [Events](/3.x/events) page. ### Observer Behavior [#observer-behavior] `Shopper\Core\Observers\AttributeObserver` runs when an attribute is deleted. It detaches the attribute from every product, then deletes its values with a single query, so no `deleted` event fires for each value: ```php $color->delete(); ``` The foreign keys finish the cleanup: deleting a value removes it from every product and every variant that carried it. Deleting the "Color" attribute of a variant product leaves its variants without a color, so regenerate them or delete them afterwards. ## Permissions [#permissions] The admin panel checks four permissions of the `attributes` resource, which the role editor lists in the Products group: | Permission | Allows | |------------|--------| | `attributes.browse` | Opening the attributes page | | `attributes.create` | Creating an attribute | | `attributes.edit` | Editing an attribute, enabling and disabling attributes, adding and editing values | | `attributes.delete` | Deleting attributes and values, and removing an attribute from a product | The Attributes item of the sidebar shows for a user with `products.browse` or `attributes.browse`. Choosing the attributes of a product needs `products.edit`. `attributes.read` is seeded with the others, but the admin panel never checks it. Shopper 2.x named these permissions `browse_attributes`, `add_attributes` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants manage attributes under Products, Attributes. The list shows each attribute with its icon, name, type, its enabled, searchable and filterable flags, and its last update, and filters on the three flags. The form opens in a slide-over: name, slug, type, icon, description, the Enable toggle and the searchable and filterable checkboxes. Attributes that offer a list have a Values button that opens their values, with a color picker for the key of a color. In the product editor, the Attributes section picks enabled attributes and their values in two steps, lists them grouped by attribute, and sets the swatch image of each value. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes attributes under the `store` prefix, set by `SHOPPER_API_PREFIX`. `GET /store/attributes` returns the enabled, filterable attributes of the Checkbox, ColorPicker and Select types, paginated, each with its values. Filter it with `filter[name]` (partial match) and sort it with `sort=name`. There is no endpoint for a single attribute. An attribute resource has the type `attributes`, its public ID as `id`, and carries `name`, `slug`, `description`, `type`, `icon` and `values`, a list of `key`, `value` and `position`. The products endpoint filters and includes by attribute value. `filter[option]` accepts value keys or labels, separated by commas, and keeps the products that carry any of them: ```bash curl "https://example.com/store/products?filter[option]=medium,large&include=options" ``` `include=options` adds an `options` list to each product that can have attributes: the enabled attributes of the product with `name`, `slug`, `description`, `type`, `icon`, `custom_value` for a free-value attribute, and the values the product uses, each with `key`, `value`, `position` and `swatch_url`. `include=variants` returns the option values of each variant in its `values` attribute, with the attribute name and slug. The Store API serves attributes even when the `attribute` feature flag is disabled. The Store API [Catalog](/3.x/store-api/catalog#attributes) guide covers the attribute endpoints. # Brands (/3.x/brands) A brand is the manufacturer or label of a product: Nike, Adidas, Apple. Each product belongs to at most one brand, through the `brand_id` column of the products table. A storefront uses brands for a "Shop by Brand" page, a brand page listing its products, and a brand filter on the catalog. ## Model [#model] The model configured for brands is `Shopper\Models\Brand`. It extends `Shopper\Core\Models\Brand` and implements the `Shopper\Core\Models\Contracts\Brand` contract. The core class holds the columns, the relationship to products and the scopes; the admin class adds the media collections and image conversions, as described in [Core Models and Admin Models](/3.x/models#core-models-and-admin-models). Four traits of the core class change what you can do with a brand: - `HasSlug` turns the `slug` you assign into a URL-safe value and appends `-1`, `-2` and so on when it is already taken, as described in [Slug Generation](#slug-generation). - `HasPublicId` fills `public_id` with a ULID when the brand is created. The Store API returns it as the brand `id`. - `HasMediaCollections` declares the logo and image collections described in [Media](#media). - `Searchable` sends enabled brands to the search index. The [Search](/3.x/search) page covers indexing. ### Extending the Model [#extending-the-model] To add your own methods, extend the admin class: ```php title="app/Models/Brand.php" whereHas('products', fn (Builder $products) => $products->publish()); } } ``` Then point the `brand` key of the configuration to your class: ```php title="config/shopper/models.php" 'brand' => App\Models\Brand::class, ``` Extend the admin class `Shopper\Models\Brand`: the admin panel reads the brand logo through its media methods. The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ## Database Schema [#database-schema] Brands are stored in the `sh_brands` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Brand name | | `slug` | string | yes | null | URL identifier, unique | | `website` | string | yes | null | Official website of the brand | | `description` | longtext | yes | null | Brand description, HTML from the admin rich editor | | `position` | smallint (unsigned) | no | 0 | Display order | | `is_enabled` | boolean | no | false | Whether the brand is shown on the storefront | | `seo_title` | string(60) | yes | null | Title for search engines | | `seo_description` | string(160) | yes | null | Description for search engines | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A new brand is disabled by default. Set `is_enabled` to `true` when you create one that the storefront must show. ## Slug Generation [#slug-generation] The `HasSlug` trait runs every slug you assign through `Str::slug()`, so `Nike Running` becomes `nike-running`. When another brand already has that slug, it appends a counter: `nike-running-1`, then `nike-running-2`. A value that produces an empty slug, such as a string of symbols, is replaced with five random characters. The slug is not derived from the name in code. The admin form fills it from the name when the field is left empty; when you create a brand in your own code, pass a slug, because the Store API finds brands by their slug. The trait also adds `findBySlug()`, which throws a `ModelNotFoundException` when no brand matches: ```php use Shopper\Core\Models\Contracts\Brand; $nike = resolve(Brand::class)::findBySlug('nike'); ``` ## Relationships [#relationships] A brand has many products. The relation reads the product class from `config('shopper.models.product')`, so it returns your product model after a swap. ### Products [#products] `products()` is a `HasMany` relation on the `brand_id` column of the products table. Deleting a brand sets `brand_id` to `null` on its products; the products themselves stay: ```php use Shopper\Core\Models\Contracts\Brand; $nike = resolve(Brand::class)::findBySlug('nike'); $nike->products; $nike->products()->publish()->count(); ``` From the product side, `brand()` is a `BelongsTo` relation. Assign a brand to a product with `associate()`: ```php $product->brand()->associate($nike); $product->save(); $product->brand->name; ``` To list the published products of one or several brands, use the `byBrand` scope of the product model. It matches brands by slug or by public ID, and ignores disabled brands: ```php use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::query() ->publish() ->byBrand('nike', 'adidas') ->latest('published_at') ->paginate(24); ``` ## Query Scopes [#query-scopes] The model has one scope of its own, and the traits add lookups by slug and by public ID. ### Enabled Brands [#enabled-brands] The `enabled` scope keeps the brands whose `is_enabled` column is `true`. Use it on every storefront query: ```php use Shopper\Core\Models\Contracts\Brand; $brands = resolve(Brand::class)::query() ->enabled() ->orderBy('position') ->get(); ``` `findByPublicId()` returns `null` when no brand matches, and the `wherePublicId` scope filters a query by public ID. The [Models](/3.x/models#public-ids) page describes public IDs. ## Status Management [#status-management] `updateStatus()` enables a brand, or disables it when you pass `false`. It saves the change immediately: ```php $nike->updateStatus(); $nike->updateStatus(false); ``` Disabling a brand hides it everywhere a customer could see it, without touching its products: - The Store API stops returning it: `GET /store/brands` leaves it out, `GET /store/brands/{slug}` answers 404, the `brand` include of a product returns nothing and `filter[brand]` no longer matches it. - The `byBrand` scope ignores it, and the brand is removed from the search index. - The product forms of the admin panel only offer enabled brands. The products of a disabled brand stay published. Once the change is committed, Shopper reindexes them, because the product index carries the brand name only while the brand is enabled. ## Media [#media] Brands have two media collections, named in `config/shopper/media.php`: | Collection | Config key | Default name | Files | Use | |------------|------------|--------------|-------|-----| | Images | `shopper.media.storage.collection_name` | `uploads` | Several | Extra brand images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | `thumbnail` | One | The brand logo | The admin form uploads the logo to the thumbnail collection, up to `shopper.media.max_size.thumbnail` kilobytes (1024 by default). Both collections accept the MIME types listed in `shopper.media.accepts_mime_types`: JPEG, PNG, WebP and AVIF. Each upload gets the conversions of `shopper.media.conversions`, `large` (800x800) and `medium` (500x500) by default. Add a logo from an upload or from a URL: ```php $nike->addMedia($request->file('logo')) ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); $nike->addMediaFromUrl('https://cdn.example.com/brands/nike.png') ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); ``` `getThumbnailUrl()` returns the logo URL. It falls back to the first image of the images collection, then to the placeholder image of the admin panel. Pass a conversion name to get the resized file; when that conversion has not been generated yet, it returns the original: ```php $logoUrl = $nike->getThumbnailUrl('medium'); ``` The [Media](/3.x/media) page covers storage disks, conversions and the placeholder image. ## Configuration [#configuration] Brands are on by default. Their settings are the feature flag, the model key and the admin components. ### Disabling Brands [#disabling-brands] If your store does not use brands, disable the feature in `config/shopper/features.php`: ```php title="config/shopper/features.php" 'brand' => Shopper\Enum\FeatureState::Disabled, ``` The brands page is no longer registered, the Brands item leaves the sidebar, and the brand column of the products list and the brand field of the product forms are hidden. The flag only changes the admin panel: the model, the `brand_id` column and the Store API brand endpoints stay available. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Components [#components] The brands section of the admin panel is made of one page and one form. To replace either with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish brand ``` The command creates `config/shopper/components/brand.php`: ```php title="config/shopper/components/brand.php" use Shopper\Livewire; return [ 'pages' => [ 'brand-index' => Livewire\Pages\Brand\Index::class, ], 'components' => [ 'slide-overs.brand-form' => Livewire\SlideOvers\BrandForm::class, ], ]; ``` The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below resolve the brand class from its contract, so they keep working after you swap the model. ### Creating Brands [#creating-brands] The model accepts every column through `create()`. Pass the slug the storefront will use in its URLs, and enable the brand: ```php use Shopper\Core\Models\Contracts\Brand; $nike = resolve(Brand::class)::query()->create([ 'name' => 'Nike', 'slug' => 'nike', 'website' => 'https://www.nike.com', 'description' => '

    Running shoes, sneakers and sportswear.

    ', 'position' => 1, 'is_enabled' => true, 'seo_title' => 'Nike shoes and sportswear', 'seo_description' => 'Shop Nike running shoes, sneakers and sportswear.', ]); $nike->addMedia($request->file('logo')) ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); ``` ### Retrieving Brands [#retrieving-brands] For a brand list or a filter dropdown, load the enabled brands that have published products, with their count: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Models\Contracts\Brand; $brands = resolve(Brand::class)::query() ->enabled() ->whereHas('products', fn (Builder $query) => $query->publish()) ->withCount(['products' => fn (Builder $query) => $query->publish()]) ->orderBy('position') ->get(['id', 'name', 'slug']); ``` ### Updating Brands [#updating-brands] Update a brand like any Eloquent model. A slug you change goes through the same slug rules as on creation: ```php $nike->update([ 'website' => 'https://about.nike.com', 'seo_title' => 'Nike running shoes', ]); ``` ### Metadata [#metadata] The `metadata` column stores data that has no column of its own, cast to an array. The admin form edits it as a list of keys and values: ```php $nike->update([ 'metadata' => [ 'country_of_origin' => 'United States', 'founded_year' => 1964, ], ]); $country = $nike->metadata['country_of_origin'] ?? null; ``` The Store API returns `metadata` with the brand, so keep data the customers must not see out of it. ### Storefront Example [#storefront-example] A brand listing page and a brand page with its published products: ```php title="app/Http/Controllers/BrandController.php" enabled() ->withCount(['products' => fn (Builder $query) => $query->publish()]) ->orderBy('position') ->get(); return view('brands.index', ['brands' => $brands]); } public function show(string $slug): View { $brand = resolve(Brand::class)::query() ->enabled() ->where('slug', $slug) ->firstOrFail(); $products = $brand->products() ->publish() ->latest('published_at') ->paginate(12); return view('brands.show', ['brand' => $brand, 'products' => $products]); } } ``` A store that sells on several channels adds the `channel` scope to the product query, as shown in [Channels](/3.x/channels). ### View Composer [#view-composer] When the same brand list appears in several views, such as the header menu and the catalog filters, share it through a view composer: ```php title="app/View/Composers/BrandsComposer.php" with('brands', resolve(Brand::class)::query() ->enabled() ->orderBy('position') ->take(12) ->get(['id', 'name', 'slug'])); } } ``` Register it in the `boot()` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\View\Composers\BrandsComposer; use Illuminate\Support\Facades\View; public function boot(): void { View::composer(['partials.header', 'catalog.filters'], BrandsComposer::class); } ``` ## Events [#events] Shopper dispatches no brand event of its own. Listen to the Eloquent model events instead. They are dispatched under the core class name as well, so a listener registered on `Shopper\Core\Models\Brand` keeps firing after you swap the model: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Brand; public function boot(): void { Brand::saved(fn () => Cache::forget('storefront.brands')); Brand::deleted(fn () => Cache::forget('storefront.brands')); } ``` Shopper registers `Shopper\Core\Observers\BrandObserver` on the brand model. When the name or the status of a brand changes, or when a brand is deleted, it reindexes the brand's products once the transaction is committed. The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks four permissions of the `brands` resource, in the Catalog group: | Permission | Allows | |------------|--------| | `brands.browse` | Opening the brands page and seeing the Brands sidebar item | | `brands.create` | Opening and saving the form for a new brand | | `brands.edit` | Editing a brand, reordering the list, enabling and disabling brands in bulk | | `brands.delete` | Deleting a brand, one at a time or in bulk | `brands.read` is seeded with the others, but the admin panel never checks it. Shopper 2.x named these permissions `browse_brands`, `add_brands` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants manage brands under Catalog, Brands. The page lists each brand with its logo, name, website, visibility and last update, filters by visibility, and lets merchants drag rows to change their position. Bulk actions enable, disable or delete the selected brands. The brand form opens in a slide-over with four sections: General (name, slug, website, visibility, description), Media (the logo), SEO and Metadata. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the enabled brands under the `store` prefix, set by `SHOPPER_API_PREFIX`: | Endpoint | Returns | |----------|---------| | `GET /store/brands` | The enabled brands, paginated. Filter with `filter[name]` (partial match), sort with `sort=name` or `sort=position` | | `GET /store/brands/{slug}` | One enabled brand. Add `include=products` for its products published on the channel of the request | A brand resource has the type `brands` and carries `name`, `slug`, `website`, `description`, `seo_title`, `seo_description`, `metadata`, `thumbnail` (the logo with its conversion URLs), `created_at` and `updated_at`. The products endpoint filters and includes by brand. `filter[brand]` accepts brand slugs or public IDs, separated by commas: ```bash curl "https://example.com/store/products?filter[brand]=nike,adidas&include=brand" ``` The `products` include and the product listing follow the channel of the request, as described in [Channels](/3.x/channels#the-store-api); the brands themselves are not filtered by channel. The Store API [Catalog](/3.x/store-api/catalog#brands) guide covers the brand endpoints. # Campaigns (/3.x/campaigns) A campaign groups discounts under one name, one currency, a schedule and an optional shared budget. A "Summer Sale 2026" campaign can hold a `SUMMER20` code, a `BEACH15` code and an automatic discount on sandals, and stop all three once they have given $5,000.00 of discounts or been used on 1,000 orders. Each discount keeps its own rules, dates and usage limits, described on the [Discounts](/3.x/discounts) page. The campaign adds the cap they share: the cart stops applying the campaign's discounts once its budget is used, the checkout reserves budget for each order, and a cancellation or a full refund gives it back. Every reservation and release is recorded as a budget movement. The models live in `shopper/core`, and the admin panel shows campaigns behind the `campaign` feature flag. ## Model [#model] Campaigns use `Shopper\Core\Models\Campaign`, which implements the `Shopper\Core\Models\Contracts\Campaign` contract. Budget movements use `Shopper\Core\Models\CampaignBudgetMovement`. Neither model has a key in `config/shopper/models.php`, so both are always loaded with their own class. To add a relationship to one of them, register it with `resolveRelationUsing()`, as shown in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). The `HasPublicId` trait fills the `public_id` of a campaign with a ULID when it is created, so you can find a campaign with `Campaign::findByPublicId()` or the `wherePublicId()` scope, described in [Public IDs](/3.x/models#public-ids). Budget movements have no public ID. ### Campaign Table [#campaign-table] The `sh_campaigns` table holds one row per campaign (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `is_active` | boolean | no | `true` | Turns the campaign off without deleting it | | `name` | string | no | - | Campaign name, such as "Summer Sale 2026" | | `currency_code` | string | no | - | ISO code of the budget currency, such as `USD` | | `budget_type` | string | no | `none` | Caps the campaign enforces, cast to `CampaignBudgetType` | | `budget_amount` | unsigned bigint | yes | null | Spend cap, in cents | | `budget_count` | unsigned integer | yes | null | Usage cap, in orders | | `spent_amount` | unsigned bigint | no | 0 | Discount amount reserved by orders, in cents | | `used_count` | unsigned integer | no | 0 | Orders that reserved budget | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `starts_at` | datetime | no | - | Start of the campaign | | `ends_at` | datetime | yes | null | End of the campaign, null when it has none | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | `starts_at` has no default, so pass it when you create a campaign. Shopper updates `spent_amount` and `used_count` when it reserves and releases budget; leave them out of your own writes. The amounts follow the rules of [Money](/3.x/money). The `sh_discounts` table has a nullable `campaign_id` column, a foreign key to `sh_campaigns`. A discount belongs to one campaign at most. ### CampaignBudgetMovement Table [#campaignbudgetmovement-table] The `sh_campaign_budget_movements` table holds one row per reservation or release: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `campaign_id` | bigint | no | - | Foreign key to the campaign, movements are deleted with it | | `order_id` | bigint | yes | null | Foreign key to the order, set to null when the order is deleted | | `direction` | string | no | `reserve` | `reserve` or `release`, cast to `CampaignBudgetDirection` | | `amount` | bigint | no | - | Cents reserved (positive) or released (negative) | | `balance_after` | unsigned bigint | no | - | `spent_amount` of the campaign after the movement, in cents | | `actor` | string | yes | null | What released the budget, see [Budget Movements](#budget-movements) | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A unique key on `campaign_id`, `order_id` and `direction` allows one reservation and one release per campaign and order. ### Relationships [#relationships] `discounts()` returns the discounts of a campaign, a `HasMany` on `campaign_id`. The `Shopper\Core\Models\Discount` model has the inverse `campaign()` relationship, and a budget movement has `campaign()` too: ```php use Shopper\Core\Models\Campaign; use Shopper\Core\Models\Discount; $summerSale = Campaign::query()->withCount('discounts')->where('name', 'Summer Sale 2026')->firstOrFail(); $summerSale->discounts_count; Discount::query()->where('code', 'SUMMER20')->first()->campaign?->name; ``` A campaign has no relationship to its budget movements, and a movement has none to its order. Query `CampaignBudgetMovement` by `campaign_id` or `order_id` instead, as shown in [Budget Movements](#budget-movements). ### Methods [#methods] The model has no query scope besides `wherePublicId()`. Two methods and one attribute read its budget and dates: | Member | Returns | |--------|---------| | `hasReachedBudget()` | `true` when a cap of the budget type is reached: `spent_amount` is at or above `budget_amount`, or `used_count` is at or above `budget_count` | | `canAbsorb(int $spend)` | `true` when `$spend` more cents fit under the spend cap, always `true` for a campaign without one | | `status` | The `CampaignStatus` of the campaign, computed when you read it | ## Campaign Status [#campaign-status] The `status` attribute is not stored. Shopper computes it from the other columns each time you read it and returns a `Shopper\Core\Enum\CampaignStatus` case. The cases are checked in the order of this table, and the first that matches wins: | Case | Value | Admin label | When | |------|-------|-------------|------| | `Draft` | `draft` | Draft | The campaign is not saved yet | | `Disabled` | `disabled` | Disabled | `is_active` is `false` | | `Expired` | `expired` | Expired | `ends_at` is in the past | | `BudgetExhausted` | `budget_exhausted` | Budget exhausted | `hasReachedBudget()` returns `true` | | `Scheduled` | `scheduled` | Scheduled | `starts_at` is in the future | | `Active` | `active` | Active | None of the above | A disabled campaign stays Disabled after its end date, and an expired campaign shows as Expired even when its budget is used up. Since the status is computed in PHP, a query cannot filter on it: filter on `is_active`, `starts_at` and `ends_at`, which share an index, as shown in [Listing Running Campaigns](#listing-running-campaigns). The status drives the badges of the admin panel. The cart reads the budget and the currency of a campaign, as described in [Campaigns and Discounts](#campaigns-and-discounts), and does not read `is_active`, `starts_at` or `ends_at`: each discount applies according to its own active flag and [dates](/3.x/discounts#dates). ## Budgets [#budgets] The `budget_type` column decides which caps a campaign enforces. It is cast to the `Shopper\Core\Enum\CampaignBudgetType` enum: | Case | Value | Admin label | Caps | |------|-------|-------------|------| | `None` | `none` | No budget | None. The campaign still counts the amount and the orders | | `Spend` | `spend` | Spend cap | `budget_amount` | | `Count` | `count` | Usage cap | `budget_count` | | `SpendAndCount` | `spend_and_count` | Spend and usage cap | Both, and the first one reached stops the campaign | `hasSpendCap()` and `hasCountCap()` on the enum tell which caps a type has. A cap whose column is null is not enforced, so a `Spend` campaign without a `budget_amount` has no limit. The admin form requires the column of each cap of the selected type and sets the other one to null when it saves. The spend cap is the total discount the campaign gives, in cents of its currency: a `budget_amount` of `500000` stops a USD campaign after $5,000.00 of discounts. Each order adds the amount its campaign discounts took off to `spent_amount`. The usage cap counts orders. An order that uses two discounts of the same campaign, such as `SUMMER20` and the automatic sandals discount, adds one to `used_count`. ### Reserving and Releasing Budget [#reserving-and-releasing-budget] When a cart becomes an order, Shopper reserves the budget with `Shopper\Core\Actions\ReserveCampaignBudget`: one reservation per campaign and per order, for the sum of the campaign's discounts on that order. The update only goes through while the reservation fits under the caps, so two checkouts that race for the end of a budget cannot both pass. The one that no longer fits throws the [Budget Exceeded Exception](#budget-exceeded-exception) and its order is not created. `Shopper\Core\Actions\ReleaseCampaignBudget` gives the budget of an order back. Shopper calls it when an order is cancelled, and when a settled refund leaves the payment of an order fully refunded, through `PaymentProcessingService::refund()` or a refund webhook ([Refunding a Payment](/3.x/payments#refunding-a-payment)). A partial refund keeps the reservation, and a pending refund releases nothing until the provider confirms it. A refund the provider reports as failed after the release does not reserve the budget again. The release subtracts the exact amount reserved for the order and one use, without going below zero, and records a release movement. A second release for the same order does nothing, so a retried webhook cannot give the budget back twice. | Action | Method | What it does | |--------|--------|--------------| | `ReserveCampaignBudget` | `execute(Campaign $campaign, int $spend, ?int $orderId = null, ?string $actor = null, bool $overdraw = false)` | Adds `$spend` cents and one use, records a reserve movement, and throws `CampaignBudgetExceededException` when a cap would be passed | | `ReleaseCampaignBudget` | `execute(Campaign $campaign, int $orderId, ?string $actor = null)` | Gives one campaign back what it reserved for the order | | `ReleaseCampaignBudget` | `releaseOrder(int $orderId, ?string $actor = null)` | Gives back the budget of every campaign that reserved for the order | When the payment of a cart was already collected by the payment provider, the checkout honors the discounts the customer paid with. It reserves with `overdraw: true`, which skips the caps, so `spent_amount` and `used_count` can end above `budget_amount` and `budget_count`. ## Budget Movements [#budget-movements] Each reservation and release adds a `CampaignBudgetMovement` row, so the movements of a campaign tell which order used how much of its budget and when it came back. The `direction` column is cast to the `Shopper\Core\Enum\CampaignBudgetDirection` enum: | Case | Value | `amount` | |------|-------|----------| | `Reserve` | `reserve` | Positive, the cents the order reserved | | `Release` | `release` | Negative, the cents given back | `actor` records what released the budget: `order-cancelled` for a cancellation and `order-refunded` for a full refund. Reservations made by the checkout have no actor. When you call the actions yourself, pass your own actor, as shown in [Releasing Budget by Hand](#releasing-budget-by-hand). To show the history of a campaign, query the movements by `campaign_id`: ```php use Shopper\Core\Enum\CampaignBudgetDirection; use Shopper\Core\Models\CampaignBudgetMovement; $history = CampaignBudgetMovement::query() ->where('campaign_id', $summerSale->id) ->latest('id') ->get(); $cancelledOrders = CampaignBudgetMovement::query() ->where('campaign_id', $summerSale->id) ->where('direction', CampaignBudgetDirection::Release->value) ->where('actor', 'order-cancelled') ->count(); ``` Deleting a campaign deletes its budget movements and sets `campaign_id` to null on its discounts, which then apply without a shared budget. To end a campaign that has run and keep its history, turn `is_active` off and deactivate its discounts. ## Budget Exceeded Exception [#budget-exceeded-exception] `Shopper\Core\Exceptions\CampaignBudgetExceededException` extends `RuntimeException`. `ReserveCampaignBudget` throws it when a reservation does not fit under a cap. The checkout prices the cart again just before it creates the order, unless a provider payment session holds the total, and drops a discount whose campaign has already run out, so the exception only reaches a checkout that lost a race: the cart was priced while the budget still had room, and another order took that room first. Its message names the campaign: ```text The campaign "Summer Sale 2026" has reached its budget and can no longer be applied. ``` The order is not created and the cart keeps the discount until it is priced again. The Store API catches the exception, releases the payment session of the cart, prices the cart again so the discount drops, and answers with the `promotion_budget_reached` error described in [From a Storefront](#from-a-storefront). A checkout of your own that calls `CreateOrderFromCartAction` does the same, with a message that does not show the campaign name: ```php title="app/Http/Controllers/CheckoutController.php" execute($cart); } catch (CampaignBudgetExceededException) { $cartManager->releasePaymentSession($cart); $cartManager->calculate($cart->unsetRelations()); return back()->withErrors([ 'promotion' => __('shopper-cart::messages.discount.campaign_budget_reached'), ]); } return to_route('orders.confirmation', $order); } } ``` The translation reads "This promotion is no longer available." The [Cart](/3.x/cart#order-conversion) page covers the other checks of the checkout. ## Campaigns and Discounts [#campaigns-and-discounts] Codes and automatic discounts can both join a campaign through their `campaign_id`. On top of the discount's own rules, described in [Discount Eligibility](/3.x/discounts#discount-eligibility), the cart checks two things on its campaign: - The currency: the discount applies only to carts in the currency of the campaign. - The budget: the discount stops applying once `hasReachedBudget()` returns `true`. A discount whose amount does not fit in the rest of the spend budget is suppressed, never applied in part. The discounts of one campaign on the same cart share what is left: Shopper applies them in the order described in [Priority and Combination](/3.x/discounts#priority-and-combination), keeps a running total per campaign, and suppresses each discount that would pass the cap. A suppressed discount stays on the cart with an amount of 0 and does not count against `config('shopper.cart.max_promotions')`, so the next discount can take its place. The admin panel locks the campaign of a discount once the discount has been used, so that the orders it was used on stay counted against the campaign that reserved their budget. Moving a used discount from your own code breaks that link: keep `campaign_id` unchanged once `total_use` is above 0. ## Configuration [#configuration] Campaigns are on by default. Their settings are the feature flag and the admin components; the model has no configuration key. ### Disabling Campaigns [#disabling-campaigns] If your store does not use campaigns, disable the feature in `config/shopper/features.php`: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'campaign' => FeatureState::Disabled, ]; ``` The campaign pages are no longer registered and the Campaigns item leaves the Sales group of the sidebar. The flag only changes the admin panel: the models, the cart checks and the budget reservations stay in place, so a discount already attached to a campaign keeps its budget. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Components [#components] The campaigns section of the admin panel is made of three pages. To replace any of them with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish campaign ``` The command creates `config/shopper/components/campaign.php`: ```php title="config/shopper/components/campaign.php" use Shopper\Livewire; return [ 'pages' => [ 'campaign-index' => Livewire\Pages\Campaign\Index::class, 'campaign-create' => Livewire\Pages\Campaign\Create::class, 'campaign-edit' => Livewire\Pages\Campaign\Edit::class, ], ]; ``` The create and edit pages convert the spend cap to cents, require the columns of the selected caps and never write `spent_amount` or `used_count`. A replacement page must do the same. The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below work with the core models directly, from a seeder, a command or the controllers of a storefront. ### Creating a Campaign [#creating-a-campaign] Create the campaign with its currency, its caps in cents and its dates: ```php use Shopper\Core\Enum\CampaignBudgetType; use Shopper\Core\Models\Campaign; $summerSale = Campaign::query()->create([ 'name' => 'Summer Sale 2026', 'currency_code' => shopper_currency(), 'budget_type' => CampaignBudgetType::SpendAndCount, 'budget_amount' => 500000, 'budget_count' => 1000, 'starts_at' => '2026-06-21 00:00:00', 'ends_at' => '2026-08-31 23:59:59', ]); ``` `shopper_currency()` returns the code of the store default currency. A campaign in another currency only applies its discounts to carts in that currency. ### Attaching Discounts [#attaching-discounts] Attach a discount before it is used, from the discount side of the relationship: ```php use Shopper\Core\Models\Discount; $discount = Discount::query()->where('code', 'SUMMER20')->firstOrFail(); $discount->campaign()->associate($summerSale)->save(); ``` To take a discount out of its campaign before its first use, call `$discount->campaign()->dissociate()->save()`. ### Listing Running Campaigns [#listing-running-campaigns] A storefront banner shows the campaigns that are running. Filter on the indexed columns, then drop the campaigns whose budget is used up: ```php title="app/Http/Controllers/HomeController.php" addMinutes(10), function () { return Campaign::query() ->where('is_active', true) ->where('starts_at', '<=', now()) ->where(fn (Builder $query) => $query->whereNull('ends_at')->orWhere('ends_at', '>', now())) ->get() ->reject(fn (Campaign $campaign) => $campaign->hasReachedBudget()); }); return view('home', ['campaigns' => $campaigns]); } } ``` To show how many orders a campaign with a usage cap still accepts, subtract `used_count` from `budget_count`. An overdraw can push `used_count` above the cap, so floor the result at zero: ```blade @if ($campaign->budget_type->hasCountCap())

    Only {{ max(0, $campaign->budget_count - $campaign->used_count) }} orders left at {{ $campaign->name }} prices.

    @endif ``` [Events](#events) shows how to clear the cache when the budget moves. ### Releasing Budget by Hand [#releasing-budget-by-hand] Shopper releases budget when an order is cancelled through `OrderCancelled` and when its payment is fully refunded. When your code voids an order another way, release its budget yourself and name the actor: ```php use Shopper\Core\Actions\ReleaseCampaignBudget; resolve(ReleaseCampaignBudget::class)->releaseOrder($order->id, actor: 'support'); ``` The actor lands in the `actor` column of the release movement. Calling it for an order that was already released does nothing. ## Events [#events] Shopper dispatches no campaign event: nothing fires when a campaign is created, reaches its budget or gets budget back, as noted in [Cart and Discount Events](/3.x/events#cart-and-discount-events). Shopper listens to `OrderCancelled` with `Shopper\Core\Listeners\Orders\ReleaseCampaignBudgetListener`, which runs on the default queue ([Listeners Shopper Registers](/3.x/events#listeners-shopper-registers)), so the budget of a cancelled order comes back once a queue worker runs the listener. To react to budget changes, listen to the Eloquent `created` event of `CampaignBudgetMovement`. The reservation updates the campaign row with a query, so the `updated` event of `Campaign` does not fire when budget is reserved: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\CampaignBudgetMovement; public function boot(): void { CampaignBudgetMovement::created(fn () => Cache::forget('storefront.campaigns')); } ``` The movement is created inside the checkout transaction. The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks four permissions of the `campaigns` resource, in the Sales group: | Permission | Allows | |------------|--------| | `campaigns.browse` | Opening the campaigns page and seeing the Campaigns sidebar item | | `campaigns.create` | Opening the form for a new campaign and saving it | | `campaigns.edit` | Opening the edit page and saving changes | | `campaigns.delete` | Deleting a campaign, from the list (one at a time or in bulk) or from its edit page | `campaigns.read` is seeded with the others, but the admin panel never checks it. Attaching a discount to a campaign happens in the discount form, under the discount permissions. The `campaigns` resource is new in 3.x: a store upgraded from 2.x must generate its permissions, as described in [Upgrading from 2.x](/3.x/acl#upgrading-from-2x). ## In the Admin [#in-the-admin] Merchants manage campaigns under Sales, Campaigns. The list shows each campaign with its name, status, budget use, number of attached promotions and dates, and filters by active state and budget type. The form has four sections: General (name, currency from the store currencies, active toggle), Budget (budget type, spend cap as a decimal amount, usage cap), Schedule (start date, end date on or after it) and Advanced (metadata). The currency locks once the campaign has reserved budget. The edit page adds a summary, a consumption bar for each cap and the list of attached promotions. A discount joins a campaign from the Campaign section of the discount form or from the add promotion wizard. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API has no campaign endpoint, and its responses never name a campaign. Campaigns show through the promotions of a cart: | Request | Campaign effect | |---------|-----------------| | `POST /store/carts/{cartId}/promotion` | A code whose campaign has run out, uses another currency or cannot absorb the discount is refused with a 422 error, code `promotion_not_applicable`. The response does not say why | | `GET /store/carts/{cartId}` | Each item of the `promotions` attribute has a `status`: `applied`, or `suppressed` with an `amount` of 0 when the discount applies nothing, for example because its campaign budget is used up | | `POST /store/carts/{cartId}/complete` | When another order took the last of the budget, a 422 error with code `promotion_budget_reached` on the `/data/attributes/promotion` pointer. The cart is priced again without the discount: show the new total and let the customer confirm | The `store` prefix is set by `SHOPPER_API_PREFIX`. The Store API [Cart](/3.x/store-api/cart#promotion-codes) guide covers promotion codes, and the [Errors](/3.x/store-api/errors#error-codes) page lists every error code. # FedEx (/3.x/carriers/fedex) The `shopper/fedex` package connects a Shopper store to the FedEx APIs. A carrier that uses it quotes live FedEx rates at checkout, computed from the shipment origin, the customer address and the packages, and Shopper refreshes the tracking of every FedEx package from the FedEx tracking API. The package registers the `fedex` driver on the shipping manager of `shopper/shipping`. The manager, the carrier model and the rate service are described on the [Carriers](/3.x/carriers) page. This page covers what is specific to FedEx. Shopper also ships drivers for UPS (`shopper/ups`) and USPS (`shopper/usps`); each section below says where they work differently. ## Installation [#installation] Install the package with Composer: ```bash composer require shopper/fedex ``` Laravel discovers `Shopper\FedEx\FedExServiceProvider`. The provider merges the package configuration under `shopper.fedex` and registers the `fedex` driver with `Shipping::extend()`, built from that configuration. The driver reads its values from environment variables, so you only publish the file to change how a value is read: ```bash php artisan vendor:publish --tag=shopper-fedex-config ``` This creates `config/shopper/fedex.php`. ## Configuration [#configuration] Every key of the file comes from an environment variable: | Key | Environment variable | Default | Description | |-----|----------------------|---------|-------------| | `enabled` | `SHIPPING_FEDEX_ENABLED` | `false` | Lists the driver in `Shipping::configuredDrivers()` | | `sandbox` | `SHIPPING_SANDBOX` | `false` | Sends the requests to `https://apis-sandbox.fedex.com` instead of `https://apis.fedex.com` | | `client_id` | `FEDEX_CLIENT_ID` | `null` | API key of your FedEx project | | `client_secret` | `FEDEX_CLIENT_SECRET` | `null` | Secret key of your FedEx project | | `account_number` | `FEDEX_ACCOUNT_NUMBER` | `null` | FedEx account the rates are quoted against | Add the values to your `.env` file: ```dotenv SHIPPING_SANDBOX=true FEDEX_CLIENT_ID=your-api-key FEDEX_CLIENT_SECRET=your-secret-key FEDEX_ACCOUNT_NUMBER=your-account-number ``` The driver is ready once `client_id`, `client_secret` and `account_number` are all filled in: its `isConfigured()` method then returns `true`, carriers that use it quote FedEx rates, the admin panel stops showing it as "Not configured" and the tracking sync picks up its packages. The `enabled` key takes no part in that check. Only `Shipping::configuredDrivers()` reads it, as described in [Driver Configuration](/3.x/carriers#driver-configuration), so set it to `true` for code that lists the configured drivers. To stop FedEx from quoting, disable the carrier or remove a credential. `SHIPPING_SANDBOX` is shared by the FedEx, UPS and USPS drivers: one variable switches all three. To run FedEx against the sandbox while another driver stays in production, publish the file and set its `sandbox` key to `true`. ### Credentials [#credentials] FedEx issues the API key and the secret key in its Developer Portal, for a project you create there. The API key, your `client_id`, is shown on the project overview page. The secret key, your `client_secret`, is shown when the project is created, and you can regenerate it later. The project needs access to the rate and tracking APIs, the two the driver calls. The account number is the number of your FedEx shipping account. The driver exchanges the key and the secret for an OAuth access token with the client credentials grant, posting both in the form body to `/oauth/token`. It keeps the token in the default cache store until a minute before it expires, under a key that holds the client ID and the environment, and a cache lock stops two requests from asking for a token at the same time. The UPS driver sends its key and secret with HTTP Basic authentication and needs a fourth value, a user ID. The USPS driver needs no account number. ## Enabling the Carrier [#enabling-the-carrier] Installing the package adds no carrier to the store. A merchant creates one under Settings, Carriers: name it `FedEx` and pick FedEx as its driver. The name sets the slug, `fedex`, which must equal the driver code because the Store API finds the carrier of a live rate by that code, as [API-Connected Carrier](/3.x/carriers#api-connected-carrier) explains. Then add the carrier to each zone it serves, from the zone form, and keep it enabled. The [User Guide](/3.x/user-guide) walks through these screens. The driver select lists every installed driver, whatever its `enabled` key says: FedEx shows there once the package is installed, with a "Not configured" badge until the three credentials are filled in. Until then the carrier offers its shipping options in the zone, as a manual carrier does. Once the driver is configured, the carrier quotes FedEx rates and no longer reads those options, so a FedEx carrier needs no shipping option. ## Shipping Rates [#shipping-rates] The driver quotes a shipment with one call to the FedEx rate API, `POST /rate/v1/rates/quotes`. Shopper calls it through `CarrierRateService` when the Store API lists the shipping options of a cart, as described in [Calculating Shipping Rates](/3.x/carriers#calculating-shipping-rates). The Store API takes the origin from the [default inventory location](/3.x/locations#default-location), or the location with the lowest priority when none is the default, and needs its country and street address. It sends one package per cart, with the summed weight of the items and their largest dimensions, in the unit system of `shopper.shipping.units`. The request holds these values: | FedEx field | Value | |-------------|-------| | `accountNumber` | The `account_number` of the configuration | | `shipper`, `recipient` | The origin and destination: `street` and `street2` as street lines, `city`, `state` as the state or province code, `postalCode` and `country` | | `pickupType` | `DROPOFF_AT_FEDEX_LOCATION` | | `packagingType` | `YOUR_PACKAGING` | | `rateRequestType` | `ACCOUNT` and `LIST` | | `requestedPackageLineItems` | One line per package, in kilograms and centimeters rounded to two decimals | The driver converts a package measured in inches and pounds to centimeters and kilograms before sending it. FedEx answers with one entry per service, and each becomes a `ShippingRate`: | `ShippingRate` property | FedEx value | |-------------------------|-------------| | `serviceCode` | The service type, `serviceType` | | `serviceName` | The service name, or the service type when FedEx gives none | | `amount` | The `totalNetCharge` of the account rate, or of the first rate when FedEx returns no account rate, in cents | | `currency` | The currency of that rate, in uppercase | | `estimatedDays` | Not set | A currency without decimals keeps its amount as is, as described in [Zero-Decimal Currencies](/3.x/money#zero-decimal-currencies). A service without an amount, or with an amount of zero, is left out and logged as a `Discarded an unusable FedEx rate.` warning with the service type and the reason. The Store API leaves out the options priced in another currency than the cart and says so in its warnings, so the FedEx account currency must match the currency of the carts it quotes. Quotes are cached for `shopper.shipping.rates_cache_ttl` seconds, per driver, addresses and packages, as described in [Rate Caching](/3.x/carriers#rate-caching). The UPS driver also sends metric units and is the only one that returns transit days. The USPS driver sends pounds and inches and quotes retail prices in US dollars. ## Labels [#labels] The driver does not create shipments or buy labels at FedEx: its `supportsLabels()` method returns `false`, as do those of the UPS and USPS drivers. Buy the label from your FedEx account, then record the package on the order: the Create Shipping Label slide-over of the order page takes the FedEx carrier, the tracking number and the tracking URL, as described in [In the Admin](/3.x/fulfillment#in-the-admin). ## Tracking [#tracking] The driver supports tracking and no webhook, so Shopper asks FedEx for the tracking of each open package. The scheduled `shopper:shipments:sync-tracking` command queues a refresh every 30 minutes for each package of a FedEx carrier that has a tracking number and is neither Delivered nor Returned, as described in [Tracking Sync](/3.x/fulfillment#tracking-sync). Run it by hand to refresh the packages now: ```bash php artisan shopper:shipments:sync-tracking ``` The driver calls `POST /track/v1/trackingnumbers` with the detailed scans and turns each scan into a tracking event, with the FedEx description and a location made of the city, the state and the country of the scan. It reads the derived status code of the scan, or its event type when the scan has none: | FedEx code | Shipment status | |------------|-----------------| | `OC` | `ShipmentStatus::Pending` | | `PU` | `ShipmentStatus::PickedUp` | | `AR` | `ShipmentStatus::AtSortingCenter` | | `OD` | `ShipmentStatus::OutForDelivery` | | `DL` | `ShipmentStatus::Delivered` | | `DE`, `SE` | `ShipmentStatus::DeliveryFailed` | | `RS` | `ShipmentStatus::Returned` | | Any other code | `ShipmentStatus::InTransit` | When FedEx reports an actual delivery date without a delivery scan, the driver adds a Delivered event at that date. Each scan carries an external ID built from its time and event type, so a scan read twice is recorded once. A tracking number FedEx does not know is logged as a `The carrier has no record of this tracking number.` warning and the package stays as it is. Any other FedEx error fails the job, which retries after the delays of `shopper.shipping.tracking.backoff`. The UPS driver tracks its packages the same way. The USPS driver does not track. ## Errors [#errors] A failing FedEx call never hides the other carriers. Each request times out after 15 seconds, and a request that cannot connect is tried up to three times, 200 milliseconds apart. The driver throws a `Shopper\Shipping\Exceptions\ShippingException` when the connection still fails, when FedEx answers with an error, including a refused token request, or when the answer holds no usable rate. The message names the driver and the error FedEx returned, such as `API error from [fedex]: ...`, or the HTTP status when FedEx gives no message. `CarrierRateService` catches the exception, logs a `Shipping rates unavailable for carrier.` warning and reports the carrier as failing. The Store API turns it into a warning on the shipping options and answers `503` when the customer picks a FedEx option, as described in [Failing Carriers](/3.x/carriers#failing-carriers). ## Testing [#testing] Test the driver against the FedEx sandbox before the store quotes real shipments. ### Sandbox Mode [#sandbox-mode] Set `SHIPPING_SANDBOX=true` to send every request to `https://apis-sandbox.fedex.com`, with credentials the FedEx sandbox accepts. The access token is cached per environment, so a sandbox token is never sent to production. The quote cache key holds the driver, the addresses and the packages, without the environment. After you switch from the sandbox to production, run `php artisan cache:clear` or wait `shopper.shipping.rates_cache_ttl` seconds, or the Store API can serve a sandbox quote. ### Quoting a Test Shipment [#quoting-a-test-shipment] Call the driver directly to check the credentials without a cart or a carrier. This Artisan command asks for the rates of one package from a Los Angeles warehouse to a New York customer: ```php title="routes/console.php" use Illuminate\Support\Facades\Artisan; use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; use Shopper\Shipping\Facades\Shipping; Artisan::command('shipping:quote-fedex', function (): void { $rates = Shipping::driver('fedex')->calculateRates( from: new Address( firstName: '', lastName: 'Los Angeles Warehouse', street: '1200 S Alameda St', city: 'Los Angeles', postalCode: '90021', state: 'CA', country: 'US', ), to: new Address( firstName: 'Jane', lastName: 'Cooper', street: '350 Fifth Avenue', city: 'New York', postalCode: '10118', state: 'NY', country: 'US', ), packages: [ new Package(length: 30, width: 20, height: 15, weight: 2.5), ], ); foreach ($rates as $rate) { $this->line("{$rate->serviceCode}: {$rate->serviceName}, {$rate->formattedAmount()}"); } }); ``` Run `php artisan shipping:quote-fedex`. Each line is a FedEx service with its price. A `ShippingException` carries the FedEx error, for example a refused token when a credential is wrong. This call skips the quote cache, so it always reaches FedEx. ## Events [#events] The driver dispatches no event of its own. The tracking it reports is recorded through `RecordShipmentEventAction`, which dispatches the shipment events: `OrderShipmentEventRecorded` for each new scan, and `OrderShipmentDelivered`, `OrderShipmentDeliveryFailed` or `OrderShipmentReturned` when the package reaches that status. [Shipment Events](/3.x/events#shipment-events) lists their payloads. # Carriers (/3.x/carriers) A carrier is a company or a service that delivers orders: UPS, FedEx, a local courier, in-store pickup. Shopper stores shipping on two levels: the carrier itself, and its shipping options, the services a customer picks at checkout ("Standard", "Express") with a price in each zone. A carrier gets its rates in one of two ways. A manual carrier offers the options the merchant enters for each zone, at a fixed price. A carrier connected to a shipping driver asks the carrier's API for live rates, computed from the shipment origin, the destination address and the packages. The `shopper/shipping` package holds the driver manager, the manual driver, the rate service and the driver contract; the UPS, FedEx and USPS drivers ship as separate packages. The zones a carrier serves are described on the [Zones](/3.x/zones) page. Shipments, labels and tracking are on the [Fulfillment](/3.x/fulfillment) page. ## Models [#models] Shopper uses two models for shipping: | Model | Purpose | |-------|---------| | `Shopper\Core\Models\Carrier` | The carrier (UPS, FedEx, local delivery) and the driver that rates it | | `Shopper\Core\Models\CarrierOption` | A shipping option of a carrier in one zone, with its price | `Carrier` implements `Shopper\Core\Models\Contracts\Carrier` and uses the `HasPublicId`, `HasSlug` and `HasZones` traits. `CarrierOption` implements `Shopper\Core\Models\Contracts\CarrierOption` and uses `HasPublicId`. Neither model has a key in `config/shopper/models.php`, so you cannot swap them: add a relationship to them with `resolveRelationUsing()`, as shown in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). Both models carry a [public ID](/3.x/models#public-ids), and the morph map names them `carrier` and `carrier_option`. ## Database Schema [#database-schema] The two tables take the [table prefix](/3.x/configuration#database-table-prefix), so they are named `sh_carriers` and `sh_carrier_options` by default. ### Carrier Table [#carrier-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | auto | Public identifier (unique) | | `name` | string | no | - | Carrier name | | `slug` | string | yes | null | Unique identifier, such as `ups` or `local-delivery` | | `driver` | string | yes | null | Driver code: `manual`, `ups`, `fedex`, `usps` or a custom driver. `null` works as `manual` | | `link_url` | string | yes | null | Carrier website | | `description` | string | yes | null | Carrier description | | `shipping_amount` | integer | yes | null | An amount in cents kept for your own code. Shopper does not read it | | `is_enabled` | boolean | no | false | Whether the carrier quotes rates | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### CarrierOption Table [#carrieroption-table] | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | auto | Public identifier (unique), used as the service code of the option | | `name` | string | no | - | Option name, unique within a zone | | `description` | string(255) | yes | null | Option description | | `price` | integer | no | - | Price in cents, in the currency of the zone | | `is_enabled` | boolean | no | false | Whether the option is offered | | `carrier_id` | bigint | no | - | Foreign key to the carrier | | `zone_id` | bigint | no | - | Foreign key to the zone | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The foreign keys of `carrier_options` have no delete rule, so the database refuses to delete a carrier that still has shipping options: delete its options first. Orders point to a shipping option through `shipping_option_id` and shipments to a carrier through `carrier_id`; both are set to `null` when the option or the carrier is deleted. Carriers are attached to zones through the `zone_has_relations` table. ## Shipping Drivers [#shipping-drivers] Shopper rates carriers through drivers, the way Laravel sends mail through mailers. `Shopper\Shipping\ShippingManager` is a Laravel manager: it creates a driver the first time it is asked for it and reuses that instance. The `driver` column of a carrier names its driver. ### Available Drivers [#available-drivers] The manual driver ships with `shopper/shipping`. Each live driver is a separate Composer package that you install only for the carriers you use: | Driver | Code | Package | Rates | Tracking | |--------|------|---------|-------|----------| | Manual | `manual` | `shopper/shipping` | The shipping options of the zone | No | | UPS | `ups` | `shopper/ups` | Live, from the UPS API | Yes | | FedEx | `fedex` | `shopper/fedex` | Live, from the FedEx API | Yes | | USPS | `usps` | `shopper/usps` | Live, from the USPS API | No | Each driver has its own page with its installation, its credentials and its services: [UPS](/3.x/carriers/ups), [FedEx](/3.x/carriers/fedex) and [USPS](/3.x/carriers/usps). ### Driver Configuration [#driver-configuration] The shipping package merges its configuration under `shopper.shipping`. Publish it with the other Shopper configuration files to change a value: ```bash php artisan vendor:publish --tag=shopper-config ``` This creates `config/shopper/shipping.php`, with these keys: | Key | Environment variable | Default | Description | |-----|----------------------|---------|-------------| | `units` | `SHIPPING_UNITS` | `metric` | Unit system of the package the Store API builds from a cart: `metric` (cm, kg) or `imperial` (in, lb) | | `rates_cache_ttl` | `SHIPPING_RATES_CACHE_TTL` | `600` | Seconds a live quote stays cached. `0` calls the carrier API on every request | | `tracking.sync` | `SHIPPING_TRACKING_SYNC` | `true` | Schedules the tracking sync command every thirty minutes | | `tracking.queue` | `SHIPPING_TRACKING_QUEUE` | `null` | Queue of the tracking jobs. `null` uses the default queue | | `tracking.backoff` | | `[60, 300, 900]` | Seconds to wait before each retry of a tracking job | The credentials of a live driver live in the configuration file of its package, merged under `shopper.ups`, `shopper.fedex` or `shopper.usps` and published with the `shopper-ups-config`, `shopper-fedex-config` or `shopper-usps-config` tag. Shopper 2.x kept them in a `drivers` array of `config/shopper/shipping.php`; 3.x no longer reads that array. Add the credentials to your `.env` file: ```dotenv UPS_CLIENT_ID=your-client-id UPS_CLIENT_SECRET=your-client-secret UPS_USER_ID=your-user-id UPS_ACCOUNT_NUMBER=your-account-number SHIPPING_SANDBOX=true ``` A driver is configured when its `isConfigured()` method returns `true`, which the UPS, FedEx and USPS drivers do once every credential is filled in. That check decides everything: whether a carrier quotes live rates, whether the admin panel shows the driver as ready, whether its shipments are tracked and whether its webhook route answers. Each of their config files also has an `enabled` key (`SHIPPING_UPS_ENABLED`, `SHIPPING_FEDEX_ENABLED`, `SHIPPING_USPS_ENABLED`), which only `Shipping::configuredDrivers()` reads. To stop a carrier from quoting, disable the carrier. ### Using the Shipping Facade [#using-the-shipping-facade] The `Shipping` facade gives access to the shipping manager and to every registered driver: ```php use Shopper\Shipping\Facades\Shipping; $driver = Shipping::driver('ups'); $codes = Shipping::availableDrivers(); $enabled = Shipping::configuredDrivers(); $isReady = Shipping::isConfigured('fedex'); ``` `availableDrivers()` returns the codes of the manual driver and of every driver registered with `extend()`. `configuredDrivers()` returns the drivers keyed by code: the manual driver, and each driver whose `shopper.{code}.enabled` key is `true`. `isConfigured()` returns `false` for a code that no driver is registered under, where `driver()` throws an `InvalidArgumentException`. ### Carrier Driver Integration [#carrier-driver-integration] Shopper 2.x added `usesApiDriver()`, `getShippingDriver()` and `isDriverConfigured()` to the carrier model. In 3.x, the carrier only knows its driver code, and `Shopper\Shipping\Services\CarrierRateService` resolves the driver: ```php use Shopper\Core\Models\Carrier; use Shopper\Shipping\Services\CarrierRateService; $carrier = Carrier::findBySlug('ups'); $service = resolve(CarrierRateService::class); $driver = $service->resolveDriver($carrier); $isLive = $service->isDriverConfigured($carrier); $logo = $carrier->logo(); ``` `resolveDriver()` returns `null` for a carrier without a driver or with the `manual` driver. A carrier rates live when its driver is configured. Otherwise, including when its driver is missing credentials, it falls back to its shipping options in the zone, as a manual carrier does. `logo()` returns the logo URL of the carrier's driver; the manual driver returns the local delivery image of the admin panel. `logo()` calls the resolver bound to `shopper.carrier.logo` in the service container, and returns `null` without `shopper/shipping` installed. Every manual carrier shows the same image. To give some carriers their own logo, bind your resolver in the `boot()` method of a service provider and fall back to the driver logo for the others: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Core\Models\Carrier; use Shopper\Shipping\Facades\Shipping; public function boot(): void { $this->app->bind('shopper.carrier.logo', fn () => fn (Carrier $carrier): ?string => match ($carrier->slug) { 'city-courier' => asset('images/carriers/city-courier.svg'), 'store-pickup' => asset('images/carriers/store-pickup.svg'), default => Shipping::driver($carrier->driver ?? 'manual')->logo(), }); } ``` `CarrierRateService::getLogoUrl()` returns the same URL. The admin panel reads `logo()` in the carrier list, the zone shipping options, the order summary and the shipment details, so all of them show your image. The driver picker of the carrier form keeps the driver logos. ## Calculating Shipping Rates [#calculating-shipping-rates] `CarrierRateService` rates any carrier, manual or live, through the same methods. A rate request describes the shipment with three data objects from `Shopper\Shipping\DataTransferObjects`: the origin and destination `Address`, and the `Package` list. The country of an address is its ISO 3166-1 alpha-2 code, and a package is measured in centimeters and kilograms unless you pass `unit: 'imperial'`: ```php title="app/Http/Controllers/CheckoutShippingController.php" use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; use Shopper\Shipping\Services\CarrierRateService; $service = resolve(CarrierRateService::class); $from = new Address( firstName: '', lastName: 'Los Angeles Warehouse', street: '1200 S Alameda St', city: 'Los Angeles', postalCode: '90021', state: 'CA', country: 'US', ); $to = new Address( firstName: 'Jane', lastName: 'Cooper', street: '350 Fifth Avenue', city: 'New York', postalCode: '10118', state: 'NY', country: 'US', phone: '+1 212 736 3100', ); $packages = [ new Package(length: 30, width: 20, height: 15, weight: 2.5), ]; ``` `Address` also accepts `company`, `street2`, `phone` and `email`. ### Getting Rates for a Carrier [#getting-rates-for-a-carrier] `getRatesForCarrier()` rates one carrier. A carrier with a configured driver gets live rates from the carrier's API. Any other carrier returns its enabled shipping options in the zone you pass: ```php $rates = $service->getRatesForCarrier( carrier: $carrier, from: $from, to: $to, packages: $packages, zone: $zone, ); ``` Pass the zone for a manual carrier: without one, the method returns every enabled option of the carrier, from every zone, and labels each rate with the store default currency, even when its zone uses another one. This method calls the carrier API directly, without the cache and the per-carrier isolation of the zone methods, so an API error reaches your code as an exception. ### Getting Rates for a Zone [#getting-rates-for-a-zone] `getRatesForZone()` collects the rates of every enabled carrier attached to the zone. `getZoneRates()` does the same and returns a `ZoneRateResult`, with the rates in `$result->rates` and the names of the carriers whose API failed in `$result->failedCarriers`: ```php $rates = $service->getRatesForZone( zone: $zone, from: $from, to: $to, packages: $packages, ); $result = $service->getZoneRates( zone: $zone, from: null, to: null, packages: $packages, ); ``` `getZoneRates()` accepts `null` addresses. Manual rates only need the zone, while live carriers are skipped until both addresses are known, so a checkout can show the manual options before the customer enters an address. ### ShippingRate DTO [#shippingrate-dto] Both methods return a collection of `Shopper\Shipping\DataTransferObjects\ShippingRate` objects. Their values depend on where the rate comes from: | Property | Type | Manual rate | Live rate | |----------|------|-------------|-----------| | `serviceCode` | `string\|int` | Public ID of the shipping option | Service code of the carrier, such as `03` for UPS Ground | | `serviceName` | `string` | Name of the option | Service name returned by the carrier | | `amount` | `int` | Price of the option, in cents | Quoted price, in cents | | `currency` | `string` | Currency of the zone, or the store default currency when no zone is given | Currency of the quote | | `carrierCode` | `string` | Slug of the carrier, or its name when it has no slug | Code the driver sets, `ups` for the UPS driver | | `estimatedDays` | `?string` | `null` | Transit days, when the carrier returns them | | `estimatedDelivery` | `?string` | `null` | Delivery date, when the carrier returns it | | `priceType` | `string` | `flat` | `calculated` | ```php foreach ($rates as $rate) { echo $rate->serviceName.': '.$rate->formattedAmount(); } ``` `formattedAmount()` formats the amount with `shopper_money_format()`, described on the [Money](/3.x/money) page, and `toArray()` returns the properties with snake_case keys. The Store API identifies a rate as `{carrierCode}:{serviceCode}`, such as `local-delivery:01J8Z3K2YB6Q9M4T5N7V0W1X2C` or `ups:03`. ### Rate Caching [#rate-caching] Carrier APIs are slow and rate-limited, so `getZoneRates()` keeps each live quote in the default cache store for `config('shopper.shipping.rates_cache_ttl')` seconds. The cache key holds the driver code and a hash of the addresses and packages, so a new address or a change in the cart produces a new quote. Manual rates are read from the database on every request, a failed quote is never cached, and `getRatesForCarrier()` does not use the cache. ## Failing Carriers [#failing-carriers] `getZoneRates()` isolates each carrier. When a carrier API times out, answers with an error or returns a response the driver cannot read, the service catches the exception, logs a `Shipping rates unavailable for carrier.` warning with the carrier name, its driver and the error message, adds the carrier name to `failedCarriers`, and returns the rates of the other carriers. An outage at UPS never hides the local delivery options: ```php $result = $service->getZoneRates(zone: $zone, from: $from, to: $to, packages: $packages); $warnings = array_map( fn (string $carrier): string => "Rates from {$carrier} are temporarily unavailable.", $result->failedCarriers, ); return view('checkout.shipping', [ 'rates' => $result->rates, 'warnings' => $warnings, ]); ``` The Store API turns failed carriers into warnings, and answers `503` when the customer picks an option of a carrier that is failing, as described in [From a Storefront](#from-a-storefront). The isolation covers the API call only. A carrier whose `driver` names a code that no driver is registered under, for example after its package was removed, throws an `InvalidArgumentException` that stops the quote of the whole zone. Switch those carriers to the `manual` driver before you remove a driver package. ## Custom Shipping Drivers [#custom-shipping-drivers] A custom driver connects a carrier that has no driver package, such as DHL, Canada Post, Colissimo or a regional courier. Once registered, it appears in the carrier form of the admin panel and rates carriers like the built-in drivers. ### Creating a Driver [#creating-a-driver] A driver implements the `Shopper\Shipping\Contracts\ShippingDriver` contract. Extend the abstract `Shopper\Shipping\Drivers\Driver` class, which implements the optional methods, and write the four required ones. `calculateRates()` returns amounts in cents, so convert the decimal prices of the carrier as described in [Converting Input](/3.x/money#converting-input): ```php title="app/Shipping/DhlDriver.php" apiKey) && filled($this->accountNumber); } public function supportsLabels(): bool { return false; } public function calculateRates(Address $from, Address $to, array $packages): Collection { $response = Http::withHeaders(['DHL-API-Key' => $this->apiKey]) ->timeout(10) ->post($this->apiUrl().'/rates', [ 'accountNumber' => $this->accountNumber, 'originAddress' => $this->formatAddress($from), 'destinationAddress' => $this->formatAddress($to), 'packages' => $this->formatPackages($this->normalizePackages($packages)), ]); if ($response->failed()) { throw ShippingException::apiError('dhl', $response->json('detail', 'HTTP '.$response->status())); } return collect($response->json('products', []))->map(function (array $product): ShippingRate { $currency = strtoupper($product['priceCurrency']); return new ShippingRate( serviceCode: $product['productCode'], serviceName: $product['productName'], amount: is_no_division_currency($currency) ? (int) round($product['totalPrice']) : (int) round($product['totalPrice'] * 100), currency: $currency, carrierCode: 'dhl', estimatedDays: $product['deliveryCapabilities']['estimatedDeliveryDays'] ?? null, ); }); } private function apiUrl(): string { return $this->sandbox ? 'https://express.api.dhl.com/mydhlapi/test' : 'https://express.api.dhl.com/mydhlapi'; } private function formatAddress(Address $address): array { return [ 'postalCode' => $address->postalCode, 'cityName' => $address->city, 'countryCode' => $address->country, ]; } private function formatPackages(array $packages): array { return array_map(fn (Package $package): array => [ 'weight' => $package->weight, 'dimensions' => [ 'length' => $package->length, 'width' => $package->width, 'height' => $package->height, ], ], $packages); } } ``` Throw an exception when the carrier cannot quote: the zone methods catch it and report the carrier as failing. `Shopper\Shipping\Exceptions\ShippingException` has four named constructors: | Method | Message | |--------|---------| | `ShippingException::notConfigured($driver)` | The driver is missing its credentials | | `ShippingException::notSupported($method, $driver)` | The driver does not implement the method | | `ShippingException::apiError($driver, $message)` | The carrier API answered with an error | | `ShippingException::invalidResponse($driver)` | The carrier API answered with a response the driver cannot read | Carriers that authenticate with OAuth can use the `Shopper\Shipping\Concerns\InteractsWithCarrierApi` trait, as the UPS, FedEx and USPS drivers do. `cachedToken($key, $request)` keeps the token returned by the `$request` closure in the default cache store until 60 seconds before it expires, behind a cache lock so that concurrent requests fetch one token. `readToken($response)` reads `access_token` and `expires_in` (3600 seconds when absent) from a token response and throws `apiError()` or `invalidResponse()` when it cannot, and `carrierMessage($response)` extracts the error message of a failed response. ### The Driver Contract [#the-driver-contract] The `ShippingDriver` contract declares these methods: | Method | Returns | Description | |--------|---------|-------------| | `code()` | `string` | Driver code, the value of the carrier `driver` column | | `name()` | `string` | Name shown in the admin panel | | `logo()` | `?string` | URL of the carrier logo | | `isConfigured()` | `bool` | Whether the credentials are set | | `supportsRealTimeRates()` | `bool` | Whether the driver quotes live rates | | `supportsLabels()` | `bool` | Whether the driver creates shipping labels | | `supportsTracking()` | `bool` | Whether `track()` works | | `supportsWebhooks()` | `bool` | Whether `handleWebhook()` works | | `calculateRates($from, $to, $packages)` | `Collection` | The `ShippingRate` objects for the shipment | | `createShipment($from, $to, $packages, $serviceCode)` | `Shipment` | Books a shipment and returns its label | | `track($trackingNumber)` | `TrackingInfo` | The tracking of a package | | `handleWebhook($request)` | `?TrackingInfo` | The tracking update a carrier pushes | The abstract `Driver` class returns `null` from `logo()`, `true` from `supportsRealTimeRates()` and `supportsLabels()`, and `false` from `supportsTracking()` and `supportsWebhooks()`. Its `createShipment()`, `track()` and `handleWebhook()` throw `ShippingException::notSupported()`. Shopper calls `code()`, `name()`, `logo()`, `isConfigured()` and `calculateRates()`, plus the tracking and webhook methods described in [Driver Capabilities](#driver-capabilities). It does not call `supportsRealTimeRates()`, `supportsLabels()` or `createShipment()`: the admin panel records labels and tracking numbers by hand, as described on the [Fulfillment](/3.x/fulfillment) page. ### Registering the Driver [#registering-the-driver] Register the driver in a service provider with the `extend()` method of the `Shipping` facade. The closure returns the driver, built from its configuration: ```php title="app/Providers/AppServiceProvider.php" use App\Shipping\DhlDriver; use Shopper\Shipping\Facades\Shipping; public function boot(): void { Shipping::extend('dhl', fn (): DhlDriver => new DhlDriver( apiKey: config('shopper.dhl.api_key'), accountNumber: config('shopper.dhl.account_number'), sandbox: (bool) config('shopper.dhl.sandbox', false), )); } ``` Register the driver under the code its `code()` method returns, since carriers store that code in their `driver` column. The manager calls the closure the first time the driver is used. Once registered, the driver appears in the Driver field of the carrier form, with a "Not configured" badge while `isConfigured()` returns `false`. ### Adding Configuration [#adding-configuration] Keep the settings of the driver in `config/shopper/dhl.php`, which Laravel loads under the `shopper.dhl` key, the way the driver packages merge theirs under `shopper.ups` and `shopper.fedex`: ```php title="config/shopper/dhl.php" env('SHIPPING_DHL_ENABLED', false), 'sandbox' => env('SHIPPING_SANDBOX', false), 'api_key' => env('DHL_API_KEY'), 'account_number' => env('DHL_ACCOUNT_NUMBER'), ]; ``` The `enabled` key follows the driver packages, so that `Shipping::configuredDrivers()` lists the driver once it is `true`. ### Driver Capabilities [#driver-capabilities] The abstract `Driver` class provides `normalizePackages()`, which converts packages between metric and imperial units. Pass `'metric'` (the default) for a carrier that expects centimeters and kilograms, or `'imperial'` for one that expects inches and pounds: ```php public function calculateRates(Address $from, Address $to, array $packages): Collection { $packages = $this->normalizePackages($packages, 'imperial'); return $this->quote($from, $to, $packages); } ``` A driver reports tracking in one of two ways, both described in [Tracking Events](/3.x/fulfillment#tracking-events): - Polling: return `true` from `supportsTracking()` and implement `track()`. The `shopper:shipments:sync-tracking` command, scheduled every thirty minutes while `tracking.sync` is on, queues a tracking job for each open shipment that has a tracking number and whose carrier driver is configured, supports tracking and does not support webhooks. - Webhooks: return `true` from `supportsWebhooks()` and implement `handleWebhook()`. The Store API passes each `POST /store/webhooks/shipping/{driver}` request to it. The route is public, so `handleWebhook()` must verify that the request comes from the carrier (a signature or a shared secret) and throw when the check fails; the route then answers `400`. It returns a `TrackingInfo` to record, or `null` for a notification that carries nothing to record. The route answers `404` for a driver that is not registered, not configured, or does not support webhooks. ## Relationships [#relationships] A carrier has many shipping options and belongs to many zones. A shipping option belongs to one carrier and one zone. ### Carrier Options [#carrier-options] `options()` returns every shipping option of the carrier, in every zone: ```php use Shopper\Core\Models\Carrier; $carrier = Carrier::findBySlug('local-delivery'); $carrier->options; $carrier->options()->enabled()->get(); $carrier->options()->create([ 'name' => 'Express (2 hours)', 'price' => 1500, 'zone_id' => $zone->id, 'is_enabled' => true, ]); ``` ### Zones [#zones] The `HasZones` trait gives the carrier a `zones()` relationship, stored in `zone_has_relations`. A carrier quotes in a zone only when it is attached to it, and a zone lists its carriers and its shipping options: ```php $carrier->zones()->attach($zone); $carrier->zones; $zone->carriers; $zone->shippingOptions; ``` The [Zones](/3.x/zones) page describes the other relationships of a zone. ### Zone (CarrierOption) [#zone-carrieroption] `zone()` returns the zone of the option. Query the options of a zone directly: ```php use Shopper\Core\Models\CarrierOption; $option->zone; CarrierOption::query() ->where('zone_id', $zone->id) ->enabled() ->get(); ``` ### Carrier (CarrierOption) [#carrier-carrieroption] `carrier()` returns the carrier of the option: ```php $option->carrier; ``` ## Query Scopes [#query-scopes] Both models have an `enabled` scope, which keeps the rows where `is_enabled` is `true`: ```php use Shopper\Core\Models\Carrier; use Shopper\Core\Models\CarrierOption; Carrier::query()->enabled()->get(); CarrierOption::query()->enabled()->get(); ``` ## Price Handling [#price-handling] The price of a shipping option is stored in cents, in the currency of its zone. Format it with that currency: ```php use Shopper\Core\Models\CarrierOption; $option = CarrierOption::query()->create([ 'name' => 'Standard Shipping', 'price' => 1000, 'zone_id' => $zone->id, 'carrier_id' => $carrier->id, 'is_enabled' => true, ]); shopper_money_format($option->price, $option->zone->currency_code); ``` A zone has one currency, so a store that sells in euros and in dollars enters its prices in each zone. The [Money](/3.x/money) page covers cents and zero-decimal currencies. ## Creating Carriers [#creating-carriers] A carrier needs a name, a driver, the zones it serves and, for a manual carrier, a shipping option in each of those zones. Setting `slug` runs the value through `Str::slug()` and appends `-1`, `-2` when it is taken, and `Carrier::findBySlug()` returns the carrier of a slug. ### Manual Carrier [#manual-carrier] A manual carrier offers the options you create for each zone, at the price you set: ```php use Shopper\Core\Models\Carrier; $carrier = Carrier::query()->create([ 'name' => 'Local Delivery', 'slug' => 'local-delivery', 'driver' => 'manual', 'description' => 'Same-day delivery within city limits', 'is_enabled' => true, ]); $carrier->zones()->attach($localZone); $carrier->options()->createMany([ [ 'name' => 'Standard', 'price' => 500, 'zone_id' => $localZone->id, 'is_enabled' => true, ], [ 'name' => 'Express (2 hours)', 'price' => 1500, 'zone_id' => $localZone->id, 'is_enabled' => true, ], ]); ``` ### API-Connected Carrier [#api-connected-carrier] A carrier with a live driver needs no shipping option: its rates come from the carrier's API once the driver is configured. Give it the driver code as its slug, because the Store API finds the carrier of a live rate by the driver code the rate carries. In the admin panel the slug follows the name, so name the carrier after the code, such as `UPS` for `ups`: ```php use Shopper\Core\Models\Carrier; $carrier = Carrier::query()->create([ 'name' => 'UPS', 'slug' => 'ups', 'driver' => 'ups', 'link_url' => 'https://www.ups.com', 'is_enabled' => true, ]); $carrier->zones()->attach($domesticZone); ``` The shipping options of such a carrier are offered only while its driver is not configured. ### Free Shipping Option [#free-shipping-option] Free shipping is a shipping option with a price of `0`: ```php use Shopper\Core\Models\Carrier; $freeShipping = Carrier::query()->create([ 'name' => 'Free Shipping', 'slug' => 'free-shipping', 'driver' => 'manual', 'description' => 'Free standard shipping', 'is_enabled' => true, ]); $freeShipping->zones()->attach($domesticZone); $freeShipping->options()->create([ 'name' => 'Free Standard Delivery', 'price' => 0, 'zone_id' => $domesticZone->id, 'is_enabled' => true, ]); ``` Shopper offers the option to every cart of the zone: it has no minimum order amount. ## Retrieving Carriers [#retrieving-carriers] Load the enabled options with their carrier, in one query, to list the manual shipping choices of a zone: ```php use Shopper\Core\Models\Carrier; use Shopper\Core\Models\CarrierOption; $carriers = Carrier::query() ->enabled() ->with(['options' => fn ($query) => $query->enabled()]) ->get(); $carrier = Carrier::findBySlug('fedex'); $options = CarrierOption::query() ->where('zone_id', $zone->id) ->enabled() ->with('carrier') ->orderBy('price') ->get(); $cheapest = CarrierOption::query() ->where('zone_id', $zone->id) ->enabled() ->orderBy('price') ->first(); ``` These queries read the shipping options only. To get the price a customer pays, including live rates, use `CarrierRateService`. ## Working with Orders [#working-with-orders] When a cart becomes an order, the order keeps the shipping price in `shipping_amount`, in cents, and links the shipping option in `shipping_option_id`, as described in [Order Conversion](/3.x/cart#order-conversion). Only a manual rate links an option: an order placed with a live rate has a `null` `shipping_option_id` and keeps its price only. ```php use Shopper\Core\Models\Contracts\Order; $order = resolve(Order::class)::query() ->with('shippingOption.carrier') ->findOrFail($orderId); $order->shippingOption?->carrier->name; shopper_money_format($order->shipping_amount ?? 0, $order->currency_code); ``` The packages sent for an order, their carrier and their tracking are shipments, described on the [Fulfillment](/3.x/fulfillment) page. The [Orders](/3.x/orders) page describes the order itself. ## Storefront Example [#storefront-example] A Blade or Livewire storefront calls `CarrierRateService` itself; a storefront built on the Store API gets the same rates from the [shipping options endpoint](#from-a-storefront). ### Checkout Shipping Selection [#checkout-shipping-selection] The origin of a shipment is the inventory location it leaves from, described on the [Locations](/3.x/locations) page. This controller quotes the cart from the default location, offers the rates priced in the cart currency, and quotes again when the customer submits a choice, so the price stored on the cart comes from the server: ```php title="app/Http/Controllers/CheckoutShippingController.php" $cart, 'rates' => $this->quote($cart), ]); } public function store(Request $request, CartManager $manager): RedirectResponse { $cart = Cart::current() ?? abort(404); $rate = $this->quote($cart)->first( fn (ShippingRate $rate): bool => $this->optionId($rate) === $request->input('option_id'), ); if ($rate === null) { return back()->withErrors(['option_id' => __('This shipping option is no longer available.')]); } $manager->setShippingMethod($cart, $this->optionId($rate), $rate->amount); return redirect()->route('checkout.payment'); } private function quote(CartModel $cart): Collection { return $this->rateService ->getZoneRates( zone: $cart->zone, from: $this->origin(), to: $this->destination($cart), packages: $this->packages($cart), ) ->rates ->filter(fn (ShippingRate $rate): bool => $rate->currency === $cart->currency_code) ->values(); } private function optionId(ShippingRate $rate): string { return "{$rate->carrierCode}:{$rate->serviceCode}"; } private function origin(): Address { $inventory = resolve(Inventory::class)::query() ->with('country') ->default() ->firstOrFail(); return new Address( firstName: '', lastName: $inventory->name, street: $inventory->street_address, city: $inventory->city, postalCode: $inventory->postal_code, state: $inventory->state ?? '', country: $inventory->country->cca2, street2: $inventory->street_address_plus, phone: $inventory->phone_number, email: $inventory->email, ); } private function destination(CartModel $cart): ?Address { $address = $cart->shippingAddress(); if ($address?->country === null) { return null; } return new Address( firstName: $address->first_name ?? '', lastName: $address->last_name, street: $address->address_1, city: $address->city, postalCode: $address->postal_code, state: $address->state ?? '', country: $address->country->cca2, company: $address->company, street2: $address->address_2, phone: $address->phone, ); } private function packages(CartModel $cart): array { $weight = $cart->lines->sum( fn (CartLine $line): float => (float) $line->purchasable->weight_value * $line->quantity, ); return [new Package(length: 40, width: 30, height: 20, weight: $weight)]; } } ``` The cart needs a zone before it can be quoted. Until the customer enters a shipping address, `destination()` returns `null` and the page offers the manual rates only. The example ships every order in one 40 by 30 by 20 cm box and assumes product weights are entered in kilograms; describe the boxes you really ship. `setShippingMethod()` is described in [Shipping and Payment](/3.x/cart). A store with several warehouses can ship from another location: pass the inventory you pick, such as the one nearest to the customer or the one that holds the stock, to `origin()`. A live quote depends on its origin, so quote again with the same origin when the customer confirms. ## Use Cases [#use-cases] These carriers and options cover the common shipping setups: | Carrier | Options | |---------|---------| | USPS | Priority Mail, Ground Advantage, Media Mail | | FedEx | Ground, Express, Overnight | | UPS | Ground, 2-Day, Next Day Air | | DHL | Express, Economy, Freight | | Local | Same-Day, Pick-up | | Scenario | Implementation | |----------|----------------| | Flat rate shipping | Manual carrier with one option at a fixed price | | Free shipping | Manual option with a price of `0` | | Zone-based pricing | One option per zone for each manual carrier | | Real-time rates | Assign a configured driver to the carrier | | Hybrid approach | Manual carriers for local delivery, live drivers for national and international shipping | | Carrier without a driver package | A [custom shipping driver](#custom-shipping-drivers) | ## Events [#events] Shopper dispatches no carrier event of its own and registers no observer on carriers or shipping options. Listen to the Eloquent model events instead, for example to clear a cached list of carriers on a delivery information page: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Carrier; use Shopper\Core\Models\CarrierOption; public function boot(): void { Carrier::saved(fn () => Cache::forget('storefront.delivery-options')); CarrierOption::saved(fn () => Cache::forget('storefront.delivery-options')); CarrierOption::deleted(fn () => Cache::forget('storefront.delivery-options')); } ``` A tracking update from a carrier driver dispatches the shipment events listed in [Shipment Events](/3.x/events#shipment-events). ## Permissions [#permissions] The admin panel checks one permission for shipping, `system.settings`. It opens the Carriers page and allows creating, editing, enabling and deleting a carrier, and adding, editing and deleting the shipping options of a zone. The [Access Control](/3.x/acl#access-by-section) page lists the permission of each section. ## In the Admin [#in-the-admin] Merchants manage carriers under Settings, Carriers, in the Shipping group. The list shows each carrier with its logo, name, driver, status toggle and last update. The driver badge is gray for the manual driver, green for a configured live driver and amber for a live driver missing its credentials. The carrier form holds the name, which also sets the slug, the driver (`Manual` by default, the others listed with a "Not configured" badge until their credentials are set), the website and the description. Shipping options are managed on each zone, in its Shipping Options section: the Add Option slide-over takes a name, a price in the zone currency, a carrier among those of the zone, a description, the visibility and metadata. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API quotes and stores the shipping choice of a cart under the `store` prefix, set by `SHOPPER_API_PREFIX`: | Endpoint | Does | |----------|------| | `GET /store/carts/{cartId}/shipping-options` | Lists the shipping options of the cart and their rates | | `POST /store/carts/{cartId}/shipping-method` | Chooses an option by `option_id` | | `POST /store/webhooks/shipping/{driver}` | Receives the tracking updates a carrier pushes, as described in [Driver Capabilities](#driver-capabilities) | The shipping options endpoint quotes the zone of the cart with `getZoneRates()`, and answers `422` when the cart has no zone. A cart that holds only virtual or external products gets no options. Manual rates are quoted at once; live rates need a shipping address on the cart and an origin, which is the default inventory location, or the location with the lowest `priority` when none is the default. A shipping address outside the zone returns no options. Options priced in another currency than the cart are left out. A shipping option resource has the type `shipping-options` and the ID `{carrier_code}:{service_code}`. It carries `name`, `carrier_name`, `carrier_code`, `service_code`, `amount` (in cents), `currency`, `price_type`, `estimated_days` and `estimated_delivery`. The response lists in `meta.warnings` what kept options out: a failing carrier, a missing origin, a currency mismatch or an address outside the zone. The amounts of the list are for display. Choosing an option quotes the cart again and stores the price of that quote, and the payment session and the cart completion quote it once more. These requests answer with an error code when the shipping choice no longer holds: | Code | Status | When | |------|--------|------| | `shipping_method_required` | 422 | The cart needs shipping and has no shipping option | | `shipping_option_unavailable` | 422 | The option is not, or no longer, among the quotes of the cart | | `shipping_price_changed` | 422 | The quote rose since the option was chosen. Choose the option again to accept the new price | | `shipping_provider_unavailable` | 503 | The carrier of the option is failing. The response carries `Retry-After: 5` | A lower quote replaces the stored price without an error. Once the payment provider may have collected the payment, the cart keeps the price it was charged. The [Cart](/3.x/cart) page describes the rest of the checkout, and the Store API [Checkout](/3.x/store-api/checkout#shipping-options) guide the shipping endpoints. # UPS (/3.x/carriers/ups) The `shopper/ups` package connects a Shopper store to the UPS APIs. A carrier that uses it quotes live UPS rates at checkout, computed from the shipment origin, the customer address and the packages, and Shopper refreshes the tracking of every UPS package from the UPS tracking API. The package registers the `ups` driver on the shipping manager of `shopper/shipping`. The manager, the carrier model and the rate service are described on the [Carriers](/3.x/carriers) page. This page covers what is specific to UPS. Shopper also ships drivers for FedEx (`shopper/fedex`) and USPS (`shopper/usps`); each section below says where they work differently. ## Installation [#installation] Install the package with Composer: ```bash composer require shopper/ups ``` Laravel discovers `Shopper\Ups\UpsServiceProvider`. The provider merges the package configuration under `shopper.ups` and registers the `ups` driver with `Shipping::extend()`, built from that configuration. The driver reads its values from environment variables, so you only publish the file to change how a value is read: ```bash php artisan vendor:publish --tag=shopper-ups-config ``` This creates `config/shopper/ups.php`. ## Configuration [#configuration] Every key of the file comes from an environment variable: | Key | Environment variable | Default | Description | |-----|----------------------|---------|-------------| | `enabled` | `SHIPPING_UPS_ENABLED` | `false` | Lists the driver in `Shipping::configuredDrivers()` | | `sandbox` | `SHIPPING_SANDBOX` | `false` | Sends the requests to the UPS Customer Integration Environment, `https://wwwcie.ups.com`, instead of `https://onlinetools.ups.com` | | `client_id` | `UPS_CLIENT_ID` | `null` | Client ID of your UPS app | | `client_secret` | `UPS_CLIENT_SECRET` | `null` | Client secret of your UPS app | | `user_id` | `UPS_USER_ID` | `null` | User ID of your UPS account | | `account_number` | `UPS_ACCOUNT_NUMBER` | `null` | UPS account number, sent as the shipper number | Add the values to your `.env` file: ```dotenv SHIPPING_SANDBOX=true UPS_CLIENT_ID=your-client-id UPS_CLIENT_SECRET=your-client-secret UPS_USER_ID=your-user-id UPS_ACCOUNT_NUMBER=your-account-number ``` The driver is ready once `client_id`, `client_secret`, `user_id` and `account_number` are all filled in: its `isConfigured()` method then returns `true`, carriers that use it quote UPS rates, the admin panel stops showing it as "Not configured" and the tracking sync picks up its packages. The `enabled` key takes no part in that check. Only `Shipping::configuredDrivers()` reads it, as described in [Driver Configuration](/3.x/carriers#driver-configuration), so set it to `true` for code that lists the configured drivers. To stop UPS from quoting, disable the carrier or remove a credential. `SHIPPING_SANDBOX` is shared by the FedEx, UPS and USPS drivers: one variable switches all three. To run UPS against the sandbox while another driver stays in production, publish the file and set its `sandbox` key to `true`. ### Credentials [#credentials] UPS issues the client ID and the client secret for an app you create in its developer portal; both are listed on the app info page. The account number is your UPS shipper number. The user ID is the one of your UPS account: `isConfigured()` requires it, but no request of the driver sends it. The driver exchanges the client ID and the secret for an OAuth access token with the client credentials grant, sending them with HTTP Basic authentication to `/security/v1/oauth/token`. It keeps the token in the default cache store until a minute before it expires, under a key that holds the client ID and the environment, and a cache lock stops two requests from asking for a token at the same time. Each rate and tracking request also carries a `transId` header, a new identifier per request, and a `transactionSrc` header set to `shopper`. The FedEx and USPS drivers post their key and secret in the form body instead, and the USPS driver needs no account number. ## Enabling the Carrier [#enabling-the-carrier] Installing the package adds no carrier to the store. A merchant creates one under Settings, Carriers: name it `UPS` and pick UPS as its driver. The name sets the slug, `ups`, which must equal the driver code because the Store API finds the carrier of a live rate by that code, as [API-Connected Carrier](/3.x/carriers#api-connected-carrier) explains. Then add the carrier to each zone it serves, from the zone form, and keep it enabled. The [User Guide](/3.x/user-guide) walks through these screens. The driver select lists every installed driver, whatever its `enabled` key says: UPS shows there once the package is installed, with a "Not configured" badge until the four credentials are filled in. Until then the carrier offers its shipping options in the zone, as a manual carrier does. Once the driver is configured, the carrier quotes UPS rates and no longer reads those options, so a UPS carrier needs no shipping option. ## Shipping Rates [#shipping-rates] The driver quotes a shipment with one call to the UPS rating API, `POST /api/rating/v2409/Shop`, which returns a rate for every UPS service between the two addresses. Shopper calls it through `CarrierRateService` when the Store API lists the shipping options of a cart, as described in [Calculating Shipping Rates](/3.x/carriers#calculating-shipping-rates). The Store API takes the origin from the [default inventory location](/3.x/locations#default-location), or the location with the lowest priority when none is the default, and needs its country and street address. It sends one package per cart, with the summed weight of the items and their largest dimensions, in the unit system of `shopper.shipping.units`. The request holds these values: | UPS field | Value | |-----------|-------| | `PickupType` | `01`, daily pickup | | `CustomerClassification` | `01`, daily rates | | `Shipper` | The `account_number` as `ShipperNumber`, the company of the origin address or its name as `Name`, and the origin address | | `ShipFrom`, `ShipTo` | The origin and destination: `street` and `street2` as address lines, `city`, `state` as the state or province code, `postalCode` and `country` | | `Package` | One entry per package, with the packaging type `02`, dimensions in `CM` and weight in `KGS`, rounded to two decimals | The driver converts a package measured in inches and pounds to centimeters and kilograms before sending it. UPS answers with one rated shipment per service, and each becomes a `ShippingRate`: | `ShippingRate` property | UPS value | |-------------------------|-----------| | `serviceCode` | The service code, `Service.Code` | | `serviceName` | The service description, or the name of the code from the table below | | `amount` | `TotalCharges.MonetaryValue`, in cents | | `currency` | `TotalCharges.CurrencyCode`, in uppercase | | `estimatedDays` | `GuaranteedDelivery.BusinessDaysInTransit`, when UPS guarantees the service | When UPS sends no description, the driver names the service from its code: | Code | Service | Code | Service | |------|---------|------|---------| | `01` | UPS Next Day Air | `13` | UPS Next Day Air Saver | | `02` | UPS 2nd Day Air | `14` | UPS Next Day Air Early | | `03` | UPS Ground | `54` | UPS Worldwide Express Plus | | `07` | UPS Worldwide Express | `59` | UPS 2nd Day Air A.M. | | `08` | UPS Worldwide Expedited | `65` | UPS Saver | | `11` | UPS Standard | `71` | UPS Worldwide Express Freight Midday | | `12` | UPS 3 Day Select | `75` | UPS Heavy Goods | | `96` | UPS Worldwide Express Freight | | | Any other code is named `UPS` followed by the code. The driver does not ask for negotiated rates: it reads `TotalCharges`, so a discount negotiated on your UPS account does not show in the quotes. A currency without decimals keeps its amount as is, as described in [Zero-Decimal Currencies](/3.x/money#zero-decimal-currencies). A service without an amount, or with an amount of zero, is left out and logged as a `Discarded an unusable UPS rate.` warning with the service code and the reason. The Store API leaves out the options priced in another currency than the cart and says so in its warnings, so the currency UPS quotes in must match the currency of the carts. Quotes are cached for `shopper.shipping.rates_cache_ttl` seconds, per driver, addresses and packages, as described in [Rate Caching](/3.x/carriers#rate-caching). UPS is the only one of the three drivers that returns transit days. The FedEx driver also sends metric units, and the USPS driver sends pounds and inches and quotes retail prices in US dollars. ## Labels [#labels] The driver does not create shipments or buy labels at UPS: its `supportsLabels()` method returns `false`, as do those of the FedEx and USPS drivers. Buy the label from your UPS account, then record the package on the order: the Create Shipping Label slide-over of the order page takes the UPS carrier, the tracking number and the tracking URL, as described in [In the Admin](/3.x/fulfillment#in-the-admin). ## Tracking [#tracking] The driver supports tracking and no webhook, so Shopper asks UPS for the tracking of each open package. The scheduled `shopper:shipments:sync-tracking` command queues a refresh every 30 minutes for each package of a UPS carrier that has a tracking number and is neither Delivered nor Returned, as described in [Tracking Sync](/3.x/fulfillment#tracking-sync). Run it by hand to refresh the packages now: ```bash php artisan shopper:shipments:sync-tracking ``` The driver calls `GET /api/track/v1/details/{trackingNumber}` and turns each activity of the package into a tracking event, with the UPS description and a location made of the city, the state and the country of the activity. The time of an activity is read in UTC, or from its local time and offset when UPS gives no UTC time. The status comes from the type of the activity: | UPS activity type | Shipment status | |-------------------|-----------------| | `M` | `ShipmentStatus::Pending` | | `P` | `ShipmentStatus::PickedUp` | | `D` | `ShipmentStatus::OutForDelivery` | | `X` | `ShipmentStatus::DeliveryFailed` | | Any other type | `ShipmentStatus::InTransit` | When UPS reports a delivery date, the driver adds a Delivered event at the time of the last activity of that day. No activity type maps to Returned, so record a package UPS sends back yourself, as described in [Handling Returns](/3.x/fulfillment#handling-returns). Each activity carries an external ID built from its time and status code, so an activity read twice is recorded once. A tracking number UPS answers with a `404` and an error code is logged as a `The carrier has no record of this tracking number.` warning and the package stays as it is. Any other UPS error fails the job, which retries after the delays of `shopper.shipping.tracking.backoff`. The FedEx driver tracks its packages the same way. The USPS driver does not track. ## Errors [#errors] A failing UPS call never hides the other carriers. Each request times out after 15 seconds, and a request that cannot connect is tried up to three times, 200 milliseconds apart. The driver throws a `Shopper\Shipping\Exceptions\ShippingException` when the connection still fails, when UPS answers with an error, including a refused token request, or when the answer holds no usable rate. The message names the driver and the error UPS returned, such as `API error from [ups]: ...`, or the HTTP status when UPS gives no message. `CarrierRateService` catches the exception, logs a `Shipping rates unavailable for carrier.` warning and reports the carrier as failing. The Store API turns it into a warning on the shipping options and answers `503` when the customer picks a UPS option, as described in [Failing Carriers](/3.x/carriers#failing-carriers). ## Testing [#testing] Test the driver against the UPS Customer Integration Environment before the store quotes real shipments. ### Sandbox Mode [#sandbox-mode] Set `SHIPPING_SANDBOX=true` to send every request to `https://wwwcie.ups.com`. The access token is cached per environment, so a sandbox token is never sent to production. The quote cache key holds the driver, the addresses and the packages, without the environment. After you switch from the sandbox to production, run `php artisan cache:clear` or wait `shopper.shipping.rates_cache_ttl` seconds, or the Store API can serve a sandbox quote. ### Quoting a Test Shipment [#quoting-a-test-shipment] Call the driver directly to check the credentials without a cart or a carrier. This Artisan command asks for the rates of one package from a Los Angeles warehouse to a New York customer: ```php title="routes/console.php" use Illuminate\Support\Facades\Artisan; use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; use Shopper\Shipping\Facades\Shipping; Artisan::command('shipping:quote-ups', function (): void { $rates = Shipping::driver('ups')->calculateRates( from: new Address( firstName: '', lastName: 'Los Angeles Warehouse', street: '1200 S Alameda St', city: 'Los Angeles', postalCode: '90021', state: 'CA', country: 'US', ), to: new Address( firstName: 'Jane', lastName: 'Cooper', street: '350 Fifth Avenue', city: 'New York', postalCode: '10118', state: 'NY', country: 'US', ), packages: [ new Package(length: 30, width: 20, height: 15, weight: 2.5), ], ); foreach ($rates as $rate) { $this->line("{$rate->serviceCode}: {$rate->serviceName}, {$rate->formattedAmount()}"); } }); ``` Run `php artisan shipping:quote-ups`. Each line is a UPS service with its price. A `ShippingException` carries the UPS error, for example a refused token when a credential is wrong. This call skips the quote cache, so it always reaches UPS. ## Events [#events] The driver dispatches no event of its own. The tracking it reports is recorded through `RecordShipmentEventAction`, which dispatches the shipment events: `OrderShipmentEventRecorded` for each new activity, and `OrderShipmentDelivered` or `OrderShipmentDeliveryFailed` when the package reaches that status. [Shipment Events](/3.x/events#shipment-events) lists their payloads. # USPS (/3.x/carriers/usps) The `shopper/usps` package connects a Shopper store to the USPS APIs. A carrier that uses it quotes live USPS rates at checkout, computed from the postal codes of the shipment origin and the customer address and from the packages. The driver does not track packages. The package registers the `usps` driver on the shipping manager of `shopper/shipping`. The manager, the carrier model and the rate service are described on the [Carriers](/3.x/carriers) page. This page covers what is specific to USPS. Shopper also ships drivers for FedEx (`shopper/fedex`) and UPS (`shopper/ups`); each section below says where they work differently. ## Installation [#installation] Install the package with Composer: ```bash composer require shopper/usps ``` Laravel discovers `Shopper\Usps\UspsServiceProvider`. The provider merges the package configuration under `shopper.usps` and registers the `usps` driver with `Shipping::extend()`, built from that configuration. The driver reads its values from environment variables, so you only publish the file to change how a value is read: ```bash php artisan vendor:publish --tag=shopper-usps-config ``` This creates `config/shopper/usps.php`. ## Configuration [#configuration] Every key of the file comes from an environment variable: | Key | Environment variable | Default | Description | |-----|----------------------|---------|-------------| | `enabled` | `SHIPPING_USPS_ENABLED` | `false` | Lists the driver in `Shipping::configuredDrivers()` | | `sandbox` | `SHIPPING_SANDBOX` | `false` | Sends the requests to the USPS test environment, `https://apis-tem.usps.com`, instead of `https://apis.usps.com` | | `client_id` | `USPS_CLIENT_ID` | `null` | Consumer key of your USPS app | | `client_secret` | `USPS_CLIENT_SECRET` | `null` | Consumer secret of your USPS app | Add the values to your `.env` file: ```dotenv SHIPPING_SANDBOX=true USPS_CLIENT_ID=your-consumer-key USPS_CLIENT_SECRET=your-consumer-secret ``` The driver is ready once `client_id` and `client_secret` are both filled in: its `isConfigured()` method then returns `true`, carriers that use it quote USPS rates and the admin panel stops showing it as "Not configured". The `enabled` key takes no part in that check. Only `Shipping::configuredDrivers()` reads it, as described in [Driver Configuration](/3.x/carriers#driver-configuration), so set it to `true` for code that lists the configured drivers. To stop USPS from quoting, disable the carrier or remove a credential. `SHIPPING_SANDBOX` is shared by the FedEx, UPS and USPS drivers: one variable switches all three. To run USPS against the test environment while another driver stays in production, publish the file and set its `sandbox` key to `true`. ### Credentials [#credentials] USPS issues a consumer key and a consumer secret for an app you add in the Customer Onboarding Portal of your USPS business account, under My Apps, in the credentials of the app. The consumer key is your `client_id` and the consumer secret your `client_secret`. The driver needs no account number: it quotes retail prices. The driver exchanges the key and the secret for an OAuth access token with the client credentials grant, posting both in the form body to `/oauth2/v3/token`. It keeps the token in the default cache store until a minute before it expires, under a key that holds the client ID and the environment, and a cache lock stops two requests from asking for a token at the same time. The FedEx driver also needs an account number, and the UPS driver needs an account number and a user ID and sends its key and secret with HTTP Basic authentication. ## Enabling the Carrier [#enabling-the-carrier] Installing the package adds no carrier to the store. A merchant creates one under Settings, Carriers: name it `USPS` and pick USPS as its driver. The name sets the slug, `usps`, which must equal the driver code because the Store API finds the carrier of a live rate by that code, as [API-Connected Carrier](/3.x/carriers#api-connected-carrier) explains. Then add the carrier to each zone it serves, from the zone form, and keep it enabled. The [User Guide](/3.x/user-guide) walks through these screens. The driver select lists every installed driver, whatever its `enabled` key says: USPS shows there once the package is installed, with a "Not configured" badge until the two credentials are filled in. Until then the carrier offers its shipping options in the zone, as a manual carrier does. Once the driver is configured, the carrier quotes USPS rates and no longer reads those options, so a USPS carrier needs no shipping option. ## Shipping Rates [#shipping-rates] The driver quotes each package with one call to the USPS shipping options API, `POST /shipments/v3/options/search`. Shopper calls it through `CarrierRateService` when the Store API lists the shipping options of a cart, as described in [Calculating Shipping Rates](/3.x/carriers#calculating-shipping-rates). The Store API takes the origin from the [default inventory location](/3.x/locations#default-location), or the location with the lowest priority when none is the default, and needs its country and street address. It sends one package per cart, with the summed weight of the items and their largest dimensions, in the unit system of `shopper.shipping.units`. The driver sends only the postal codes of the two addresses, and the destination country when the shipment is not domestic. A shipment is domestic when both addresses are in the United States (`country` is `US`): | USPS field | Domestic shipment | Other destinations | |------------|-------------------|--------------------| | `pricingOptions` | `RETAIL` price type | `RETAIL` price type | | `originZIPCode` | The postal code of the origin | The postal code of the origin | | `destinationZIPCode` | The postal code of the destination | Not sent | | `destinationCountryCode` | Not sent | The country of the destination | | `foreignPostalCode` | Not sent | The postal code of the destination | | `destinationEntryFacilityType` | `NONE` | `NONE` | | `packageDescription` | Weight in pounds, length, width and height in inches, rounded to two decimals, mail class `ALL_OUTBOUND` | The same, with the mail class `ALL` | The driver converts a package measured in centimeters and kilograms to inches and pounds before sending it. USPS answers with the prices of its mail classes, and each becomes a `ShippingRate`: | `ShippingRate` property | USPS value | |-------------------------|------------| | `serviceCode` | The mail class, followed by a hyphen and the rate indicator when USPS gives one | | `serviceName` | The product name, `productName` | | `amount` | The price, in cents | | `currency` | Always `USD` | | `estimatedDays` | Not set | A shipment with several packages is quoted one package at a time. The driver adds up the prices of each service and keeps only the services USPS priced for every package. A price without a mail class, a product name or a numeric amount, or with an amount of zero, is left out and logged as a `Discarded an unusable USPS rate.` warning with the mail class and the reason. Every USPS rate is in US dollars, and the Store API leaves out the options priced in another currency than the cart and says so in its warnings: a cart in another currency gets no USPS option. Quotes are cached for `shopper.shipping.rates_cache_ttl` seconds, per driver, addresses and packages, as described in [Rate Caching](/3.x/carriers#rate-caching). The FedEx and UPS drivers send centimeters and kilograms, quote the whole shipment in one call and return the currency of the carrier, and only the UPS driver returns transit days. ## Labels [#labels] The driver does not create shipments or buy labels at USPS: its `supportsLabels()` method returns `false`, as do those of the FedEx and UPS drivers. Buy the label from USPS, then record the package on the order: the Create Shipping Label slide-over of the order page takes the USPS carrier, the tracking number and the tracking URL, as described in [In the Admin](/3.x/fulfillment#in-the-admin). ## Tracking [#tracking] The driver does not track packages: its `supportsTracking()` method returns `false`, so the `shopper:shipments:sync-tracking` command skips the packages of a USPS carrier, as described in [Tracking Sync](/3.x/fulfillment#tracking-sync). Record each step from the shipment timeline of the admin panel, or from your code with `RecordShipmentEventAction`, as described in [Carrier Tracking](/3.x/fulfillment#carrier-tracking). The FedEx and UPS drivers both track their packages. ## Errors [#errors] A failing USPS call never hides the other carriers. Each request times out after 15 seconds, and a request that cannot connect is tried up to three times, 200 milliseconds apart. The driver throws a `Shopper\Shipping\Exceptions\ShippingException` when the connection still fails, when USPS answers with an error, including a refused token request, or when the answer holds no usable rate. The message names the driver and the error USPS returned, such as `API error from [usps]: ...`, or the HTTP status when USPS gives no message. With several packages, an error on one package fails the whole quote. `CarrierRateService` catches the exception, logs a `Shipping rates unavailable for carrier.` warning and reports the carrier as failing. The Store API turns it into a warning on the shipping options and answers `503` when the customer picks a USPS option, as described in [Failing Carriers](/3.x/carriers#failing-carriers). ## Testing [#testing] Test the driver against the USPS test environment before the store quotes real shipments. ### Sandbox Mode [#sandbox-mode] Set `SHIPPING_SANDBOX=true` to send every request to `https://apis-tem.usps.com`. The test environment takes the same consumer key and secret as production. The access token is cached per environment, so a test token is never sent to production. The quote cache key holds the driver, the addresses and the packages, without the environment. After you switch from the sandbox to production, run `php artisan cache:clear` or wait `shopper.shipping.rates_cache_ttl` seconds, or the Store API can serve a sandbox quote. ### Quoting a Test Shipment [#quoting-a-test-shipment] Call the driver directly to check the credentials without a cart or a carrier. This Artisan command asks for the rates of one package from a Los Angeles warehouse to a New York customer: ```php title="routes/console.php" use Illuminate\Support\Facades\Artisan; use Shopper\Shipping\DataTransferObjects\Address; use Shopper\Shipping\DataTransferObjects\Package; use Shopper\Shipping\Facades\Shipping; Artisan::command('shipping:quote-usps', function (): void { $rates = Shipping::driver('usps')->calculateRates( from: new Address( firstName: '', lastName: 'Los Angeles Warehouse', street: '1200 S Alameda St', city: 'Los Angeles', postalCode: '90021', state: 'CA', country: 'US', ), to: new Address( firstName: 'Jane', lastName: 'Cooper', street: '350 Fifth Avenue', city: 'New York', postalCode: '10118', state: 'NY', country: 'US', ), packages: [ new Package(length: 12, width: 8, height: 6, weight: 5.5, unit: 'imperial'), ], ); foreach ($rates as $rate) { $this->line("{$rate->serviceCode}: {$rate->serviceName}, {$rate->formattedAmount()}"); } }); ``` Run `php artisan shipping:quote-usps`. Each line is a USPS mail class with its price. A `ShippingException` carries the USPS error, for example a refused token when a credential is wrong. This call skips the quote cache, so it always reaches USPS. ## Events [#events] The driver dispatches no event of its own, and since it does not track, no shipment event comes from USPS. The events you record on a USPS package dispatch the shipment events listed in [Shipment Events](/3.x/events#shipment-events). # Cart (/3.x/cart) The `shopper/cart` package holds everything between "Add to cart" and "Place order". It stores the cart and its lines, prices each line through the pricing resolver, checks stock, applies promotions, computes tax, and turns the cart into an order inside a single database transaction. The Store API is built on it, and a Blade or Livewire storefront calls the same classes directly. The package has five main pieces: - `Shopper\Cart\CartManager` changes a cart: lines, addresses, promotions, shipping and payment choices, currency and zone, totals. - `Shopper\Cart\CartSessionManager`, behind the `Shopper\Cart\Facades\Cart` facade, keeps the current cart of a visitor in the session. - The calculation pipeline computes the subtotal, discounts, tax, shipping and total through a list of steps you can extend. - `Shopper\Cart\Discounts\PromotionResolver` and `Shopper\Cart\Discounts\DiscountValidator` decide which discount codes and automatic promotions apply. - `Shopper\Cart\Actions\CreateOrderFromCartAction` converts the cart into an order, reserves stock and records promotion usage. Every amount of the cart is an integer in cents: a line priced at $25.00 stores `2500`. The [Money](/3.x/money#amounts-in-cents) page covers cents, zero-decimal currencies and formatting. ## Models [#models] The cart models live in `Shopper\Cart\Models`. `Cart` and `CartLine` can be replaced with your own classes; their contracts are `Shopper\Cart\Models\Contracts\Cart` and `Shopper\Cart\Models\Contracts\CartLine`. The four other models (`CartAddress`, `CartLineAdjustment`, `CartLineTaxLine` and `CartPromotion`) are fixed. Their tables take the Shopper [table prefix](/3.x/configuration#database-table-prefix), `sh_` by default. ### Cart [#cart] `Shopper\Cart\Models\Cart` implements the `Shopper\Cart\Models\Contracts\Cart` contract and uses `HasPublicId`, which fills `public_id` with a ULID on creation. The Store API identifies a cart by this public ID, never by its numeric key, as described in [Public IDs](/3.x/models#public-ids). Carts are stored in the `sh_carts` table: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `customer_id` | bigint | yes | null | The customer, a row of the `users` table | | `channel_id` | bigint | yes | null | The sales channel | | `zone_id` | bigint | yes | null | The zone that sets carriers and payment methods, passed to the price resolver | | `currency_code` | string | no | - | ISO currency code, such as `USD` | | `email` | string | yes | null | Contact email of the checkout | | `completed_at` | timestamp | yes | null | Set when the cart becomes an order | | `order_id` | bigint | yes | null | The order created from the cart | | `payment_method_id` | bigint | yes | null | The payment method chosen at checkout | | `shipping_option_id` | string | yes | null | The chosen shipping option, `{carrier_code}:{service_code}` | | `shipping_amount` | integer | yes | null | Price of the chosen shipping option, in cents | | `payment_session` | jsonb | yes | null | The payment session opened with the payment provider | | `payment_reference` | string | yes | null | Provider reference of that payment session, indexed | | `calculated_at` | timestamp | yes | null | When the totals were last calculated | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last activity on the cart | Deleting a channel, a zone, a payment method or an order sets the matching column to `null`. Deleting a customer does the same for `customer_id`. `payment_session` and `payment_reference` are guarded from mass assignment: the payment flow writes them through the cart manager, as the [Payments](/3.x/payments) page describes. A cart has these relationships: | Relationship | Type | Related model | |--------------|------|---------------| | `lines` | HasMany | The class in `shopper.cart.models.cart_line` | | `promotions` | HasMany | `CartPromotion` | | `addresses` | HasMany | `CartAddress` | | `customer` | BelongsTo | The class in `auth.providers.users.model` | | `channel` | BelongsTo | The class in `shopper.models.channel` | | `zone` | BelongsTo | `Shopper\Core\Models\Zone` | | `paymentMethod` | BelongsTo | `Shopper\Core\Models\PaymentMethod` | | `order` | BelongsTo | `Shopper\Core\Models\Order` | And these methods: | Method | Returns | |--------|---------| | `isCompleted()` | `true` once `completed_at` is set | | `shippingAddress()` | The `CartAddress` of type shipping, or `null` | | `billingAddress()` | The `CartAddress` of type billing, or `null` | | `belongsToCustomer($customerId)` | Whether the cart belongs to that customer | | `holdsProviderPaymentSession()` | Whether a payment session other than the manual driver is open | | `pricingContext()` | The `PricingContext` of the cart (currency, zone, channel, customer), for the [price resolver](/3.x/pricing#resolving-prices) | Two query scopes find the cart of a payment: `holdingPaymentReference($reference)` and `forPayment($reference, $publicId)`. The payment package uses them when a provider reports a payment. ### CartLine [#cartline] `Shopper\Cart\Models\CartLine` implements the `Shopper\Cart\Models\Contracts\CartLine` contract and uses `HasPublicId`. A line holds one purchasable, a product or a variant, through the `purchasable` morph relation. The cart keeps one line per purchasable: a unique index on `cart_id`, `purchasable_type` and `purchasable_id` enforces it. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `cart_id` | bigint | no | - | The cart, deleted with it | | `purchasable_type` | string | no | - | Morph type of the product or variant | | `purchasable_id` | bigint | no | - | Morph key of the product or variant | | `quantity` | unsigned int | no | - | Quantity, at most `CartLine::MAXIMUM_QUANTITY` (1,000,000) | | `unit_price_amount` | unsigned int | no | - | Unit price, in cents | | `is_custom_price` | boolean | no | false | Whether the price was set by hand, as described in [Custom Line Prices](#custom-line-prices) | | `pricing` | json | yes | null | What the price resolver returned with the price | | `metadata` | jsonb | yes | null | Your own data, such as a gift message | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A line belongs to its `cart` and has many `adjustments` (`CartLineAdjustment`) and `taxLines` (`CartLineTaxLine`). `is_custom_price` and `pricing` are guarded: the cart manager writes them when it prices the line. ### CartAddress [#cartaddress] `Shopper\Cart\Models\CartAddress` holds the shipping and billing addresses of the checkout. A cart has at most one address of each type, and the `type` column is cast to the `Shopper\Core\Enum\AddressType` enum (`Shipping` or `Billing`). | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `public_id` | ulid | yes | Public identifier, unique | | `cart_id` | bigint | no | The cart, deleted with it | | `type` | string | no | `shipping` or `billing` | | `country_id` | bigint | yes | The country | | `first_name` | string | yes | First name | | `last_name` | string | no | Last name | | `company` | string | yes | Company name | | `address_1` | string | no | Street address | | `address_2` | string | yes | Apartment, suite, floor | | `city` | string | no | City | | `state` | string | yes | State or province code | | `postal_code` | string | no | Postal code | | `phone` | string | yes | Phone number | The `full_name` accessor joins `first_name` and `last_name`. The country of the shipping address decides the tax of the cart. ### CartLineAdjustment [#cartlineadjustment] `Shopper\Cart\Models\CartLineAdjustment` is the share of one promotion on one line. The pipeline deletes and rewrites these rows on every calculation. | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `cart_line_id` | bigint | no | The line, deleted with it | | `cart_promotion_id` | bigint | yes | The promotion of the cart that produced it | | `discount_id` | bigint | yes | The discount | | `amount` | unsigned int | no | Discount on the line, in cents | | `code` | string | yes | The discount code, `null` for an automatic promotion | ### CartLineTaxLine [#cartlinetaxline] `Shopper\Cart\Models\CartLineTaxLine` is one tax applied to one line, with its `taxRate` relation. The pipeline rewrites these rows when it calculates tax. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `cart_line_id` | bigint | no | - | The line, deleted with it | | `tax_rate_id` | bigint | yes | null | The tax rate | | `code` | string | no | - | Tax code | | `name` | string | no | - | Tax name, such as "VAT" | | `rate` | decimal(8,4) | no | - | Rate in percent: `20.0000` for 20% | | `amount` | unsigned int | no | 0 | Tax on the line, in cents | ### CartPromotion [#cartpromotion] `Shopper\Cart\Models\CartPromotion` is a discount attached to the cart, either a code the customer entered or an automatic promotion the pipeline found. The `source` column is cast to `Shopper\Core\Enum\PromotionSource` (`Code` or `Automatic`). A cart holds each discount once: a unique index covers `cart_id` and `discount_id`. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `cart_id` | bigint | no | - | The cart, deleted with it | | `discount_id` | bigint | yes | null | The discount | | `source` | string | no | `code` | `code` or `automatic` | | `code` | string | yes | null | The code entered, `null` for an automatic promotion | | `computed_amount` | unsigned int | no | 0 | What the promotion takes off the cart at the last calculation, in cents | | `sequence` | unsigned int | no | 0 | Order in which it was applied | | `type` | string | yes | null | Discount type at the last calculation | | `value` | unsigned int | yes | null | Discount value at the last calculation | | `campaign_id` | bigint | yes | null | Campaign of the discount at the last calculation | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A promotion with a `computed_amount` of `0` stays on the cart without discounting anything: the code no longer validates, or a better promotion of the same class won. ## Session Management [#session-management] `CartSessionManager` remembers the cart of a visitor in the HTTP session. It stores the cart's `id` under the session key `shopper.cart.session.key` (`shopper_cart` by default) and is registered as a singleton. A Blade or Livewire storefront uses it to find the cart of the current request; a storefront built on the Store API keeps the cart public ID on its side instead. ### Using the Facade [#using-the-facade] The `Shopper\Cart\Facades\Cart` facade points to the session manager. Create the cart with the channel and the zone of the visitor, so the pricing context carries them from the first line: ```php title="app/Http/Controllers/CartController.php" use Shopper\Cart\Facades\Cart; use Shopper\Core\Models\Contracts\Channel; $cart = Cart::current() ?? Cart::create([ 'channel_id' => resolve(Channel::class)::query()->default()->value('id'), 'zone_id' => session('zone_id'), 'currency_code' => 'EUR', ]); Cart::use($existingCart); Cart::associate($request->user()); Cart::forget(); ``` ### Behavior [#behavior] The session manager follows these rules: - `current()` returns the cart stored in the session, or `null` when there is none or it is completed. When `shopper.cart.session.auto_create` is `true`, it creates a cart instead of returning `null`. - `create()` creates a cart with the attributes you pass, sets `currency_code` to the store default currency from `shopper_currency()` when you pass none, and stores the cart in the session. - `use()` stores an existing cart in the session. - `forget()` removes the cart from the session without deleting it. - `associate()` gives the session cart to the customer who just signed in, as described in [Associating Cart on Login](#associating-cart-on-login). ## Calculation Pipeline [#calculation-pipeline] Cart totals come out of a Laravel pipeline. Each step receives a `Shopper\Cart\Pipelines\CartPipelineContext`, adds its part and passes it on. The context carries the cart and the running amounts in cents: `subtotal`, `discountTotal`, `taxTotal`, `shippingTotal`, `total`, `taxInclusive`, and `lineSubtotals`, the subtotal of each line keyed by line ID. ### Default Pipeline [#default-pipeline] The steps are listed under `pipelines.cart` in `config/shopper/cart.php`: ```php title="config/shopper/cart.php" use Shopper\Cart\Pipelines; 'pipelines' => [ 'cart' => [ Pipelines\CalculateLines::class, Pipelines\ApplyAutomaticPromotions::class, Pipelines\ApplyDiscounts::class, Pipelines\CalculateTax::class, Pipelines\Calculate::class, ], ], ``` ### Pipeline Steps [#pipeline-steps] Each step does one job, in this order: | Step | What it does | |------|--------------| | `CalculateLines` | Multiplies the unit price of each line by its quantity, fills `lineSubtotals` and sums them into `subtotal` | | `ApplyAutomaticPromotions` | Attaches each active automatic discount the cart qualifies for as a `CartPromotion`, and removes those it no longer qualifies for | | `ApplyDiscounts` | Resolves the promotions of the cart, writes a `CartLineAdjustment` for each line a promotion discounts, and sets `discountTotal` | | `CalculateTax` | Computes the tax of each line on its subtotal minus its adjustments, writes the `CartLineTaxLine` rows, sets `taxTotal` and `taxInclusive`. Skipped until the shipping address has a country | | `Calculate` | Sets `shippingTotal` from the cart's `shipping_amount` and computes `total` | `Calculate` adds tax to the total only when prices exclude it: the goods total is `subtotal - discountTotal + taxTotal`, or `subtotal - discountTotal` when prices include tax, and never goes below `0`. The shipping amount is added on top. The [Taxes](/3.x/taxes) page covers tax zones, rates and tax-inclusive prices. While the cart holds an open payment session with a provider, the promotion and tax steps keep the stored adjustments and tax lines as they are, so the amount being paid does not move under the customer. ### Stored Totals [#stored-totals] `CartManager` offers two ways to read totals. `calculate()` always runs the pipeline and records the time in `calculated_at`. `totals()` runs the pipeline only when the cart was never calculated or the last calculation is older than `shopper.cart.totals_ttl_minutes` (15 by default). Otherwise it rebuilds the totals from the stored rows: line prices, adjustments, tax lines and `shipping_amount`. Every change to a line, an address, a promotion, the currency or the shipping choice clears `calculated_at`, so the next `totals()` call runs the pipeline again. The TTL covers what changes without touching the cart, such as an automatic promotion that starts or ends. The Store API answers with `totals()`; the checkout, the payment session and the promotion endpoint call `calculate()`. ### Custom Pipeline [#custom-pipeline] A step is a class with a `handle(CartPipelineContext $context, Closure $next)` method that returns `$next($context)`. The container builds it, so its constructor can ask for services. This step records the loyalty points the order will earn, one point per dollar of the total, in the cart metadata where the storefront can show them: ```php title="app/Cart/RecordLoyaltyPoints.php" cart; $points = intdiv($context->total, 100); if (($cart->metadata['loyalty_points'] ?? null) !== $points) { $cart->update([ 'metadata' => [...$cart->metadata ?? [], 'loyalty_points' => $points], ]); } return $next($context); } } ``` Add it to `pipelines.cart` in `config/shopper/cart.php`, at the position where it must run. A package or an add-on that cannot edit the application configuration registers its step on the `Shopper\Cart\Pipelines\CartPipeline` singleton instead, from the `boot()` method of its service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Cart\RecordLoyaltyPoints; use Shopper\Cart\Pipelines\CartPipeline; public function boot(): void { $this->app->make(CartPipeline::class)->append(RecordLoyaltyPoints::class); } ``` `insertAfter($anchor, $step)` and `insertBefore($anchor, $step)` place a step next to an existing one, such as `Shopper\Cart\Pipelines\CalculateTax`. Shopper applies the insertions to the configured list in the order they are registered. When the anchor is not in the pipeline, the first calculation throws an `InvalidArgumentException` that names the step and its anchor. A step that changes an amount must store it where `totals()` reads it: the line prices, the adjustments, the tax lines or `shipping_amount`. An amount added to the context only shows in the result of `calculate()`, and `totals()` returns the stored amounts until the next calculation. ## Promotions [#promotions] A discount reaches the cart in two ways. A code entered by the customer is attached with `applyCoupon()` as a `CartPromotion` of source `code`. An automatic discount needs no code: the `ApplyAutomaticPromotions` step attaches it while the cart qualifies. On each calculation, `ApplyDiscounts` checks every promotion against the discount rules (dates, usage limits, eligibility, zone, minimum amount or quantity), applies them by exclusivity class and priority, stacks a second discount of the same class only when both are combinable, stops at `shopper.cart.max_promotions` (5 by default), and skips a promotion its campaign budget cannot cover. A promotion that does not apply stays on the cart with a computed amount of `0`. The [Discounts](/3.x/discounts) page documents [eligibility](/3.x/discounts#discount-eligibility), [usage limits](/3.x/discounts#usage-limit-enforcement), [priority and combination](/3.x/discounts#priority-and-combination) and [automatic discounts](/3.x/discounts#automatic-discounts). ## Stock Validation [#stock-validation] `add()` and `update()` check stock before they change the quantity of a line. The check covers products and variants that implement `Shopper\Core\Models\Contracts\Stockable` and track inventory: products of type standard or variant, and product variants. Virtual and external products are not checked, nor is a product with `allow_backorder` set to `true`. When the cart quantity exceeds the stock, the manager throws a `Shopper\Cart\Exceptions\InsufficientStockException`: ```php title="app/Http/Controllers/CartLineController.php" use Shopper\Cart\Exceptions\InsufficientStockException; try { $manager->add($cart, $variant, quantity: 10); } catch (InsufficientStockException $exception) { return back()->with('error', __('Only :count left in stock.', [ 'count' => $exception->available, ])); } ``` The exception carries `purchasable` (the product or variant), `available` (its stock) and `requested` (the quantity asked for). This check reads the stock without holding it: two customers can put the last unit in their carts. Stock is held at checkout, as described in [Stock Reservation](#stock-reservation). The [Products](/3.x/products#stock-management) page explains how stock is counted. ## Order Conversion [#order-conversion] `CreateOrderFromCartAction` turns a cart into an order, in one database transaction that Laravel attempts up to three times when it hits a deadlock: ```php title="app/Http/Controllers/CheckoutController.php" use Shopper\Cart\Actions\CreateOrderFromCartAction; $order = resolve(CreateOrderFromCartAction::class)->execute($cart); ``` `execute()` accepts three optional closures that the Store API checkout uses: `assertTotals` receives the final `CartPipelineContext` and can throw to abort, `afterCreate` receives the new order inside the transaction, and `honoursPayment` tells whether a payment already collected must be honored when a price or a promotion changed. The [Payments](/3.x/payments) page covers that flow. ### What Happens [#what-happens] Inside the transaction, the action: 1. Locks the cart row with `FOR UPDATE` and throws `CartCompletedException` when the cart is already completed, so two checkouts of the same cart create one order. 2. On MySQL and MariaDB, locks the discount rows of the cart's promotions. 3. Prices every line again. A unit price that went up throws `PriceChangedException` with `was` and `now`; a price that went down is applied. A line without a price throws `MissingPriceException`, a quantity the [quantity rules](/3.x/pricing#quantity-rules) refuse throws `QuantityRuleViolationException`. 4. Runs the calculation pipeline and checks the terms of each applied promotion again, throwing `PromotionUnavailableException` when one no longer holds. 5. Copies the shipping and billing addresses to `OrderAddress` rows. 6. Creates the order with the total, tax and shipping amounts, the currency, email, customer, channel, zone, payment method and carrier option of the cart, and the discount of the promotion with the largest amount. 7. Creates one order item per line, with its name, SKU, quantity, unit price, discount and tax, and reserves stock for each line that tracks inventory. 8. Copies the tax lines of the cart to `OrderTaxLine` rows. 9. Records the use of each applied promotion, checks its usage limits and charges its campaign budget. 10. Sets `completed_at` and `order_id` on the cart and dispatches `CartCompleted` once the transaction commits. Any exception rolls the whole transaction back: no order, no stock movement, no promotion use. The [Orders](/3.x/orders) page covers the order that comes out. ### Discount Limit Exceptions [#discount-limit-exceptions] Usage limits are checked again at commit time, because another checkout may have used the last redemption since the cart was calculated. `Shopper\Cart\Exceptions\DiscountLimitReachedException::global()` is thrown when the discount reached its `usage_limit`, and `DiscountLimitReachedException::perUser()` when this customer, found by customer ID or by email for a guest, already used it. A campaign that cannot absorb the discount throws `Shopper\Core\Exceptions\CampaignBudgetExceededException`, as described in [Budgets](/3.x/campaigns#budgets). ```php title="app/Http/Controllers/CheckoutController.php" use Shopper\Cart\Exceptions\DiscountLimitReachedException; try { $order = resolve(CreateOrderFromCartAction::class)->execute($cart); } catch (DiscountLimitReachedException $exception) { return back()->with('error', $exception->getMessage()); } ``` The [Usage Limit Enforcement](/3.x/discounts#usage-limit-enforcement) section of the Discounts page explains the counters. ### Stock Reservation [#stock-reservation] Stock is reserved inside the transaction that creates the order, so two checkouts cannot both take the last unit. The action calls the `Shopper\Core\Contracts\StockReserver` contract for every line whose product or variant tracks inventory: ```php namespace Shopper\Core\Contracts; use Illuminate\Database\Eloquent\Model; use Shopper\Core\Models\Contracts\Stockable; interface StockReserver { public function reserve(Stockable $product, int $quantity, ?Model $reference = null, ?int $userId = null): int; } ``` The default implementation, `Shopper\Core\Stock\LockingStockReserver`, locks the product row, spreads the quantity over the [inventory locations](/3.x/locations) that hold stock, records the movements against the order, and returns the quantity reserved. When the stock is short, it reserves nothing and returns what was available; the action then throws `InsufficientStockException` and the order is rolled back. A product with `allow_backorder` takes the full quantity from its first inventory location, and its stock can go below zero. To reserve against an external warehouse system, bind your own implementation in a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Stock\WarehouseStockReserver; use Shopper\Core\Contracts\StockReserver; public function register(): void { $this->app->bind(StockReserver::class, WarehouseStockReserver::class); } ``` ## Abandoned Carts [#abandoned-carts] A cart is abandoned when it is not completed, has at least one line, and saw no activity for `shopper.cart.abandoned_after_minutes` (60 by default). Activity is read from the `updated_at` column of the cart row. Merchants see these carts in the admin panel, as described in [In the Admin](#in-the-admin); your code can query them to send recovery emails. ### Querying Abandoned Carts [#querying-abandoned-carts] Query the carts through the contract, so a swapped cart model is honored. This query keeps the carts of signed-in customers, the ones you can email: ```php title="app/Console/Commands/SendCartReminders.php" use Shopper\Cart\Models\Contracts\Cart; $abandoned = resolve(Cart::class)::query() ->whereNull('completed_at') ->whereHas('lines') ->whereNotNull('customer_id') ->where('updated_at', '<=', now()->subMinutes( (int) config('shopper.cart.abandoned_after_minutes') )) ->with(['customer', 'lines.purchasable']) ->get(); ``` A guest cart has no customer, but it has an `email` once the checkout collected one. ### Pruning [#pruning] The `shopper:prune-carts` command deletes the open carts not updated for `shopper.cart.prune_after_days` days (30 by default). Completed carts are kept with their orders. The `--days` option overrides the setting for one run: ```bash php artisan shopper:prune-carts php artisan shopper:prune-carts --days=7 ``` The cart package schedules the command daily, so you do not add it to `routes/console.php`; your application only needs the Laravel scheduler running. The command deletes in batches of 1,000, and the lines, addresses and promotions of each cart are deleted with it. ## Configuration [#configuration] The cart has no feature flag: the package is always installed with Shopper. Its settings live in `config/shopper/cart.php`, which `php artisan shopper:install` publishes with the other [configuration files](/3.x/configuration#configuration-files): | Key | Default | Purpose | |-----|---------|---------| | `pipelines.cart` | The five steps above | Steps of the [calculation pipeline](#calculation-pipeline) | | `max_promotions` | `5` | Most promotions applied to one cart | | `session.key` | `shopper_cart` | Session key of the current cart | | `session.auto_create` | `false` | Whether `Cart::current()` creates a cart when the session has none | | `abandoned_after_minutes` | `60` | Inactivity before a cart counts as [abandoned](#abandoned-carts) | | `totals_ttl_minutes` | `15` | How long `totals()` reuses the stored totals | | `prune_after_days` | `30` | Age of the open carts that `shopper:prune-carts` deletes | | `models.cart` | `Shopper\Cart\Models\Cart::class` | Cart model | | `models.cart_line` | `Shopper\Cart\Models\CartLine::class` | Cart line model | ### Model Swapping [#model-swapping] Extend `Shopper\Cart\Models\Cart` or `Shopper\Cart\Models\CartLine` and register your class under `models` in the same file: ```php title="config/shopper/cart.php" 'models' => [ 'cart' => App\Models\Cart::class, 'cart_line' => Shopper\Cart\Models\CartLine::class, ], ``` Shopper binds the contracts to the configured classes, so the session manager, the admin panel and the Store API load your model. The [Swapping the Cart Models](/3.x/models#swapping-the-cart-models) section of the Models page lists the rules. ## Usage [#usage] Resolve `CartManager` from the container, or inject it. Every method takes the cart as its first argument, and the methods that change the cart throw `CartCompletedException` once it is completed: ```php use Shopper\Cart\CartManager; $manager = resolve(CartManager::class); ``` ### Adding Items [#adding-items] `add()` takes any Eloquent model that implements `Shopper\Core\Contracts\Priceable`, a product or a variant, with an optional quantity and metadata. It prices the line in the currency of the cart through the [price resolver](/3.x/pricing#resolving-prices) and returns the `CartLine`: ```php title="app/Http/Controllers/CartLineController.php" use Shopper\Core\Models\Contracts\Product; $tshirt = resolve(Product::class)::query() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $line = $manager->add($cart, $tshirt, quantity: 2, metadata: [ 'gift_message' => 'Happy birthday!', ]); ``` Adding a product already in the cart raises the quantity of its line. The metadata must then match the line's, or the manager throws `CartLineMetadataConflictException`. A quantity below 1 throws an `InvalidArgumentException`, a product without a price in the cart currency throws `MissingPriceException`, and a quantity the quantity rules refuse throws `QuantityRuleViolationException`. When a new quantity moves another line into a different price tier, the manager prices that line again. ### Updating a Line [#updating-a-line] `update()` takes the line ID and a quantity, metadata, or both: ```php $manager->update($cart, $line->id, ['quantity' => 3]); $manager->update($cart, $line->id, ['metadata' => ['gift_message' => 'Congratulations!']]); ``` A new quantity goes through the same stock and quantity rule checks as `add()`. ### Removing Lines [#removing-lines] `remove()` deletes one line and `clear()` deletes them all: ```php $manager->remove($cart, $line->id); $manager->clear($cart); ``` ### Applying Coupons [#applying-coupons] `applyCoupon()` attaches the discount with that code to the cart. It throws `InvalidDiscountException` when no discount has the code. Whether the code discounts anything is decided at the next calculation, as described in [Promotions](#promotions): ```php title="app/Http/Controllers/CouponController.php" use Shopper\Cart\Exceptions\InvalidDiscountException; try { $manager->applyCoupon($cart, 'SUMMER20'); } catch (InvalidDiscountException $exception) { return back()->with('error', $exception->getMessage()); } $manager->removeCoupon($cart, 'SUMMER20'); ``` `removeCoupon()` without a code removes every code of the cart. When a guest cart passes to a signed-in customer, the manager calls `revalidateCoupons()`, which drops the codes that no longer validate for that customer. ### Adding Addresses [#adding-addresses] `addAddress()` creates the address of a type, or updates it when the cart already has one: ```php title="app/Http/Controllers/CheckoutController.php" use Shopper\Core\Enum\AddressType; $manager->addAddress($cart, AddressType::Shipping, [ 'first_name' => 'Jane', 'last_name' => 'Cooper', 'address_1' => '350 Fifth Avenue', 'city' => 'New York', 'state' => 'NY', 'postal_code' => '10118', 'country_id' => $country->id, ]); $manager->setEmail($cart, 'jane@example.com'); ``` ### Shipping and Payment [#shipping-and-payment] `setShippingMethod()` stores the chosen shipping option and its price in cents. The option ID has the form `{carrier_code}:{service_code}`, as the shipping options of the cart return it; compute the price on the server, as described in [Calculating Shipping Rates](/3.x/carriers#calculating-shipping-rates). `removeShippingMethod()` clears it. `setPaymentMethod()` takes the ID of one of the [payment methods](/3.x/payment-methods) of the zone: ```php $manager->setShippingMethod($cart, 'ups:03', 899); $manager->setPaymentMethod($cart, $paymentMethod->id); ``` When a change moves the total of a cart that holds a provider payment session, the manager releases that session, so the customer is never charged an outdated amount. ### Calculating Totals [#calculating-totals] `calculate()` runs the pipeline and returns the `CartPipelineContext`; `totals()` returns the same object from the stored rows when they are recent, as described in [Stored Totals](#stored-totals): ```blade title="resources/views/cart/summary.blade.php" @php($totals = app(\Shopper\Cart\CartManager::class)->totals($cart))
    Subtotal
    {{ shopper_money_format($totals->subtotal, $cart->currency_code) }}
    @if ($totals->discountTotal > 0)
    Discount
    -{{ shopper_money_format($totals->discountTotal, $cart->currency_code) }}
    @endif
    Shipping
    {{ shopper_money_format($totals->shippingTotal, $cart->currency_code) }}
    {{ $totals->taxInclusive ? 'Including tax' : 'Tax' }}
    {{ shopper_money_format($totals->taxTotal, $cart->currency_code) }}
    Total
    {{ shopper_money_format($totals->total, $cart->currency_code) }}
    ``` ### Changing the Currency or the Zone [#changing-the-currency-or-the-zone] `changeCurrency()` prices every line again in the new currency and clears the shipping choice; a line without a price in that currency throws `MissingPriceException` and nothing changes. `changeContext()` sets a new zone and channel, clears the shipping and payment choices, and prices the lines again, dispatching `CartLinesRepriced` when a unit price changed: ```php $manager->changeCurrency($cart, 'EUR'); $manager->changeContext($cart, zoneId: $zone->id, channelId: $cart->channel_id); ``` `reprice()` prices the lines again without changing the currency, the zone or the shipping choice, dispatches `CartLinesRepriced` when a unit price changed, and returns those changes, each with `line`, `from` and `to`. ### Associating Cart on Login [#associating-cart-on-login] When a guest signs in, give the session cart to the customer from a `Login` listener: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Event; use Shopper\Cart\Facades\Cart; public function boot(): void { Event::listen(Login::class, fn (Login $event) => Cart::associate($event->user)); } ``` `associate()` calls `CartManager::transfer()`. When the customer already has an open cart, the guest cart is merged into it: lines of the same product or variant add up, the other lines and the codes move over, the guest cart is deleted, and the session points to the customer's cart. Otherwise the customer takes the guest cart. Either way the lines are priced again for the customer and the codes that no longer apply are dropped. When the guest cart is completed or belongs to another customer, `associate()` forgets it. `merge($source, $target)` is available on its own for other flows. ### Custom Line Prices [#custom-line-prices] `setLinePrice()` sets the unit price of a line by hand, for a price your application decides, such as a negotiated quote. The line is then locked: its quantity cannot change and a currency change throws `CartLineLockedException`. `clearLinePrice()` returns the line to the resolved price: ```php $manager->setLinePrice($cart, $line->id, 1999); $manager->clearLinePrice($cart, $line->id); ``` A negative amount throws an `InvalidArgumentException`. Call these methods from trusted code only, never with an amount taken from the customer's request. ### Completed Cart Guard [#completed-cart-guard] Once `completed_at` is set, every method that changes the cart throws `Shopper\Cart\Exceptions\CartCompletedException`, and `Cart::current()` stops returning it. The order holds the record of the purchase from then on. ```php use Shopper\Cart\Exceptions\CartCompletedException; try { $manager->add($cart, $tshirt); } catch (CartCompletedException) { Cart::forget(); } ``` ### Converting to Order [#converting-to-order] At the end of the checkout, convert the cart and clear the session: ```php title="app/Http/Controllers/CheckoutController.php" use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Facades\Cart; $order = resolve(CreateOrderFromCartAction::class)->execute(Cart::current() ?? abort(404)); Cart::forget(); return redirect()->route('orders.confirmation', $order); ``` The [Order Conversion](#order-conversion) section lists the exceptions to catch. A store that takes payment online opens a payment session before this step, as the [Payments](/3.x/payments) page describes. ## Events [#events] The cart dispatches four events from `Shopper\Cart\Events`: `CartCompleted` when the checkout creates the order, `CouponApplied` and `CouponRemoved` when a code is added or removed, and `CartLinesRepriced` when unit prices change. The [Cart and Discount Events](/3.x/events#cart-and-discount-events) section of the Events page lists their payloads and the exact moments they fire. ```php title="app/Providers/AppServiceProvider.php" use App\Notifications\OrderReceived; use Illuminate\Support\Facades\Event; use Shopper\Cart\Events\CartCompleted; public function boot(): void { Event::listen(CartCompleted::class, function (CartCompleted $event): void { $event->cart->customer?->notify(new OrderReceived($event->order)); }); } ``` `CartCompleted` is also an outgoing [webhook](/3.x/webhooks) event, `cart.completed`. ## Permissions [#permissions] The cart has no permission of its own. The admin panel checks `orders.browse` before it shows the Abandoned Carts page, its sidebar item and the detail of a cart. The [Access by Section](/3.x/acl#access-by-section) table of the Access Control page lists the permissions of the Orders section. ## In the Admin [#in-the-admin] Merchants find the carts that did not reach checkout under Orders, Abandoned Carts. The list shows each cart with its customer (or "Guest"), its items, its channel and its last activity, newest first, and opens a slide-over with the lines and the addresses of the cart. The page is read-only: carts are created and changed by the storefront. The [User Guide](/3.x/user-guide) walks through the orders screens. ## From a Storefront [#from-a-storefront] The Store API exposes the cart under the `store` prefix, set by `SHOPPER_API_PREFIX`. A cart and its lines are addressed by their public IDs. Every route works for guests except the transfer, which needs a signed-in customer: | Endpoint | Does | |----------|------| | `POST /store/carts` | Creates a cart with an optional `currency_code`, `email` and `metadata`, in the zone and channel of the request | | `GET /store/carts/{cartId}` | Returns the cart. Add `include=lines`, `lines.purchasable`, `lines.purchasable.product`, `addresses` or `paymentMethod` | | `PATCH /store/carts/{cartId}` | Changes `currency_code`, `zone_code`, `email` or `metadata` | | `POST /store/carts/{cartId}/lines` | Adds a line from `purchasable_type` (`product` or `variant`), `purchasable_id`, `quantity` and `metadata` | | `PATCH /store/carts/{cartId}/lines/{lineId}` | Changes the quantity or the metadata of a line | | `DELETE /store/carts/{cartId}/lines/{lineId}` | Removes a line | | `POST /store/carts/{cartId}/addresses` | Sets `shipping_address`, `billing_address` and `email` | | `POST /store/carts/{cartId}/promotion` | Applies a discount `code` | | `DELETE /store/carts/{cartId}/promotion` | Removes a code, or every code when the request names none | | `GET /store/carts/{cartId}/shipping-options` | Lists the shipping options and their rates | | `POST /store/carts/{cartId}/shipping-method` | Chooses a shipping option by `option_id` | | `GET /store/carts/{cartId}/payment-methods` | Lists the enabled payment methods, limited to the cart's zone when it has one | | `POST /store/carts/{cartId}/payment-method` | Chooses a payment method | | `POST /store/carts/{cartId}/payment-session` | Opens a payment session with the provider | | `POST /store/carts/{cartId}/complete` | Converts the cart into an order | | `POST /store/carts/{cartId}/transfer` | Gives a guest cart to the signed-in customer, merging it into their open cart | A cart resource has the type `carts` and carries `currency_code`, `email`, `promotions` (each with `code`, `source`, `amount` and a `status` of `applied` or `suppressed`), `completed_at`, `metadata`, `lines_count`, `lines_quantity`, `subtotal`, `discount_total`, `tax_total`, `shipping_total`, `total`, `tax_inclusive`, `shipping_option_id`, `created_at` and `updated_at`, with the `lines`, `addresses` and `paymentMethod` relationships. Amounts are in cents. The promotion endpoint applies a code only when it discounts the cart and answers with the same error for every code it refuses. The Store API [Cart](/3.x/store-api/cart) guide covers these endpoints. # Categories (/3.x/categories) Categories organize the catalog into a tree that customers browse: Electronics, then Computers, then Laptops. A category can have a parent and any number of children, with no depth limit, and a product can belong to several categories at once. A storefront builds its navigation menu, its category pages and its breadcrumbs from this tree. ## Model [#model] The model configured for categories is `Shopper\Models\Category`. It extends `Shopper\Core\Models\Category` and implements the `Shopper\Core\Models\Contracts\Category` contract. The core class holds the columns, the tree and the scopes; the admin class adds the media collections and image conversions, as described in [Core Models and Admin Models](/3.x/models#core-models-and-admin-models). Five traits of the core class change what you can do with a category: - `HasRecursiveRelationships`, from the [laravel-adjacency-list](https://github.com/staudenmeir/laravel-adjacency-list) package, adds the tree relationships and scopes listed in [Available Tree Methods](#available-tree-methods). - `HasSlug` turns the `slug` you assign into a URL-safe value and appends `-1`, `-2` and so on when it is already taken. Child categories follow an extra rule, described in [Custom Paths & Slug Behavior](#custom-paths--slug-behavior). - `HasPublicId` fills `public_id` with a ULID when the category is created. The Store API returns it as the category `id`. - `HasMediaCollections` declares the image collections described in [Media](#media). - `Searchable` sends visible categories to the search index. The [Search](/3.x/search) page covers indexing. ### Extending the Model [#extending-the-model] To add your own methods, extend the admin class: ```php title="app/Models/Category.php" where('metadata->featured_on_homepage', true); } } ``` Then point the `category` key of the configuration to your class: ```php title="config/shopper/models.php" 'category' => App\Models\Category::class, ``` The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ## Database Schema [#database-schema] Categories are stored in the `sh_categories` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Category name | | `slug` | string | yes | null | URL identifier, unique across all categories | | `description` | longtext | yes | null | Category description, HTML from the admin rich editor | | `position` | smallint (unsigned) | no | 0 | Order among the categories of the same parent | | `is_enabled` | boolean | no | false | Whether the category is shown on the storefront | | `seo_title` | string(60) | yes | null | Title for search engines | | `seo_description` | string(160) | yes | null | Description for search engines | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `parent_id` | bigint | yes | null | Parent category. Deleting the parent sets it to `null` | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The slug of a top-level category is not derived from the name in code. The admin form fills it from the name when the field is left empty; when you create a top-level category in your own code, pass a slug, because the Store API finds categories by their slug. ## Hierarchical Structure [#hierarchical-structure] Each category stores the ID of its parent in `parent_id`, and a category without a parent sits at the top of the tree. Nothing limits the depth: ```text Electronics Computers Laptops Desktops Phones Smartphones Audio ``` Products are attached to any category of the tree, at any depth. Shopper does not copy a product to the parents of its category: browsing Electronics returns the products of Laptops only when you query the whole branch, as shown in [Working with Products](#working-with-products). ### Visibility and Depth [#visibility-and-depth] A category is visible to customers when it is enabled and every one of its ancestors is enabled too. Disabling Computers hides Laptops and Desktops from the storefront, even though both stay enabled in the admin panel. `Shopper\Core\Queries\CategoryTree` applies this rule. It reads the `id`, `parent_id` and `is_enabled` columns of every category, then keeps the depth of each visible category (0 for a top-level category) and the list of hidden ones. The Store API, the `category` and `categoryTree` product scopes and the search index all read it, so a hidden category is never returned, filtered on or indexed: ```php use Shopper\Core\Queries\CategoryTree; $tree = resolve(CategoryTree::class); $tree->depth($laptops->id); $tree->hiddenIds(); ``` `depth()` returns `null` for a hidden category. `enabledSubtreeIds()`, on the model, returns the IDs of a category and of its visible descendants, or an empty collection when the category itself is hidden: ```php $ids = $electronics->enabledSubtreeIds(); ``` Shopper caches this data, as described in [Tree Cache](#tree-cache). ### Ordering [#ordering] The `position` column orders the categories that share a parent. The reorder panel of the admin panel numbers them from 1 under each parent, and the Store API returns the tree in that order. Add `orderBy('position')` to your own queries for the same order. ### Moving Categories [#moving-categories] To move a category, change its `parent_id`. Set it to `null` to make the category top-level: ```php $laptops->update(['parent_id' => $electronics->id]); ``` A category cannot move under itself or under one of its descendants: the update throws a `RuntimeException` with the message "A category cannot be moved under one of its own descendants." Moving a category also changes its slug when the new parent is a category, as described in [Custom Paths & Slug Behavior](#custom-paths--slug-behavior). Deleting a category makes its direct children top-level. Its products stay, and no longer list it among their categories. ## Media [#media] Categories have the same two media collections as brands, named in `config/shopper/media.php`: | Collection | Config key | Default name | Files | Use | |------------|------------|--------------|-------|-----| | Images | `shopper.media.storage.collection_name` | `uploads` | Several | Extra category images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | `thumbnail` | One | The image shown in menus and category listings | The admin form uploads the image to the thumbnail collection, up to `shopper.media.max_size.thumbnail` kilobytes (1024 by default). Both collections accept the MIME types listed in `shopper.media.accepts_mime_types`: JPEG, PNG, WebP and AVIF. Each upload gets the conversions of `shopper.media.conversions`, `large` (800x800) and `medium` (500x500) by default. ```php $laptops->addMedia($request->file('image')) ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); $imageUrl = $laptops->getThumbnailUrl('medium'); ``` `getThumbnailUrl()` falls back to the first image of the images collection, then to the placeholder image of the admin panel. When the conversion you ask for has not been generated yet, it returns the original. The [Media](/3.x/media) page covers storage disks, conversions and the placeholder image. ## Relationships [#relationships] The tree relationships come from the adjacency list package and return your category class after a swap. The products relationship reads the product class from `config('shopper.models.product')`. ### Parent Category [#parent-category] `parent` returns the category one level up, or `null` for a top-level category. For a breadcrumb, load the `ancestors` ordered by depth, which starts at the top of the tree: ```php $laptops->parent; $breadcrumb = $laptops->ancestors()->orderBy('depth')->get(); ``` ### Child Categories [#child-categories] `children` returns the categories one level down. Constrain it like any relationship to keep the enabled ones in their order: ```php $subcategories = $electronics->children() ->enabled() ->orderBy('position') ->get(); ``` ### Descendant Categories [#descendant-categories] `descendants` returns every category below a category, at any depth, and `descendantsAndSelf` adds the category itself: ```php $electronics->descendants; $electronics->descendants()->count(); $electronics->descendantsAndSelf()->pluck('id'); ``` These relationships ignore visibility. To keep the visible branch only, use `enabledSubtreeIds()`, described in [Visibility and Depth](#visibility-and-depth). `descendantCategories()`, declared on the contract, does not return the descendants of a category: it matches every category that has a parent. Use `descendants()`. ### Products [#products] `products()` is a polymorphic many-to-many relation through the `sh_product_has_relations` table. It returns the products attached to this category only, without those of its descendants: ```php $laptops->products; $laptops->products()->publish()->count(); ``` From the product side, `categories()` returns the categories of a product. Attach a product to one or several categories with `attach()` or `sync()`: ```php $product->categories()->sync([$laptops->id, $computers->id]); ``` ## Available Tree Methods [#available-tree-methods] The adjacency list package adds these relationships to the model: | Method | Returns | |--------|---------| | `ancestors()` | The parents of the category, up to the top of the tree | | `ancestorsAndSelf()` | The ancestors and the category itself | | `bloodline()` | The ancestors, the descendants and the category itself | | `children()` | The direct children | | `childrenAndSelf()` | The direct children and the category itself | | `descendants()` | Every category below, at any depth | | `descendantsAndSelf()` | The descendants and the category itself | | `parent()` | The direct parent | | `parentAndSelf()` | The direct parent and the category itself | | `rootAncestor()` | The top-level ancestor | | `rootAncestorOrSelf()` | The top-level ancestor, or the category itself when it is top-level | | `siblings()` | The other children of the same parent | | `siblingsAndSelf()` | Every child of the same parent | The package also adds query scopes. `tree()` loads every category with a `depth` column, starting from the top-level categories; pass a number to stop at a depth, such as `tree(1)` for the top-level categories and their children. `isRoot()` and `isLeaf()` keep the categories without a parent or without children, `hasChildren()` the ones with children, and `whereDepth()` filters a `tree()` query by depth. On a collection, `toTree()` nests each category under its parent in a `children` relation. ```php use Shopper\Core\Models\Contracts\Category; $firstTwoLevels = resolve(Category::class)::query() ->tree(1) ->orderBy('position') ->get() ->toTree(); ``` ## Query Scopes [#query-scopes] The model has one scope of its own; the adjacency list package and the traits add the others. ### Enabled Categories [#enabled-categories] The `enabled` scope keeps the categories whose `is_enabled` column is `true`. It checks the category itself, not its ancestors: use the [category tree](#visibility-and-depth) when a disabled parent must hide its children. ```php use Shopper\Core\Models\Contracts\Category; $categories = resolve(Category::class)::query() ->enabled() ->orderBy('position') ->get(); ``` ### Root Categories [#root-categories] The `isRoot` scope keeps the top-level categories: ```php $topLevel = resolve(Category::class)::query() ->isRoot() ->enabled() ->orderBy('position') ->get(); ``` ## Custom Paths & Slug Behavior [#custom-paths--slug-behavior] The model declares a custom path named `slug_path`, which joins the slugs of a category and its ancestors with `/`. The path is built by the tree query, so it exists on the rows loaded with `tree()`; a category loaded with `find()` or `where()` has no `slug_path`. When a category has a parent, `Shopper\Core\Observers\CategoryObserver` replaces its slug, on every create and update, with the slug of the parent followed by the category name. Because the slug of the parent already carries its own parent, slugs grow with each level: | Category | Parent | Slug | `slug_path` | |----------|--------|------|-------------| | Electronics | none | `electronics` | `electronics` | | Computers | Electronics | `electronics-computers` | `electronics/electronics-computers` | | Laptops | Computers | `electronics-computers-laptops` | `electronics/electronics-computers/electronics-computers-laptops` | This rule has three consequences for your code: - The slug you pass when you create or update a child category is replaced. Only top-level categories keep the slug you choose. - Moving a category under another parent changes its slug, and so its storefront URL. Its children keep their slugs until they are saved again. - A category moved to the top level keeps the slug it had under its former parent. Slugs are unique across all categories, so the slug alone identifies a category. Build category URLs from it, such as `/categories/electronics-computers-laptops`, the way the Store API looks categories up. ## Methods & Helpers [#methods--helpers] The model adds three helpers to the relationships and scopes. ### Find by Slug [#find-by-slug] `findBySlug()` returns the category with that slug, and throws a `ModelNotFoundException` when there is none: ```php use Shopper\Core\Models\Contracts\Category; $laptops = resolve(Category::class)::findBySlug('electronics-computers-laptops'); ``` It does not check visibility. `findByPublicId()` looks a category up by its public ID and returns `null` when there is none. ### Label with Path [#label-with-path] `getLabelOptionName()` returns the names of the ancestors and of the category, separated by ` / `. For Laptops, it returns `Electronics / Computers / Laptops`. The admin panel uses it in the parent select of the category form: ```php $laptops->getLabelOptionName(); ``` ### Status Management [#status-management] `updateStatus()` enables a category, or disables it when you pass `false`. It saves the change immediately: ```php $computers->updateStatus(); $computers->updateStatus(false); ``` Disabling a category hides its whole branch from the storefront, as described in [Visibility and Depth](#visibility-and-depth). Once the change is committed, Shopper updates the search index for the category, its descendants and their products. The products of a hidden category stay published and reachable through their other categories. ## Configuration [#configuration] Categories are on by default. Their settings are the feature flag, the tree cache, the model key and the admin components. ### Disabling Category Feature [#disabling-category-feature] If your store does not use categories, disable the feature in `config/shopper/features.php`: ```php title="config/shopper/features.php" 'category' => Shopper\Enum\FeatureState::Disabled, ``` The categories page is no longer registered, the Categories item leaves the sidebar, and the categories field of the product forms is hidden. The flag only changes the admin panel: the model, the product relation and the Store API category endpoints stay available. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Tree Cache [#tree-cache] The data of `CategoryTree` is cached for the number of seconds set in `config/shopper/core.php`: ```php title="config/shopper/core.php" 'cache' => [ 'category_tree' => 3600, ], ``` Saving or deleting a category through the model refreshes the cache, so the duration only matters for changes made another way, such as a `DB::table()` update or an import that writes to the table directly. Call `Shopper\Core\Queries\CategoryTree::flush()` after such a change, or set the value to `null` to read the tree from the database on every request. ### Components [#components] The categories section of the admin panel is made of one page, the category form and the reorder panel. To replace one with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish category ``` The command creates `config/shopper/components/category.php`: ```php title="config/shopper/components/category.php" use Shopper\Livewire; return [ 'pages' => [ 'category-index' => Livewire\Pages\Category\Index::class, ], 'components' => [ 'slide-overs.category-form' => Livewire\SlideOvers\CategoryForm::class, 'slide-overs.re-order-categories' => Livewire\SlideOvers\ReOrderCategories::class, ], ]; ``` The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below resolve the category class from its contract, so they keep working after you swap the model. ### Creating Categories [#creating-categories] Create a top-level category with its slug, then its children with a `parent_id`: ```php use Shopper\Core\Models\Contracts\Category; $electronics = resolve(Category::class)::query()->create([ 'name' => 'Electronics', 'slug' => 'electronics', 'position' => 1, 'is_enabled' => true, 'seo_title' => 'Electronics: computers, phones and audio', ]); $computers = resolve(Category::class)::query()->create([ 'name' => 'Computers', 'parent_id' => $electronics->id, 'position' => 1, 'is_enabled' => true, ]); ``` The slug of Computers is `electronics-computers`, built from its parent as described in [Custom Paths & Slug Behavior](#custom-paths--slug-behavior). ### Retrieving Categories [#retrieving-categories] For a navigation menu, load the tree, keep the enabled categories and nest them. `toTree()` drops a category whose parent is not in the collection, so a disabled category takes its whole branch out of the menu: ```php use Shopper\Core\Models\Contracts\Category; $menu = resolve(Category::class)::query() ->tree() ->enabled() ->orderBy('position') ->get() ->toTree(); ``` For a category page, exclude the hidden categories, then load the breadcrumb and the visible subcategories: ```php use Shopper\Core\Models\Contracts\Category; use Shopper\Core\Queries\CategoryTree; $category = resolve(Category::class)::query() ->whereKeyNot(resolve(CategoryTree::class)->hiddenIds()) ->where('slug', 'electronics-computers') ->firstOrFail(); $breadcrumb = $category->ancestors()->orderBy('depth')->get(); $subcategories = $category->children() ->enabled() ->orderBy('position') ->get(); ``` ### Updating Categories [#updating-categories] Update a category like any Eloquent model. Changing `parent_id` moves it, with the rules of [Moving Categories](#moving-categories): ```php $computers->update([ 'seo_title' => 'Laptops and desktop computers', 'seo_description' => 'Shop laptops, desktops and computer accessories.', ]); ``` ### Working with Products [#working-with-products] The product model has two scopes for categories. Both take slugs or public IDs and ignore hidden categories. `category` matches the products attached to the given categories, and `categoryTree` matches the products of the given categories and of all their visible descendants: ```php use Shopper\Core\Models\Contracts\Product; $laptopsOnly = resolve(Product::class)::query() ->publish() ->category('electronics-computers-laptops') ->get(); $wholeBranch = resolve(Product::class)::query() ->publish() ->categoryTree('electronics') ->latest('published_at') ->paginate(24); ``` Use `categoryTree` for a category page that lists the products of its subcategories: browsing Electronics then returns the products of Computers, Laptops and Phones. ### Metadata [#metadata] The `metadata` column stores data that has no column of its own, cast to an array. The admin form edits it as a list of keys and values: ```php $electronics->update([ 'metadata' => [ 'banner_color' => '#FF6B35', 'featured_on_homepage' => true, ], ]); $color = $electronics->metadata['banner_color'] ?? null; ``` The Store API returns `metadata` with the category, so keep data the customers must not see out of it. ### Storefront Example [#storefront-example] A controller for the category menu and a category page. The page lists the products of the whole branch, so browsing Electronics also shows the laptops: ```php title="app/Http/Controllers/CategoryController.php" tree() ->enabled() ->orderBy('position') ->get() ->toTree(); return view('categories.index', ['categories' => $categories]); } public function show(string $slug): View { $category = resolve(Category::class)::query() ->whereKeyNot(resolve(CategoryTree::class)->hiddenIds()) ->where('slug', $slug) ->firstOrFail(); $products = resolve(Product::class)::query() ->publish() ->categoryTree($category->slug) ->latest('published_at') ->paginate(12); return view('categories.show', [ 'category' => $category, 'breadcrumb' => $category->ancestors()->orderBy('depth')->get(), 'products' => $products, ]); } } ``` A store that sells on several channels adds the `channel` scope to the product query, as shown in [Channels](/3.x/channels). ## Events [#events] Shopper dispatches no category event of its own. Listen to the Eloquent model events instead. They are dispatched under the core class name as well, so a listener registered on `Shopper\Core\Models\Category` keeps firing after you swap the model: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Category; public function boot(): void { Category::saved(fn () => Cache::forget('storefront.menu')); Category::deleted(fn () => Cache::forget('storefront.menu')); } ``` Shopper registers `Shopper\Core\Observers\CategoryObserver` on the category model. It sets the slug of child categories, refuses a move under a descendant, refreshes the tree cache, and once the transaction is committed updates the search index of the category, its descendants and their products when the name, the status or the parent changes, or when the category is deleted. The reorder panel of the admin panel saves a position change within the same parent without firing model events. A listener on `saved` runs only when a category moves to another parent. The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks four permissions of the `categories` resource, in the Catalog group: | Permission | Allows | |------------|--------| | `categories.browse` | Opening the categories page and seeing the Categories sidebar item | | `categories.create` | Opening and saving the form for a new category | | `categories.edit` | Editing a category, enabling and disabling categories in bulk, opening the reorder panel and saving the new order | | `categories.delete` | Deleting a category, one at a time or in bulk | `categories.read` is seeded with the others, but the admin panel never checks it. Shopper 2.x named these permissions `browse_categories`, `add_categories` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants manage categories under Catalog, Categories. The page lists each category with its image, name, slug, visibility and last update, and filters by visibility. Bulk actions enable, disable or delete the selected categories. The Reorder button opens a panel where merchants drag categories to change their order and their parent. The category form opens in a slide-over with four sections: General (name, slug, parent, visibility, description), Media, SEO and Metadata. The parent select lists enabled categories only. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the visible categories under the `store` prefix, set by `SHOPPER_API_PREFIX`. A category hidden by a disabled ancestor is left out of every response: | Endpoint | Returns | |----------|---------| | `GET /store/categories` | The visible categories, paginated. Filter with `filter[name]` (partial match), sort with `sort=name` or `sort=position` | | `GET /store/categories/tree` | The whole visible tree in one response, ordered by position, without pagination | | `GET /store/categories/{slug}` | One visible category | A category resource has the type `categories` and carries `name`, `slug`, `description`, `position`, `parent_id` (the public ID of the parent), `is_enabled`, `depth`, `seo_title`, `seo_description`, `metadata`, `thumbnail`, `created_at` and `updated_at`. The listing and the single category accept these includes: | Include | Returns | |---------|---------| | `parent` | The parent, when it is enabled | | `children` | The enabled children | | `ancestors` | The enabled ancestors, starting at the top of the tree, for a breadcrumb | | `products` | The products attached to the category itself, published on the channel of the request | | `products_count` | A `products_count` attribute: the published products of the category and its visible descendants on the channel, each counted once | The tree endpoint returns plain JSON rather than JSON:API resources, so a menu loads in one call. Each node has `id`, `name`, `slug`, `position` and `children`: ```bash curl "https://example.com/store/categories/tree" ``` The response nests each category in the `children` of its parent: ```json { "data": [ { "id": "01JZ8Q2M4T6V8X0Z2B4D6F8H0K", "name": "Electronics", "slug": "electronics", "position": 1, "children": [ { "id": "01JZ8Q2M4T6V8X0Z2B4D6F8H0M", "name": "Computers", "slug": "electronics-computers", "position": 1, "children": [] } ] } ] } ``` On the products endpoint, `filter[category]` matches the products of the given categories and `filter[category_tree]` adds the products of their descendants, like the scopes of the same name. Both accept slugs or public IDs separated by commas, and `include=categories` returns the visible categories of each product: ```bash curl "https://example.com/store/products?filter[category_tree]=electronics&include=categories" ``` The products and the counts follow the channel of the request, as described in [Channels](/3.x/channels#the-store-api); the categories themselves are not filtered by channel. The Store API [Catalog](/3.x/store-api/catalog#categories) guide covers the category endpoints and the tree. # Channels (/3.x/channels) A channel is a place where the store sells: the website, a mobile app, a marketplace, a physical shop or a wholesale portal. Each product is attached to the channels it is sold on. The admin panel uses channels to choose where a product is available and to tell orders apart, and the Store API uses them to show each storefront only its own products. ## Model [#model] The model is `Shopper\Core\Models\Channel`. It implements the `Shopper\Core\Models\Contracts\Channel` contract. Two of its traits change how you create and find channels: - `HasSlug` turns the `slug` you assign into a URL-safe value and appends `-1`, `-2` and so on when it is already taken. The slug is not derived from the name: pass one when you create a channel, because the Store API finds channels by their slug. - `HasPublicId` fills `public_id` with a ULID when the channel is created. The model can be swapped through the `channel` key of `config/shopper/models.php`. ### Extending the Model [#extending-the-model] To add your own methods, extend the model: ```php title="app/Models/Channel.php" namespace App\Models; use Shopper\Core\Models\Channel as ShopperChannel; class Channel extends ShopperChannel { public function isMobileApp(): bool { return $this->slug === 'mobile-app'; } } ``` Then point the configuration to your class: ```php title="config/shopper/models.php" 'channel' => App\Models\Channel::class, ``` Shopper binds the contract to the configured class, so `resolve(Shopper\Core\Models\Contracts\Channel::class)`, `$product->channels` and `$order->channel` all return your model. The [Models](/3.x/models) page explains how swapping works. ## Database Schema [#database-schema] Channels are stored in the `sh_channels` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Channel name | | `slug` | string | yes | null | Unique identifier sent in the `X-Shopper-Channel` header | | `description` | text | yes | null | Channel description | | `timezone` | string | yes | null | Stored for your own code, Shopper does not read it | | `url` | string | yes | null | Address of the channel, shown on the settings page | | `driver` | string | yes | null | Code of the [channel driver](#channel-drivers); `null` means `web` | | `is_default` | boolean | no | false | Default channel flag | | `is_enabled` | boolean | no | false | Whether the channel is active | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Relationships [#relationships] A channel is linked to the products it sells through a polymorphic pivot table, and every order or cart records the channel it was placed on. ### Products [#products] Channels and products are linked through the polymorphic `sh_product_has_relations` table, which also links products to categories and collections. The relation works from both sides: ```php use Shopper\Core\Models\Channel; use Shopper\Core\Models\Product; $channel = Channel::findBySlug('mobile-app'); $channel->products; $channel->products()->attach([$sneakers->id, $hoodie->id]); $channel->products()->detach($hoodie->id); $channel->products()->sync($productIds); $product = Product::query()->where('slug', 'classic-t-shirt')->first(); $product->channels; ``` ### Orders and Carts [#orders-and-carts] Orders and carts carry a nullable `channel_id` column and a `channel()` relation. Deleting a channel sets the column to `null` on its orders and carts. The channel model has no inverse relation, so query orders by the column: ```php use Shopper\Core\Models\Channel; use Shopper\Core\Models\Order; $mobileApp = Channel::findBySlug('mobile-app'); $mobileOrders = Order::query() ->where('channel_id', $mobileApp->id) ->count(); ``` ## Query Scopes [#query-scopes] The model has a `default` and an `enabled` scope: ```php use Shopper\Core\Models\Channel; $default = Channel::query()->default()->first(); $channels = Channel::query()->enabled()->orderBy('name')->get(); $channels = Channel::query() ->enabled() ->withCount('products') ->get(); ``` The traits add lookups by slug and by public ID. `findBySlug()` throws a `ModelNotFoundException` when no channel matches, `findByPublicId()` returns `null`: ```php use Shopper\Core\Models\Channel; $webStore = Channel::findBySlug('web-store'); $mobileApp = Channel::findByPublicId('01JZ8Q4X7M2N3P5R6S7T8V9W0Y'); ``` ## Default Channel [#default-channel] The installer runs `Shopper\Core\Database\Seeders\ShopperSeeder`, which calls `ChannelSeeder`. It creates one channel, enabled and marked as default: | Attribute | Value | |-----------|-------| | `name` | Web Store | | `slug` | `web-store` | | `url` | `config('app.url')` | | `driver` | `null` (the `web` driver) | `Shopper\Core\Observers\ChannelObserver` keeps two rules each time a channel is created or updated: - Only one channel is the default. Saving a channel with `is_default` set to `true` removes the flag from the previous default. - The default channel is always enabled. Its `is_enabled` is forced to `true`. To make the mobile app the default channel: ```php use Shopper\Core\Models\Channel; Channel::findBySlug('mobile-app')->update(['is_default' => true]); ``` The previous default loses its flag without firing model events. The admin panel uses the default channel in two places: the Add product form selects it for every new product, and the settings page lists it first with its status toggle locked. The Store API does not read `is_default`. A request without a channel header falls back to the slug in `SHOPPER_API_DEFAULT_CHANNEL`, as described in [The Store API](#the-store-api). ## Creating Channels [#creating-channels] The settings page lists channels and turns them on and off. It has no form to create or edit a channel, so create them in code, for example in a seeder of your application: ```php title="database/seeders/ChannelSeeder.php" namespace Database\Seeders; use Illuminate\Database\Seeder; use Shopper\Core\Models\Channel; class ChannelSeeder extends Seeder { public function run(): void { Channel::query()->create([ 'name' => 'Mobile app', 'slug' => 'mobile-app', 'description' => 'iOS and Android app', 'url' => 'https://apps.apple.com/app/id6741234567', 'is_enabled' => true, 'metadata' => [ 'ios_app_id' => '6741234567', 'android_package' => 'com.example.shop', ], ]); } } ``` `is_enabled` defaults to `false`: a channel created without it stays disabled until someone turns it on from the settings page. The model has no guarded attributes, so every column can be filled with `create()`. Use `metadata` for the data your own code needs per channel, such as the store identifiers above: ```php $androidPackage = Channel::findBySlug('mobile-app')->metadata['android_package'] ?? null; ``` ## Channel Drivers [#channel-drivers] A driver describes the platform a channel sells on: its name, its logo, and whether it has what it needs to work, such as API credentials. The admin panel reads the driver to show the logo and the driver badge on the settings page and the logo next to each channel in the product form. Shopper ships one driver, `web` (`Shopper\Core\Channel\Drivers\WebDriver`). A channel whose `driver` column is `null` uses it. ### Writing a Driver [#writing-a-driver] A driver implements `Shopper\Core\Channel\Contracts\ChannelDriver`: ```php title="app/Channels/MobileAppDriver.php" namespace App\Channels; use Shopper\Core\Channel\Contracts\ChannelDriver; final class MobileAppDriver implements ChannelDriver { public function code(): string { return 'mobile'; } public function name(): string { return 'Mobile app'; } public function logo(): ?string { return asset('images/channels/mobile-app.svg'); } public function isConfigured(): bool { return true; } } ``` `logo()` returns an image URL or a data URI, or `null` for the default placeholder. `isConfigured()` returns `false` while the driver lacks something it needs; the settings page then shows its badge in orange. ### Registering a Driver [#registering-a-driver] `Shopper\Core\Channel\ChannelManager` extends Laravel's `Illuminate\Support\Manager`. Register the driver with `extend()` in the `boot` method of a service provider, through the `Channels` facade: ```php title="app/Providers/AppServiceProvider.php" use App\Channels\MobileAppDriver; use Shopper\Core\Channel\Contracts\ChannelDriver; use Shopper\Core\Channel\Facades\Channels; public function boot(): void { Channels::extend('mobile', fn (): ChannelDriver => new MobileAppDriver); } ``` The name passed to `extend()` is the value to store in the `driver` column, so keep it equal to `code()`: ```php Channel::findBySlug('mobile-app')->update(['driver' => 'mobile']); ``` The facade also lists and checks drivers: | Method | Returns | |--------|---------| | `Channels::driver('mobile')` | The driver instance; throws `InvalidArgumentException` for an unknown name | | `Channels::availableDrivers()` | The driver names: `web` and every registered one | | `Channels::configuredDrivers()` | The drivers whose `isConfigured()` returns `true`, keyed by name | | `Channels::isConfigured('mobile')` | `false` for an unknown driver or one whose check throws | | `Channels::logoFor($channel->driver)` | The driver logo, the `web` logo for `null`, `null` for an unknown driver | A channel can name a driver that is not registered, for example after you remove a package. The settings page then shows the raw driver name in an orange badge and a placeholder logo. ## Settings Page [#settings-page] The channels page is under **Settings**, in the **Selling** group, as **Sales channels** (`/cpanel/setting/channels`). It requires the `system.settings` permission. The table lists every channel, the default one first and the others by name, with these columns: | Column | Content | |--------|---------| | Logo | The logo of the channel driver | | Name | The channel name, with its `url` below it | | Driver | The driver name: gray for `web`, green for a configured driver, orange otherwise | | Default | Whether the channel is the default one | | Status | A toggle for `is_enabled`, locked on the default channel | | Updated At | Date of the last change | Disabling a channel takes it out of the Store API and out of the channels a new product can be added to. Products keep their link to it, and the product form shows it grayed out with a Disabled badge. To hide the page, set `Items\ChannelSetting::class` to `false` in `config/shopper/settings.php`, as shown in [Settings](/3.x/configuration#settings). The [User Guide](/3.x/user-guide) covers the admin screens. ## Assigning Products to Channels [#assigning-products-to-channels] In the admin panel, the Add product form has a **Sales channels** field that lists the enabled channels and starts with the default channel selected. The product page has a **Sales channels** section with one toggle per channel and a counter such as "Available in 1 of 2 sales channels". The product list can be filtered by channel. In code, attach channels through the product: ```php use Shopper\Core\Models\Channel; use Shopper\Core\Models\Product; $product = Product::query()->where('slug', 'classic-t-shirt')->first(); $product->channels()->attach([ Channel::findBySlug('web-store')->id, Channel::findBySlug('mobile-app')->id, ]); ``` Products created in code or through an import are attached to no channel. As soon as a Store API request resolves a channel, they disappear from its catalog. Attach them to their channels after you create them. The `channel` scope of the product model keeps the products attached to one channel, or to any of several channels. It takes channel IDs: ```php use Shopper\Core\Models\Product; $products = Product::query() ->channel([$webStore->id, $mobileApp->id]) ->publish() ->get(); ``` The search index of products also stores the public IDs of their channels, in a filterable `channels` field. The [Search](/3.x/search) page covers the index. ### Storefront Example [#storefront-example] A storefront built in the same Laravel application filters the catalog itself. This controller lists the products of the default channel: ```php title="app/Http/Controllers/ProductController.php" namespace App\Http\Controllers; use Illuminate\Contracts\View\View; use Shopper\Core\Models\Channel; use Shopper\Core\Models\Product; class ProductController extends Controller { public function index(): View { $channel = Channel::query()->default()->firstOrFail(); $products = Product::query() ->channel($channel->id) ->publish() ->with(['brand', 'categories']) ->paginate(12); return view('products.index', ['products' => $products]); } } ``` ## The Store API [#the-store-api] The Store API reads the channel of each request from the `X-Shopper-Channel` header, which carries a channel slug. The examples below use `store`, the default prefix of the Store API routes, set by `SHOPPER_API_PREFIX`: ```bash curl https://example.com/store/products \ -H "X-Shopper-Channel: mobile-app" ``` The `Shopper\Http\Middleware\ResolveChannel` middleware runs on every route of the `shopper:store` and `shopper:store-auth` groups. It resolves the channel in this order: 1. The enabled channel whose slug matches the header. 2. When the header is missing, unknown, longer than 64 characters or names a disabled channel: the enabled channel whose slug is set in `SHOPPER_API_DEFAULT_CHANNEL`. 3. Otherwise no channel. The request goes on without one and the API returns no error. The channel filters the catalog and never refuses a request. Without a resolved channel, the catalog is not filtered: the API returns every published product, including products attached to no channel and products reserved for another channel. Set `SHOPPER_API_DEFAULT_CHANNEL` before you open the Store API, for example to `web-store`. Without it, a client that omits the header sees the products of every channel. The settings live in `config/shopper/http.php`: ```php title="config/shopper/http.php" 'channel' => [ 'resolver' => Shopper\Http\Channel\DefaultChannelResolver::class, 'header' => 'X-Shopper-Channel', 'default_slug' => env('SHOPPER_API_DEFAULT_CHANNEL'), 'cache_ttl' => 60, ], ``` The resolver caches each channel it finds for `cache_ttl` seconds, and forgets it when the channel is saved or deleted. Set `cache_ttl` to `0` to query the database on every request. Every response adds the header name to `Vary`, so a shared cache keeps one copy per channel. ### What the Channel Changes [#what-the-channel-changes] When a channel is resolved: - `GET /store/products` lists only the products attached to it, and `GET /store/products/{slug}` answers 404 for a product that is not. - The `products` include of categories, collections, brands and tags, the `relatedProducts` include of a product, and the `products_count` include of categories count only its products. - `POST /store/carts` records it on the new cart, and the order placed from that cart keeps it. The admin panel shows the channel on the orders list, where it can also filter by channel, on the order page, and on abandoned carts. - The pricing context passed to the price resolver carries its ID in `Shopper\Core\Pricing\PricingContext::$channelId`. The default resolver ignores it; a custom one can set prices per channel, as described in [Pricing](/3.x/pricing). Categories, collections, brands and tags themselves are not filtered by channel, and neither are the review endpoints or `POST /store/carts/{cartId}/lines`: a cart accepts a product that is not attached to its channel. ### Reading the Channel in Your Own Endpoints [#reading-the-channel-in-your-own-endpoints] The middleware stores the channel in the `shopper_channel` request attribute, as an instance of the channel contract or `null`. A route registered inside `Shopper\Http\Facades\ShopperApi::store()` runs the same middleware and can read it: ```php title="app/Http/Controllers/FeaturedProductController.php" namespace App\Http\Controllers; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Shopper\Core\Models\Contracts\Channel; use Shopper\Core\Models\Product; class FeaturedProductController { public function __invoke(Request $request): JsonResponse { $channel = $request->attributes->get('shopper_channel'); $products = Product::query() ->publish() ->where('featured', true) ->when($channel instanceof Channel, fn (Builder $query) => $query->channel($channel->id)) ->limit(8) ->get(['id', 'name', 'slug']); return response()->json(['data' => $products]); } } ``` Register the route in `routes/web.php`, which Laravel loads without an `/api` prefix, so it answers on `/store/featured-products`: ```php title="routes/web.php" use App\Http\Controllers\FeaturedProductController; use Illuminate\Support\Facades\Route; use Shopper\Http\Facades\ShopperApi; ShopperApi::store(function (): void { Route::get('featured-products', FeaturedProductController::class); }); ``` ### Custom Resolver [#custom-resolver] To find the channel another way, from the domain of the storefront or an API key, implement `Shopper\Http\Contracts\ChannelResolver` and set it as the `resolver`. This resolver matches the `Origin` header of browser requests against the `url` of the channels, and falls back to the header lookup: ```php title="app/Http/OriginChannelResolver.php" namespace App\Http; use Illuminate\Http\Request; use Shopper\Core\Models\Contracts\Channel; use Shopper\Http\Channel\DefaultChannelResolver; use Shopper\Http\Contracts\ChannelResolver; final class OriginChannelResolver implements ChannelResolver { public function __construct(private readonly DefaultChannelResolver $headerResolver) {} public function resolve(Request $request): ?Channel { $origin = $request->headers->get('Origin'); $channel = filled($origin) ? resolve(Channel::class)::query() ->enabled() ->where('url', $origin) ->first() : null; return $channel ?? $this->headerResolver->resolve($request); } } ``` This entry of `config/shopper/http.php` makes the Store API use the resolver: ```php title="config/shopper/http.php" 'channel' => [ 'resolver' => App\Http\OriginChannelResolver::class, // ... ], ``` The [Store API](/3.x/store-api#request-headers) overview lists the other request headers. # Collections (/3.x/collections) A collection groups products for merchandising: a "Summer Sale" page, "New Arrivals", "Best Sellers", an "Editor's Picks" block on the home page. Categories organize the catalog into one tree; collections cut across it, and a product can belong to any number of them. A collection is either manual or automatic. The merchant picks the products of a manual collection one by one. An automatic collection holds the products that match its rules, such as "price less than 50.00" or "more than 10 units sold", and Shopper keeps that list up to date with a queued job and an Artisan command. ## Model [#model] The model configured for collections is `Shopper\Models\Collection`. It extends `Shopper\Core\Models\Collection` and implements the `Shopper\Core\Models\Contracts\Collection` contract. The core class holds the columns, the relationships, the scopes and the rule evaluation; the admin class adds the media collections and image conversions, as described in [Core Models and Admin Models](/3.x/models#core-models-and-admin-models). Four traits of the core class change what you can do with a collection: - `HasSlug` turns the `slug` you assign into a URL-safe value and appends `-1`, `-2` and so on when it is already taken. The slug is not derived from the name: pass one, because storefronts and the Store API find collections by their slug. - `HasPublicId` fills `public_id` with a ULID when the collection is created. The Store API returns it as the collection `id`. - `HasMediaCollections` declares the image and cover collections described in [Media](#media). - `Searchable` sends published collections to the search index. The [Search](/3.x/search) page covers indexing. The rules of an automatic collection are `Shopper\Core\Models\CollectionRule` models. That model has no configuration key, so it is always loaded with its own class. ### Extending the Model [#extending-the-model] To add your own methods, extend the admin class: ```php title="app/Models/Collection.php" whereHas('zones', fn (Builder $zones) => $zones->whereKey($zoneId)); } } ``` Then point the `collection` key of the configuration to your class: ```php title="config/shopper/models.php" 'collection' => App\Models\Collection::class, ``` Extend `Shopper\Models\Collection` rather than the core class: the admin panel uploads and reads the collection cover through the media methods of the admin class. The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ## Database Schema [#database-schema] Collections and their rules are stored in two tables, `sh_collections` and `sh_collection_rules` (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)). ### Collection Table [#collection-table] The `sh_collections` table holds one row per collection: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Collection name | | `slug` | string | yes | null | URL identifier, unique | | `description` | longtext | yes | null | Collection description, HTML from the admin editor | | `type` | string | no | - | `manual` or `auto`, cast to `CollectionType` | | `sort` | string | yes | null | Stored for your own code, Shopper does not read it | | `match_conditions` | string | yes | null | `all` or `any`, see [Match Conditions](#match-conditions) | | `published_at` | datetime (with time zone) | no | migration date | Publication date | | `seo_title` | string(60) | yes | null | SEO meta title | | `seo_description` | string(160) | yes | null | SEO meta description | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The database default of `published_at` is the date the migration ran, so always pass a publication date when you create a collection. ### CollectionRule Table [#collectionrule-table] The `sh_collection_rules` table holds the rules of automatic collections: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `rule` | string | no | - | Product property to compare, cast to `Rule` | | `operator` | string | no | - | Comparison, cast to `Operator` | | `value` | string | no | - | Value to compare with | | `collection_id` | bigint | no | - | Foreign key to the collection, rules are deleted with it | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ## Collection Types [#collection-types] The `type` column is cast to the `Shopper\Core\Enum\CollectionType` enum: | Case | Value | Admin label | Products come from | |------|-------|-------------|--------------------| | `CollectionType::Manual` | `manual` | Manual | The products attached to the collection | | `CollectionType::Auto` | `auto` | Automatic | The products that match the collection rules | The admin panel sets the type when the collection is created and has no field to change it afterwards. ### Type Checking [#type-checking] Two methods tell the types apart: ```php $collection->isManual(); $collection->isAutomatic(); ``` ## Relationships [#relationships] A collection is linked to its products and zones through polymorphic pivot tables, and an automatic collection owns its rules. ### Products [#products] Collections and products are linked through the polymorphic `sh_product_has_relations` table, which also links products to categories, channels and tags. For a manual collection, attach and detach products with the usual Eloquent methods: ```php $collection->products; $collection->products()->attach([$classicTShirt->id, $linenShorts->id]); $collection->products()->detach($linenShorts->id); $collection->products()->sync($productIds); $classicTShirt->collections; ``` For an automatic collection, the same table holds the result of the last [synchronization](#automatic-synchronization). The next sync replaces it with the products that match the rules, so products you attach or detach by hand do not stay. ### Zones [#zones] A collection can be linked to [zones](/3.x/zones) through the `sh_zone_has_relations` table, to record the markets a promotion runs in. The collections list of the admin panel has a zones column, hidden by default, and filters by zone. The models and the Store API do not filter collections by zone: apply the filter in your storefront if your markets need it. ```php use Shopper\Core\Models\Zone; $collection->zones; $collection->zones()->sync($zoneIds); $europe = Zone::query()->where('slug', 'europe')->first(); $europe->collections; ``` ### Rules (Automatic Collections) [#rules-automatic-collections] The `rules()` relation returns the `CollectionRule` models of the collection. Each rule compares one product property with a value: ```php use Shopper\Core\Enum\Operator; use Shopper\Core\Enum\Rule; $collection->rules; $collection->rules()->create([ 'rule' => Rule::ProductTitle, 'operator' => Operator::Contains, 'value' => 'summer', ]); ``` Creating, changing or deleting a rule in code does not update the products of the collection. Run a sync afterwards, as shown in [Updating Collections](#updating-collections). ## Slug & Lookup [#slug--lookup] The `HasSlug` trait adds a `findBySlug()` static method, which throws a `ModelNotFoundException` when no collection matches. `findByPublicId()` returns `null` instead: ```php use Shopper\Core\Models\Contracts\Collection; $summerSale = resolve(Collection::class)::findBySlug('summer-sale'); $summerSale = resolve(Collection::class)::findByPublicId('01JBX3M5D7R8K2C9P4W6Y0T1QE'); ``` Neither method checks the publication date. In a storefront, query with the `published` scope, as in the [Storefront Example](#storefront-example). ## Query Scopes [#query-scopes] The model has three scopes. `manual` and `automatic` filter by type, and `published` keeps the collections whose `published_at` date is set and not in the future: ```php use Shopper\Core\Models\Contracts\Collection; $collections = resolve(Collection::class)::query()->manual()->get(); $collections = resolve(Collection::class)::query() ->automatic() ->with('rules') ->get(); $collections = resolve(Collection::class)::query()->published()->get(); ``` ## Collection Rules [#collection-rules] An automatic collection holds one or more rules. Each rule names a product property (`rule`), a comparison (`operator`) and a value (`value`), and the `match_conditions` column of the collection decides whether a product must match all the rules or one of them. ### Rule Types [#rule-types] The `rule` column is cast to the `Shopper\Core\Enum\Rule` enum: | Case | Value | Matches against | |------|-------|-----------------| | `Rule::ProductTitle` | `product_title` | The product `name` | | `Rule::ProductBrand` | `product_brand` | The name of the product brand | | `Rule::ProductCategory` | `product_category` | The names of the product categories | | `Rule::ProductPrice` | `product_price` | The price `amount`, in cents | | `Rule::CompareAtPrice` | `compare_at_price` | The price `compare_amount`, in cents | | `Rule::InventoryStock` | `inventory_stock` | The stock of the product, summed from its inventory history | | `Rule::ProductCreatedAt` | `product_created_at` | The date the product was created | | `Rule::ProductFeatured` | `product_featured` | The `featured` flag, `1` or `0` | | `Rule::ProductRating` | `product_rating` | The average rating of the approved reviews | | `Rule::ProductSalesCount` | `product_sales_count` | The units sold in paid orders | The `value` column is a string for every rule: pass `'5000'` rather than `5000`. The enum also has `isPrice()`, `isNumeric()`, `isDate()` and `isBoolean()` helpers, which the admin panel uses to pick the input for each rule. ### Operators [#operators] The `operator` column is cast to the `Shopper\Core\Enum\Operator` enum: | Case | Value | Admin label | |------|-------|-------------| | `Operator::EqualsTo` | `equals_to` | Equals to | | `Operator::NotEqualTo` | `not_equal_to` | Not equals to | | `Operator::LessThan` | `less_than` | Less than | | `Operator::GreaterThan` | `greater_than` | Greater than | | `Operator::StartsWith` | `starts_with` | Starts with | | `Operator::EndsWith` | `ends_with` | End with | | `Operator::Contains` | `contains` | Contains | | `Operator::NotContains` | `not_contains` | Not contains | Each rule accepts a subset of these operators, returned by the `allowedOperators()` method of its case, such as `Rule::ProductPrice->allowedOperators()`: | Rules | Operators | |-------|-----------| | `ProductTitle`, `ProductBrand`, `ProductCategory` | `contains`, `not_contains`, `starts_with`, `ends_with`, `equals_to`, `not_equal_to` | | `ProductPrice`, `CompareAtPrice`, `InventoryStock`, `ProductRating`, `ProductSalesCount` | `equals_to`, `not_equal_to`, `less_than`, `greater_than` | | `ProductCreatedAt` | `equals_to`, `less_than`, `greater_than` | | `ProductFeatured` | `equals_to` | The admin panel only offers these combinations. The model does not validate them, so check them yourself when you save rules from code or from an import: a text rule with `less_than` adds no comparison, so a title rule matches every product and a brand or category rule every product that has one, and a numeric rule with `contains` compares with "equals". ### Match Conditions [#match-conditions] When a collection has several rules, `match_conditions` decides how they combine. With `all`, a product must match every rule. With `any`, one matching rule is enough. A collection with no value in `match_conditions` behaves as `any`. ```php $collection->update(['match_conditions' => 'all']); ``` An automatic collection without rules contains no products. ### Price Rules [#price-rules] `ProductPrice` and `CompareAtPrice` rules store their value in cents, as a string: `'5000'` is 50.00 in a two-decimal currency. They compare it with the product prices in the store default currency, the `default_currency_id` [setting](/3.x/settings). The [Money](/3.x/money) page explains cents and currencies without decimals. The rules slide-over of the admin panel converts the value for the merchant. It shows the stored cents divided by 100, and multiplies the amount the merchant types by 100 before saving it. For a [zero-decimal currency](/3.x/money#zero-decimal-currencies) such as XAF or JPY, it shows and stores the whole amount as typed. Code that saves price rules from a decimal input converts it the way [Converting Input](/3.x/money#converting-input) shows. Price, compare-at price, stock and sales count rules read values stored on the product itself. A product of the variant type keeps its prices, its stock and its sales on its variants (the admin panel has no product-level price for it), so these four rules ignore its variants and match it only on values stored on the product itself. ## Display Helpers [#display-helpers] The `firstRule()` method returns a readable summary of the rules of an automatic collection, made of the first rule and the number of other rules, such as `Product price Less than $50.00 + 1 other(s)`. The admin panel shows it in the collections list. It returns `null` for a manual collection, and expects an automatic collection to have at least one rule. ```php $collection->firstRule(); ``` A rule formats itself with `getFormattedRule()`, `getFormattedOperator()` and `getFormattedValue()`. The value of a price rule is formatted as money in the store currency, and the value of the featured rule as "Yes" or "No": ```php foreach ($collection->rules as $rule) { echo $rule->getFormattedRule().' '.$rule->getFormattedOperator().' '.$rule->getFormattedValue(); } ``` ## Retrieving Products [#retrieving-products] A collection gives two ways to read its products. `getProducts()` and `productsQuery()` compute the list when you call them. The `products` relation reads the pivot table, which for an automatic collection holds the result of the last [synchronization](#automatic-synchronization). ### Basic Usage [#basic-usage] `getProducts()` returns an Eloquent collection of products. `productsQuery()` returns a query builder, to paginate, eager load or add your own conditions: ```php use Shopper\Core\Models\Contracts\Collection; $summerSale = resolve(Collection::class)::findBySlug('summer-sale'); $products = $summerSale->getProducts(); $products = $summerSale->productsQuery() ->with(['brand', 'prices.currency']) ->orderBy('name') ->paginate(12); ``` ### How It Works [#how-it-works] For a manual collection, both methods return the attached products that are published: `published_at` in the past and `is_visible` set. For an automatic collection, they start from all published products and add one condition per rule, joined with `AND` when `match_conditions` is `all` and with `OR` otherwise. Both methods run through `Shopper\Core\Queries\CollectionProductsQuery`, which you can also call directly. Its `matches()` method tells whether one product matches the rules of an automatic collection: ```php use Shopper\Core\Queries\CollectionProductsQuery; $query = new CollectionProductsQuery; $products = $query->query($summerSale)->with('brand')->paginate(12); $isInSale = $query->matches($summerSale, $classicTShirt); ``` The `products` relation returns every attached product, published or not. Add the product `publish` scope when you read it for a storefront: `$collection->products()->publish()->get()`. ### Rule Evaluation [#rule-evaluation] Each rule becomes one condition on the products query: | Rule | Condition | |------|-----------| | `ProductTitle` | `name` compared with the value, `LIKE` for the text operators | | `ProductBrand` | The product has a brand whose `name` matches | | `ProductCategory` | The product has a category whose `name` matches. For `not_equal_to` and `not_contains`, the product has no category whose `name` passes the negated test: only products whose categories all equal (or all contain) the value, and products with no category, match | | `ProductPrice` | The product has a price in the default currency whose `amount` matches | | `CompareAtPrice` | The product has a price in the default currency whose `compare_amount` matches | | `InventoryStock` | The sum of the `quantity` column of the product inventory history matches. A product with no history does not match | | `ProductCreatedAt` | The date part of `created_at` is equal to, before or after the value, a date such as `2026-09-01` | | `ProductFeatured` | `featured` equals the value, whatever the operator | | `ProductRating` | The average `rating` of the approved reviews of the product matches. A product with no approved review does not match | | `ProductSalesCount` | The sum of the `quantity` of the order items of the product matches, counting orders with the `processing` or `completed` status and the `paid` payment status. A product never sold does not match | ## Automatic Synchronization [#automatic-synchronization] Reading an automatic collection through `productsQuery()` runs every rule on each call. A rule on sales or ratings adds an aggregate subquery over orders or reviews. To keep storefront pages and the Store API fast, Shopper stores the matching products in the pivot table and refreshes it at set moments. ### How Sync Works [#how-sync-works] Three things refresh the products of automatic collections: | Trigger | What runs | |---------|-----------| | A product is created or updated | `SyncProductWithCollectionsJob`, queued once the database transaction commits. It adds the product to every automatic collection whose rules it matches, and removes it from the others | | A merchant saves the conditions in the rules slide-over of the admin panel | `SyncCollectionProductsJob` for that collection | | `php artisan shopper:collections:sync` runs | `SyncCollectionProductsAction` for each automatic collection | Nothing else starts a sync. A collection created in code, a rule added or changed in code, a new price, a stock movement, a paid order, an approved review, a renamed brand or category, and a product reaching its publication date all leave the pivot table as it was until the next product save or the next run of the command. [Schedule the command](#scheduling-the-sync) to pick these changes up. ### Manual Sync Command [#manual-sync-command] The `shopper:collections:sync` command syncs every automatic collection and prints the number of products of each one. The `--collection` option syncs one collection by its ID: ```bash php artisan shopper:collections:sync php artisan shopper:collections:sync --collection=12 ``` The command fails when the ID does not exist, and skips a manual collection with a warning. It runs the sync in the same process, without the queue. ### Scheduling the Sync [#scheduling-the-sync] Shopper does not schedule the command. Add it to the scheduler of your application, at the frequency your rules need: ```php title="routes/console.php" use Illuminate\Support\Facades\Schedule; Schedule::command('shopper:collections:sync') ->hourly() ->withoutOverlapping(); ``` The scheduler runs only when `php artisan schedule:run` is called every minute, from cron or from `php artisan schedule:work`. The [Laravel scheduling documentation](https://laravel.com/docs/scheduling) covers the setup. ### Sync Action [#sync-action] `Shopper\Core\Actions\SyncCollectionProductsAction` syncs one collection in the current process. It replaces the attached products with the published products that match the rules and returns their number. It returns `0` and changes nothing for a manual collection: ```php use Shopper\Core\Actions\SyncCollectionProductsAction; $count = (new SyncCollectionProductsAction)->execute($summerSale); ``` ### Background Jobs [#background-jobs] Both jobs implement `ShouldQueue` and live in the `Shopper\Core\Jobs` namespace: - `SyncCollectionProductsJob` takes a collection and runs the sync action for it. - `SyncProductWithCollectionsJob` takes a product and checks it against every automatic collection. Dispatch `SyncCollectionProductsJob` after you change rules in code: ```php use Shopper\Core\Jobs\SyncCollectionProductsJob; SyncCollectionProductsJob::dispatch($summerSale); ``` The jobs go to the default queue connection. With a `sync` connection they run during the request; with any other connection a queue worker must run, or automatic collections stop updating: ```bash php artisan queue:work ``` ## Media [#media] Collections have two media collections, named in `config/shopper/media.php`: | Collection | Config key | Default name | Files | Use | |------------|------------|--------------|-------|-----| | Images | `shopper.media.storage.collection_name` | `uploads` | Several | Extra collection images | | Thumbnail | `shopper.media.storage.thumbnail_collection` | `thumbnail` | One | The collection cover | The admin forms upload the cover to the thumbnail collection, up to `shopper.media.max_size.thumbnail` kilobytes. Add a cover from code and read its URL with `getThumbnailUrl()`, which takes an optional conversion name: ```php $summerSale->addMedia($request->file('cover')) ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); $coverUrl = $summerSale->getThumbnailUrl('large'); ``` The [Media](/3.x/media) page covers storage disks, conversions and the placeholder image. ## Configuration [#configuration] Collections are on by default. Their settings are the feature flag, the model key and the admin components. ### Disabling Collections [#disabling-collections] If your store does not use collections, disable the feature in `config/shopper/features.php`: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'collection' => FeatureState::Disabled, ]; ``` The collection pages are no longer registered, the Collections item leaves the sidebar, and the collections field of the product forms is hidden. The flag only changes the admin panel: the models, the product observer, the sync command and the Store API collection endpoints stay available. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Components [#components] The collections section of the admin panel is made of two pages, a products table and three slide-overs. To replace any of them with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish collection ``` The command creates `config/shopper/components/collection.php`: ```php title="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, ], ]; ``` The rules slide-over converts price values and dispatches the sync job, as described above. A replacement component must do both. The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below resolve the collection class from its contract, so they keep working after you swap the model. ### Creating Collections [#creating-collections] The model accepts every column through `create()`. Pass a slug and a publication date with the name and the type. #### Manual Collection [#manual-collection] Create the collection, then attach the products the merchant picked: ```php use Shopper\Core\Enum\CollectionType; use Shopper\Core\Models\Contracts\Collection; use Shopper\Core\Models\Contracts\Product; $editorsPicks = resolve(Collection::class)::query()->create([ 'name' => "Editor's Picks", 'slug' => 'editors-picks', 'type' => CollectionType::Manual, 'published_at' => now(), ]); $productIds = resolve(Product::class)::query() ->whereIn('slug', ['classic-t-shirt', 'linen-shorts', 'canvas-sneakers']) ->pluck('id'); $editorsPicks->products()->attach($productIds); ``` #### Automatic Collection [#automatic-collection] Create the collection, add its rules, then dispatch the sync job so the pivot table holds the matching products. This collection holds the t-shirts that cost less than 50.00: ```php use Shopper\Core\Enum\CollectionType; use Shopper\Core\Enum\Operator; use Shopper\Core\Enum\Rule; use Shopper\Core\Jobs\SyncCollectionProductsJob; use Shopper\Core\Models\Contracts\Collection; $tShirtsUnder50 = resolve(Collection::class)::query()->create([ 'name' => 'T-Shirts Under 50', 'slug' => 't-shirts-under-50', 'type' => CollectionType::Auto, 'match_conditions' => 'all', 'published_at' => now(), ]); $tShirtsUnder50->rules()->createMany([ ['rule' => Rule::ProductPrice, 'operator' => Operator::LessThan, 'value' => '5000'], ['rule' => Rule::ProductCategory, 'operator' => Operator::EqualsTo, 'value' => 'T-Shirts'], ]); SyncCollectionProductsJob::dispatch($tShirtsUnder50); ``` #### Best Sellers Collection [#best-sellers-collection] A collection of the products sold more than 10 times in paid orders: ```php $bestSellers = resolve(Collection::class)::query()->create([ 'name' => 'Best Sellers', 'slug' => 'best-sellers', 'type' => CollectionType::Auto, 'match_conditions' => 'all', 'published_at' => now(), ]); $bestSellers->rules()->create([ 'rule' => Rule::ProductSalesCount, 'operator' => Operator::GreaterThan, 'value' => '10', ]); SyncCollectionProductsJob::dispatch($bestSellers); ``` Sales change with every paid order, and no order triggers a sync: a best sellers collection needs the [scheduled command](#scheduling-the-sync). #### Top Rated Collection [#top-rated-collection] A collection of the products whose approved reviews average more than 4 stars: ```php $topRated = resolve(Collection::class)::query()->create([ 'name' => 'Top Rated', 'slug' => 'top-rated', 'type' => CollectionType::Auto, 'match_conditions' => 'all', 'published_at' => now(), ]); $topRated->rules()->create([ 'rule' => Rule::ProductRating, 'operator' => Operator::GreaterThan, 'value' => '4', ]); SyncCollectionProductsJob::dispatch($topRated); ``` ### Retrieving Collections [#retrieving-collections] Query published collections with the `published` scope, and eager load the media when you show covers: ```php use Shopper\Core\Models\Contracts\Collection; $collections = resolve(Collection::class)::query() ->published() ->with('media') ->orderBy('name') ->get(); $summerSale = resolve(Collection::class)::query() ->published() ->where('slug', 'summer-sale') ->firstOrFail(); ``` The Product model has a `collection` scope that reads the pivot table. It takes collection slugs or public IDs and only looks at published collections: ```php use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::query() ->publish() ->collection('summer-sale', 'best-sellers') ->paginate(12); ``` ### Updating Collections [#updating-collections] Update the collection columns with `update()`. When you change the rules or the match conditions of an automatic collection, dispatch the sync job afterwards: ```php use Shopper\Core\Enum\Rule; use Shopper\Core\Jobs\SyncCollectionProductsJob; $tShirtsUnder50->update(['match_conditions' => 'any']); $tShirtsUnder50->rules() ->where('rule', Rule::ProductPrice) ->update(['value' => '4000']); SyncCollectionProductsJob::dispatch($tShirtsUnder50); ``` ### Storefront Example [#storefront-example] A controller that lists the published collections and shows one with its products. `productsQuery()` returns the current products of both types; for an automatic collection it runs the rules on each request: ```php title="app/Http/Controllers/CollectionController.php" published() ->with('media') ->orderBy('name') ->get(); return view('collections.index', ['collections' => $collections]); } public function show(string $slug): View { $collection = resolve(Collection::class)::query() ->published() ->where('slug', $slug) ->firstOrFail(); $products = $collection->productsQuery() ->with(['brand', 'prices.currency', 'media']) ->paginate(12); return view('collections.show', [ 'collection' => $collection, 'products' => $products, ]); } } ``` For collections with sales or rating rules on a large catalog, read the synced products instead, as the Store API does: `$collection->products()->publish()->with(['brand', 'prices.currency', 'media'])->paginate(12)`. ### Use Cases [#use-cases] Common collections and the rules behind them: | Type | Example | Rules | |------|---------|-------| | Manual | Gift Guide | Products picked by the merchant | | Manual | Editor's Picks | Products picked by the merchant | | Automatic | New Arrivals | `ProductCreatedAt` greater than a fixed date, such as `2026-09-01`, that you move forward | | Automatic | Sale Items | `CompareAtPrice` greater than `0` | | Automatic | Low Stock | `InventoryStock` less than `5` | | Automatic | Featured | `ProductFeatured` equals `1` | | Automatic | Best Sellers | `ProductSalesCount` greater than `10` | | Automatic | Top Rated | `ProductRating` greater than `4` | The date rule compares with a fixed date: "created in the last 30 days" needs your own scheduled code that updates the rule value, then syncs the collection. ## Events [#events] Shopper dispatches no collection event of its own and registers no observer on the collection or rule models. Listen to the Eloquent model events instead. They are dispatched under the core class name as well, so a listener registered on `Shopper\Core\Models\Collection` keeps firing after you swap the model: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Collection; public function boot(): void { Collection::saved(fn () => Cache::forget('storefront.collections')); Collection::deleted(fn () => Cache::forget('storefront.collections')); } ``` The product observer, `Shopper\Core\Observers\ProductObserver`, dispatches `SyncProductWithCollectionsJob` each time a product is saved, as described in [How Sync Works](#how-sync-works). The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks four permissions of the `collections` resource, in the Catalog group: | Permission | Allows | |------------|--------| | `collections.browse` | Opening the collections page and seeing the Collections sidebar item | | `collections.create` | Opening the form for a new collection | | `collections.edit` | Opening the edit page, saving the rules, adding and removing products | | `collections.delete` | Deleting a collection, one at a time or in bulk | `collections.read` is seeded with the others, but the admin panel never checks it. Shopper 2.x named these permissions `browse_collections`, `add_collections` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants manage collections under Catalog, Collections. The list shows each collection with its cover, name, type, the summary of its conditions, its zones (a column hidden by default) and its last update, and filters by type and zone. The creation form opens in a slide-over (name, slug, availability date, type, zones, description, cover, SEO and metadata), then leads to the edit page. There, a manual collection has a Browse button to add products, and an automatic collection has a Conditions button that opens the rules slide-over and syncs the collection when it is saved. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the published collections under the `store` prefix, set by `SHOPPER_API_PREFIX`: | Endpoint | Returns | |----------|---------| | `GET /store/collections` | The published collections, paginated. Filter with `filter[name]` (partial match), sort with `sort=name` | | `GET /store/collections/{slug}` | One published collection | Add `include=products` to either endpoint to get the published products of each collection. The include reads the pivot table, so an automatic collection returns the products of its last sync. A collection resource has the type `collections` and carries `name`, `slug`, `description`, `type`, `published_at`, `seo_title`, `seo_description`, `metadata`, `thumbnail` (the cover with its conversion URLs), `created_at` and `updated_at`. The products endpoint filters and includes by collection. `filter[collection]` accepts collection slugs or public IDs, separated by commas: ```bash curl "https://example.com/store/products?filter[collection]=summer-sale&include=collections" ``` The `products` include and the product listing follow the channel of the request, as described in [Channels](/3.x/channels#the-store-api); the collections themselves are not filtered by channel or zone. The Store API serves collections even when the `collection` feature flag is disabled. The Store API [Catalog](/3.x/store-api/catalog#collections) guide covers the collection endpoints. # Configuration (/3.x/configuration) Shopper publishes its configuration files to `config/shopper/` during installation. This page goes through the files and the settings you are most likely to change when you set up a store: the admin panel address, the table prefix, the sections you need, your own models, and the settings pages. Each page of the documentation covers the configuration of its own feature in more depth. ## Configuration Files [#configuration-files] `php artisan shopper:install` publishes these files: | File | Package | Purpose | |------|---------|---------| | `addons.php` | admin | Disables an installed add-on by its ID | | `admin.php` | admin | Admin panel prefix, domain, roles, branding, locales, notifications | | `auth.php` | admin | Authentication guard, two-factor authentication, passkeys, password reset | | `features.php` | admin | Feature flags for the optional sections of the admin panel | | `media.php` | admin | Media disks, accepted file types, maximum sizes, image conversions | | `models.php` | admin | The class used for each swappable model | | `routes.php` | admin | Extra middleware and a custom route file for the admin panel | | `settings.php` | admin | The pages listed on the settings screen | | `themes.php` | admin | The admin panel themes and the default one | | `core.php` | core | Table prefix, barcode type, import chunk size, category tree cache | | `orders.php` | core | Order number format and the reclaim of unpaid orders | | `search.php` | core | Search indexers, facets and the search engine of each model | | `webhooks.php` | core | Outgoing webhooks: events, queue, retries, limits, pruning | | `cart.php` | cart | Cart pipeline, promotions, abandoned cart pruning | | `payment.php` | payment | Reconciliation of pending payments | | `shipping.php` | shipping | Units, rates cache, shipment tracking sync | When `shopper/api` is installed, the same command also publishes `api.php` (pagination, token lifetime, filters and includes of each resource) and `http.php` (route prefix, rate limits, zone and channel resolution). Payment and carrier drivers publish their own file on demand, with the `shopper-stripe-config`, `shopper-fedex-config`, `shopper-ups-config` or `shopper-usps-config` tag, for example `php artisan vendor:publish --tag=shopper-stripe-config`. The [Payments](/3.x/payments) and [Carriers](/3.x/carriers) pages cover each driver. To publish the configuration files again after an upgrade, together with the translations, run `php artisan shopper:publish`. Existing files are kept; add `--force` to overwrite them. ## Admin Panel [#admin-panel] The admin panel answers on `/cpanel` by default. Change the prefix in `config/shopper/admin.php`, or set `SHOPPER_PREFIX` in your `.env` file: ```php title="config/shopper/admin.php" 'prefix' => env('SHOPPER_PREFIX', 'cpanel'), ``` To serve the admin panel on its own domain, such as `admin.example.com`, set `SHOPPER_DOMAIN`. Shopper passes it to Laravel's `Route::domain()`: ```php title="config/shopper/admin.php" 'domain' => env('SHOPPER_DOMAIN'), ``` The branding keys set the logo, the favicon and the Filament primary color of the admin panel: ```php title="config/shopper/admin.php" 'brand' => null, 'favicon' => null, 'primary_color' => \Filament\Support\Colors\Color::Blue, ``` `primary_color` accepts any color of the `Filament\Support\Colors\Color` class, such as `Color::Emerald`. ### Avatar Colors [#avatar-colors] Users without a profile photo get an avatar generated from their initials. These keys set its text and background colors, as hexadecimal values without the `#`: ```php title="config/shopper/admin.php" 'avatar' => [ 'color' => '1d4ed8', 'bg_color' => 'dbeafe', ], ``` ### Locales [#locales] The languages a user can pick for the admin panel. Each entry maps a locale code to a label and a flag code (ISO 3166-1 alpha-2, lowercase): ```php title="config/shopper/admin.php" 'locales' => [ 'en' => ['label' => 'English', 'flag' => 'gb'], 'fr' => ['label' => 'Français', 'flag' => 'fr'], ], ``` ### Custom Pages [#custom-pages] `php artisan make:shopper-page` creates an admin page in this namespace and view path: ```php title="config/shopper/admin.php" 'pages' => [ 'namespace' => 'App\\Livewire\\Shopper', 'view_path' => resource_path('views/livewire/shopper'), ], ``` ### Notifications [#notifications] Shopper can store notifications for administrators, such as a new order or a failed payment, and show them under a bell in the top bar. They are off by default: ```php title="config/shopper/admin.php" 'notifications' => [ 'database' => [ 'enabled' => false, 'polling_interval' => '30s', ], ], ``` `polling_interval` sets how often the bell refreshes. Set it to `null` to stop polling and rely on broadcasting through Laravel Echo. The [Notifications](/3.x/notifications) page covers the events that create a notification. ### Themes [#themes] The admin panel ships with three themes: `default`, `midnight` and `evergreen`. `config/shopper/themes.php` registers the available themes and sets the one used until a merchant saves another in the **Appearance** settings, for every user of the admin panel. The [Themes](/3.x/themes) page explains how to add your own. ## Database Table Prefix [#database-table-prefix] All Shopper tables are prefixed with `sh_` so that they never collide with the tables of your application: ```php title="config/shopper/core.php" 'table_prefix' => 'sh_', ``` Set the table prefix before the Shopper migrations run. Changing it afterwards requires a custom migration that renames every Shopper table. The file only exists once the installer has published it, so change the prefix in this order: Run `php artisan shopper:install` and answer no when it asks to run the migrations and seeders. Set `table_prefix` in `config/shopper/core.php`. Run the migrations and the two seeders the installer would have run: ```bash php artisan migrate php artisan db:seed --class="Shopper\Core\Database\Seeders\ShopperSeeder" php artisan db:seed --class="Shopper\Database\Seeders\AuthTableSeeder" ``` ## Feature Flags [#feature-flags] `config/shopper/features.php` turns the optional sections of the admin panel on and off. Set a feature to `FeatureState::Disabled` and its pages, its sidebar entry and its fields in the product form disappear: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'attribute' => FeatureState::Enabled, 'brand' => FeatureState::Enabled, 'campaign' => FeatureState::Enabled, 'category' => FeatureState::Enabled, 'collection' => FeatureState::Enabled, 'discount' => FeatureState::Enabled, 'review' => FeatureState::Enabled, 'supplier' => FeatureState::Disabled, 'tag' => FeatureState::Enabled, ]; ``` A store that does not collect product reviews sets `'review' => FeatureState::Disabled`: the reviews page and its sidebar link are removed. Suppliers are the only section disabled on a fresh install; enable them to show the supplier field on products. ## Models [#models] `config/shopper/models.php` lists the class Shopper uses for each swappable model. Replace a class with your own, which extends the original, and the admin panel, the relationships and the route bindings all use it: ```php title="config/shopper/models.php" use Shopper\Models; return [ 'address' => Shopper\Core\Models\Address::class, 'brand' => Models\Brand::class, 'category' => Models\Category::class, 'collection' => Models\Collection::class, 'product' => Models\Product::class, 'variant' => Models\ProductVariant::class, 'attribute_product' => Models\AttributeProduct::class, 'channel' => Shopper\Core\Models\Channel::class, 'inventory' => Shopper\Core\Models\Inventory::class, 'order' => Shopper\Core\Models\Order::class, 'supplier' => Shopper\Core\Models\Supplier::class, 'tax_zone' => Shopper\Core\Models\TaxZone::class, 'tax_rate' => Shopper\Core\Models\TaxRate::class, ]; ``` The catalog models come from the `Shopper\Models` namespace of the admin package, which adds media support to them; the others come from `Shopper\Core\Models`. Extend the exact class listed for the entry you replace. The [Models](/3.x/models) page explains how swapping works. ## Authentication [#authentication] `config/shopper/auth.php` sets the guard of the admin panel and the sign-in options: ```php title="config/shopper/auth.php" return [ 'guard' => 'web', '2fa_enabled' => env('SHOPPER_ENABLED_TWO_FACTOR', false), 'passkeys_enabled' => env('SHOPPER_ENABLED_PASSKEYS', false), 'password_reset' => true, ]; ``` Set `SHOPPER_ENABLED_TWO_FACTOR=true` to make two-factor authentication available to admin users, and `SHOPPER_ENABLED_PASSKEYS=true` to let them sign in with a passkey. Neither is forced on anyone: each user turns them on from their account page. The [Two-Factor Authentication](/3.x/two-factor) page lists what your `User` model needs for both. ## Middleware [#middleware] The `middleware` key adds your own middleware to every admin route behind the login, for example to log admin activity or restrict access to an office IP range: ```php title="config/shopper/routes.php" 'middleware' => [], ``` ## Custom Routes [#custom-routes] Your `routes/web.php` file is not loaded inside the admin panel. To add routes that share its login and middleware, point `custom_file` to a route file of your own: ```php title="config/shopper/routes.php" 'custom_file' => base_path('routes/shopper.php'), ``` The routes in this file are served under the admin panel prefix and their names start with `shopper.`, like the admin panel routes. ## Components [#components] Each section of the admin panel is made of Livewire components that you can replace one by one. Publish the component configuration of a section with its name: ```bash php artisan shopper:component:publish product ``` The command creates `config/shopper/components/product.php`, where each page and component of the section points to a class you can change. The available sections are `account`, `brand`, `campaign`, `category`, `collection`, `customer`, `dashboard`, `discount`, `order`, `product`, `review` and `setting`. Pass `--all` to publish every section at once. Without a name or `--all`, the command asks which section to publish. Add `--force` to overwrite files you already published. ## Settings [#settings] The settings screen of the admin panel lists one page per class registered in `config/shopper/settings.php`. Set an entry to `false` to take it off the settings screen: ```php title="config/shopper/settings.php" use Shopper\Navigation\Setting\Items; return [ 'items' => [ Items\GeneralSetting::class => true, Items\AppearanceSetting::class => true, Items\StaffSetting::class => true, Items\LocationSetting::class => true, Items\ChannelSetting::class => true, Items\PaymentSetting::class => true, Items\CarrierSetting::class => true, Items\LegalSetting::class => true, Items\ZoneSetting::class => true, Items\TaxSetting::class => true, Items\CurrencySetting::class => true, Items\WebhookSetting::class => true, ], ]; ``` The screen groups the pages under four headings, in this order: | Group | Pages | |-------|-------| | Store | General, Appearance, Inventories, Legal, Webhooks | | Selling | Sales channels, Payment methods, Taxes, Currencies | | Shipping | Carriers, Zones | | Team | Staff & permissions | Removing a page removes the only screen where its data is managed. Disable the Taxes page and nobody can create a tax zone from the admin panel anymore. ### Adding a Settings Page [#adding-a-settings-page] A settings page is a class that extends `Shopper\Navigation\Setting\Setting`. It gives the name, description and icon shown on the settings screen, the URL the entry opens, and optionally its position, its group and the permission needed to see it: ```php title="app/Shopper/Settings/LoyaltySetting.php" namespace App\Shopper\Settings; use Shopper\Enum\SettingGroup; use Shopper\Navigation\Setting\Setting; final class LoyaltySetting extends Setting { public function name(): string { return __('Loyalty program'); } public function description(): string { return __('Points earned per order and the rewards customers can claim.'); } public function icon(): string { return 'phosphor-gift'; } public function url(): string { return route('shopper.settings.loyalty'); } public function order(): int { return 5; } public function group(): string { return SettingGroup::Selling->value; } public function permission(): ?string { return 'loyalty.manage'; } } ``` `group()` returns one of the four `SettingGroup` values, or any other string to create a group of your own: it is listed after the four built-in ones, with the string as its heading. A page without a group is listed last. A page with a permission is hidden from users who do not have it. Register the class in `config/shopper/settings.php`: ```php title="config/shopper/settings.php" 'items' => [ // ... App\Shopper\Settings\LoyaltySetting::class => true, ], ``` A package registers its page from a service provider instead, through the `SettingManager`: ```php use Shopper\Navigation\Setting\SettingManager; app(SettingManager::class)->add(App\Shopper\Settings\LoyaltySetting::class); ``` The manager also has `enable()` and `disable()` to show or hide a registered page at runtime. ## Orders [#orders] `config/shopper/orders.php` sets the format of order numbers: a prefix, a date, and a padded sequence. ```php title="config/shopper/orders.php" 'generator' => [ 'prefix' => 'ORD', 'separator' => '-', 'date_format' => 'Ymd', 'start_sequence_from' => 0, 'pad_length' => 6, 'pad_string' => '0', ], ``` The sequence is the order's database ID plus `start_sequence_from`, so two checkouts that finish at the same time never get the same number. With the default of 0, the first order gets `000001`. A store that moves from another platform sets `start_sequence_from` to the last number it used, and its first Shopper order continues from there. With the defaults, the order with ID 124, placed on November 16, 2026, gets these numbers: | Configuration | Order number | |---------------|--------------| | Default | `ORD-20261116-000124` | | `'prefix' => null` | `20261116-000124` | | `'date_format' => null` | `ORD-000124` | | `'prefix' => null, 'date_format' => null` | `000124` | The same file sets how long an unpaid order holds its stock: ```php title="config/shopper/orders.php" 'reclaim_pending_after_hours' => 24, ``` Every hour, the `shopper:orders:reclaim` command cancels the pending orders that received no payment within this window and puts their reserved stock back on sale. Orders paid offline, such as cash on delivery, are never cancelled this way. Set the key to `null` to turn it off. The command runs through the Laravel scheduler, which the [Installation](/3.x/installation#run-the-scheduler-and-a-queue-worker) page sets up. ## Environment Variables [#environment-variables] The variables Shopper reads from your `.env` file, besides those of the payment and shipping packages and their drivers: | Variable | Default | Purpose | |----------|---------|---------| | `SHOPPER_PREFIX` | `cpanel` | URL prefix of the admin panel | | `SHOPPER_DOMAIN` | none | Domain of the admin panel | | `SHOPPER_ENABLED_TWO_FACTOR` | `false` | Makes two-factor authentication available | | `SHOPPER_ENABLED_PASSKEYS` | `false` | Makes passkey sign-in available | | `SHOPPER_WEBHOOKS_QUEUE` | `webhooks` | Queue that delivers outgoing webhooks | | `SHOPPER_WEBHOOKS_ALLOWED_HOSTS` | empty | Comma-separated hosts webhooks may be sent to; empty allows any public host | | `SHOPPER_WEBHOOKS_MAX_SUBSCRIPTIONS` | `50` | Maximum number of webhook subscriptions | | `SHOPPER_WEBHOOKS_DB_CONNECTION` | default connection | Database connection of the webhook subscriptions, events and deliveries | | `SHOPPER_API_PREFIX` | `store` | URL prefix of the Store API | | `SHOPPER_API_PER_PAGE` | `15` | Default page size of the Store API | | `SHOPPER_API_TOKEN_EXPIRATION` | `43200` | Lifetime of customer tokens, in minutes (30 days) | | `SHOPPER_API_DEFAULT_ZONE` | none | Zone code used when a request sends none | | `SHOPPER_API_DEFAULT_CHANNEL` | none | Channel slug used when a request sends none, or one that is unknown or disabled | The variables of the payment and shipping packages and of each driver are listed on their pages. # Contribution Guide (/3.x/contributing) Shopper is developed in the open on GitHub. Bug reports, fixes, features and documentation improvements are all welcome. This page explains where each kind of contribution goes and what a pull request needs before it can be merged. ## Where the Code Lives [#where-the-code-lives] All the Composer and npm packages live in one repository, [shopperlabs/shopper](https://github.com/shopperlabs/shopper), each in its own folder under `packages/`. The repositories named after a single package, such as `shopperlabs/core` or `shopperlabs/admin`, are read-only copies published from that repository on every release. Open issues and pull requests on `shopperlabs/shopper` only. The documentation you are reading lives in [shopperlabs/docs](https://github.com/shopperlabs/docs). Every page has an **Edit on GitHub** link at the bottom. ## Reporting a Bug [#reporting-a-bug] Open an [issue](https://github.com/shopperlabs/shopper/issues/new) with the bug report form. It asks for the Shopper, Laravel, Livewire and PHP versions, the steps to reproduce the problem, and a link to a repository that reproduces it. Issues without a working reproduction repository are closed: a maintainer cannot fix a bug they cannot run. A pull request with a failing test that shows the bug is even more useful than a report. ## Proposing a Feature or Asking a Question [#proposing-a-feature-or-asking-a-question] Feature ideas and support questions go to [GitHub Discussions](https://github.com/shopperlabs/shopper/discussions), not to issues. For a large feature, start a discussion before writing code, so you know it fits Shopper before you spend time on it. ## Choosing a Branch [#choosing-a-branch] Each major version has its own branch. Pull requests for Shopper 3 target the `3.x` branch. New features are only accepted on the latest major version. Bug fixes can also target the previous major version while it still receives bug fixes. The [Version Support Policy](/3.x/version-support-policy) lists the dates for each version. ## Setting Up the Repository [#setting-up-the-repository] Fork the repository on GitHub, then clone your fork and install the dependencies: ```bash git clone git@github.com:/shopper.git cd shopper git checkout 3.x composer install ``` The tests run on [Orchestra Testbench](https://packages.tools/testbench) with an in-memory SQLite database, so you do not need a Laravel application or a database server to run them. They live in `tests/`, with one folder per package (`tests/Core`, `tests/Cart`, `tests/Admin` and so on), and are written with [Pest](https://pestphp.com). ## Running the Checks [#running-the-checks] Run these commands before you open a pull request. The continuous integration runs Pint, PHPStan and the test suite on every pull request. | Command | What it does | |---|---| | `composer lint` | Formats the code with Laravel Pint. | | `composer test:lint` | Fails if a file is not formatted. | | `composer test:types` | Runs the PHPStan static analysis. | | `composer test:sqlite` | Runs the Pest test suite on SQLite. | | `composer test` | Runs the type coverage check (90% minimum), PHPStan and the SQLite tests in one go. | The continuous integration runs PHPStan on PHP 8.3, 8.4 and 8.5, Pint on PHP 8.4, and the test suite on SQLite, MySQL and PostgreSQL with Laravel 12 and 13. To reproduce a MySQL or PostgreSQL failure locally, run `composer test:mysql` or `composer test:pgsql` against a local server with a `testing` database, as the continuous integration does. ## Writing a Pull Request [#writing-a-pull-request] Keep each pull request to one change. If you want to fix a bug and add a feature, send two pull requests: they are easier to review and to revert. A pull request that changes behaviour comes with tests that cover it. If it changes something the documentation describes, open a matching pull request on [shopperlabs/docs](https://github.com/shopperlabs/docs). Shopper follows [Semantic Versioning](https://semver.org/): minor and patch releases never contain breaking changes. A change that breaks a public method, a contract, a config key, an event or a migration waits for the next major version. Write the pull request title as a [Conventional Commit](https://www.conventionalcommits.org), with the package as the scope, such as `fix(cart): keep the discount when a line is removed`. Pull requests are squashed when they are merged, so the title becomes the commit message. ## Coding Style [#coding-style] Shopper follows the Laravel coding style, checked by [Laravel Pint](https://laravel.com/docs/pint). The `pint.json` file at the root of the repository adds stricter rules: every file declares `strict_types`, comparisons are strict, classes and functions are imported, and methods that return nothing declare `void`. Run `composer lint` and Pint applies them for you. Classes follow the [PSR-4](https://www.php-fig.org/psr/psr-4/) autoloading standard, under the `Shopper\` namespace. ## Security Vulnerabilities [#security-vulnerabilities] If you discover a security vulnerability in Shopper, do not open a public issue. Report it privately through [GitHub](https://github.com/shopperlabs/shopper/security/advisories/new) or by email at [arthur@shopperlabs.co](mailto:arthur@shopperlabs.co). All security vulnerabilities are addressed promptly. ## Code of Conduct [#code-of-conduct] Shopper follows the [Contributor Covenant](https://github.com/shopperlabs/shopper/blob/3.x/CODE_OF_CONDUCT.md). Report unacceptable behaviour to [arthur@shopperlabs.co](mailto:arthur@shopperlabs.co). # Currencies (/3.x/currencies) A currency is a monetary unit your store can price products in, such as the US Dollar or the Euro. Shopper ships with 158 currencies, and the merchant picks the ones the store sells in, with one of them as the store default currency. Each [price](/3.x/pricing) and each [zone](/3.x/zones) is linked to a currency, and each cart and order records the code of the currency it is in. Shopper never converts an amount from one currency to another. A store that sells in USD and EUR sets a USD price and a EUR price for each product, as described in [Selling in Several Currencies](#selling-in-several-currencies). How amounts are stored in cents and formatted is covered on the [Money](/3.x/money) page. ## Model [#model] The model is `Shopper\Core\Models\Currency`. It implements the `Shopper\Core\Models\Contracts\Currency` contract, which declares the `zone` relationship. The currency model cannot be swapped through `config/shopper/models.php`; [Models You Cannot Swap](/3.x/models#models-you-cannot-swap) shows how to add a relationship to it with `resolveRelationUsing()`. The model has a global scope named `enabled` that hides disabled currencies from every query, as described in [Enabled Currencies](#enabled-currencies). The `HasPublicId` trait fills `public_id` with a ULID when a currency is created, and adds `findByPublicId()` and the `wherePublicId` scope, as described in [Public IDs](/3.x/models#public-ids). The model casts `exchange_rate` to a float and `is_enabled` to a boolean. ### Database Schema [#database-schema] Currencies are stored in the `sh_currencies` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)). The table has no timestamps: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Currency name, such as "US Dollar" | | `code` | string(10) | no | - | ISO 4217 code, such as `USD`, unique | | `symbol` | string(25) | no | - | Currency symbol, such as `$` | | `format` | string(50) | no | - | Display pattern, such as `$1,0.00` | | `exchange_rate` | decimal(10,2) | yes | null | Exchange rate entered by the merchant | | `is_enabled` | boolean | no | true | Whether the currency is available | Shopper stores `format` and `exchange_rate` and returns them in the Store API, but uses neither. Amounts are formatted from the currency code and the application locale, as described in [Formatting Amounts](/3.x/money#formatting-amounts), and no price is ever computed from an exchange rate. The `currency_id` foreign keys of the prices and zones tables cascade on delete: deleting a currency deletes every price in that currency and every zone that uses it. Disable a currency instead of deleting it. ## How Currencies are Created [#how-currencies-are-created] The currencies come from the `database/data/currencies.json` file of the `shopper/core` package. When you run `php artisan shopper:install` and answer yes to "Run database migrations and seeders?", the `Shopper\Core\Database\Seeders\CurrenciesTableSeeder` seeder inserts the 158 currencies of that file, all enabled, with an exchange rate of `0`. If you skipped that step, run the seeders yourself: ```bash php artisan db:seed --class="Shopper\Core\Database\Seeders\ShopperSeeder" ``` `ShopperSeeder` also seeds the countries, legal pages, default channel, carriers and payment methods. To add a currency the file does not have, such as the Sierra Leonean leone introduced in 2022 (`SLE`), create it from a migration or a seeder of your application: ```php title="database/migrations/2026_09_01_000000_add_sierra_leonean_leone_currency.php" create([ 'name' => 'Sierra Leonean Leone', 'code' => 'SLE', 'symbol' => 'Le', 'format' => 'Le1,0.00', 'is_enabled' => true, ]); } }; ``` Create the row through the model so that `public_id` is filled. ## Enabled Currencies [#enabled-currencies] A currency is either enabled or disabled. The `enabled` global scope keeps disabled currencies out of every query on the model, so they are missing from the admin currency pickers, from `shopper_currency()`, from the `currency` relationship of a zone and from the Store API. Only the `currency` relationship of a price ignores the scope, so a price keeps its currency after the currency is disabled. Remove the scope to list or enable a disabled currency: ```php use Shopper\Core\Models\Currency; $disabled = Currency::query() ->withoutGlobalScope('enabled') ->where('is_enabled', false) ->orderBy('name') ->get(); Currency::query() ->withoutGlobalScope('enabled') ->where('code', 'NGN') ->update(['is_enabled' => true]); ``` The installer enables every currency. A store that sells in a few of them can disable the others, which also shortens the list a storefront gets from `GET /store/currencies`. Nothing prevents disabling a currency the store still uses. When the default currency is disabled, `shopper_currency()` returns `USD` once its one-hour cache expires. When the currency of a zone is disabled, the zone has no currency: the Store API returns prices in the store default currency for that zone, and creating a cart in that zone without a `currency_code` fails. Remove a currency from the store currencies and from its zones before you disable it. ## Store Currencies [#how-setup-store-currencies] The merchant picks the store currencies and the default currency in the setup wizard, then changes them in the Store currency section of the **General** settings page. Both lists offer the enabled currencies only, and the default currency is chosen among the selected ones. Shopper stores the choice in two [settings](/3.x/settings#setting-keys): `currencies`, an array of currency IDs, and `default_currency_id`. The store currencies decide which currencies the merchant prices in: the admin price form shows one row for each, as described in [Pricing](/3.x/pricing#configuration). The default currency is the fallback for every amount that comes without a currency, as described in [Default Currency](/3.x/money#default-currency). To read them in your code, load the currencies from the IDs, and use `shopper_currency()` for the default currency code: ```php use Shopper\Core\Models\Currency; $storeCurrencies = Currency::query() ->whereIn('id', (array) shopper_setting('currencies')) ->orderBy('name') ->get(); $defaultCode = shopper_currency(); ``` `shopper_currency()` returns `USD` when no default currency is set, and caches the code for one hour. The [Settings](/3.x/settings#writing-settings) page shows how to write both keys from code and which cache keys to forget. ## Zero-Decimal Currencies [#zero-decimal-currencies] Some currencies have no subunit, such as the Japanese yen (`JPY`) and the Central African CFA franc (`XAF`): Shopper stores their amounts in whole units instead of cents. The list of these currencies, the helpers that detect them and the upgrade command for data from Shopper 2.x are on the [Money](/3.x/money#zero-decimal-currencies) page. ## Selling in Several Currencies [#selling-in-several-currencies] A store sells in several currencies by pricing each product in each currency and by telling the storefront which currency a customer shops in. To open a store in EUR next to USD: 1. Add the Euro to the store currencies in the General settings. The admin price form of each product and variant then shows a EUR row. 2. Set a EUR price on each product, from the admin panel or in code as shown in [Multi-Currency Pricing](/3.x/pricing#multi-currency-pricing). 3. Create a [zone](/3.x/zones) for the countries that pay in EUR and give it the Euro as currency. The zone form offers the store currencies only, which is why step 1 comes first. A storefront that sends the zone of the customer gets prices in the zone currency, and the carts it creates are in that currency. It can also ask for a currency explicitly, as described in [From a Storefront](#from-a-storefront). A cart keeps its currency until the storefront changes it, and the order placed from it records the same `currency_code`: changing the default currency later changes no existing order. A product without a price in the currency of a cart cannot be added to it: the Store API answers `422` with the `price_missing` code. Shopper does not fall back to another currency or convert a price. If you want prices derived from an exchange rate, compute them in your own code and save them as prices. ## Relation to Other Entities [#relation-to-other-entities] A currency is referenced by the store settings, by zones and by prices through its ID, and by carts and orders through its code. ### Store [#store] The store holds its currencies and its default currency as settings, described in [Store Currencies](#how-setup-store-currencies). ### Zone [#zone] Each zone has exactly one currency, and a currency can be used by several zones. `currency` on a zone returns the currency, and `currency_code` its code: ```php $zone->currency; $zone->currency_code; ``` The `zone` relationship of a currency is a `HasOne` and returns a single zone even when several use the currency. To list them all, query the zones: ```php use Shopper\Core\Models\Zone; $euroZones = Zone::query() ->whereRelation('currency', 'code', 'EUR') ->get(); ``` The [Zones](/3.x/zones) page covers zones and how the Store API resolves the zone of a request. ### Price [#price] Each price belongs to one currency. `currency` on a price returns it, disabled or not, and `currency_code` returns its code. The [Pricing](/3.x/pricing#relationships) page covers prices per currency. ## Events [#events] Shopper dispatches no currency event. The currency model fires the usual Eloquent events when you save it, but the enable and disable bulk actions of the admin panel run a single update query, which fires none. The [Events](/3.x/events) page lists the events Shopper dispatches. ## Permissions [#permissions] The Currencies page, the General settings page and the setup wizard all require the `system.settings` permission. There is no permission of its own for currencies. The [Access Control](/3.x/acl#access-by-section) page lists the permissions by section. ## In the Admin [#in-the-admin] Merchants manage currencies under Settings, Currencies, at `/cpanel/setting/currencies`. The page lists every currency, enabled or not, with its name, code, symbol, exchange rate and a status toggle, searches by name or code, and filters by status. A row action edits the exchange rate, and bulk actions enable or disable the selected currencies. The store currencies and the default currency are set in the Store currency section of the General settings page. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API lists the enabled currencies on `GET /store/currencies`, paginated, 15 per page by default. It filters by `filter[name]` (partial match) and `filter[code]` (exact match) and sorts by `name` or `code`. `GET /store/currencies/{code}` returns one currency by its code, in any case, and answers `404` for a disabled or unknown code: ```json { "data": { "id": "01JD3XQ5Z8K2M4N6P8R0T2V4W6", "type": "currencies", "attributes": { "name": "US Dollar", "code": "USD", "symbol": "$", "format": "$1,0.00", "exchange_rate": 0 } } } ``` These endpoints return every enabled currency, including those that are not store currencies. To build a currency switcher, read `currencies` and `default_currency` from `GET /store/settings` instead: they hold the codes of the store currencies and the default currency code, as described in [Settings](/3.x/settings#store-api). The currency of a request is chosen per endpoint: - The product endpoints return prices in the currency of `filter[currency]`, then in the currency of the zone of the request, then in the store default currency. An unknown or disabled code in `filter[currency]` answers `422` with the `currency_unknown` code. The [Pricing](/3.x/pricing#from-a-storefront) page shows the response. - `POST /store/carts` takes an optional `currency_code`, which must be an enabled store currency. Without it, the cart takes the zone currency, then the store default currency. `PATCH` on the cart changes the currency with the same rule. The Store API [Store and Regions](/3.x/store-api/store#picking-a-zone-and-a-currency) guide shows how a storefront picks a currency. # Customers (/3.x/customers) A customer is a row of your application's `users` table. Shopper ships no customer model: the `InteractsWithShopper` trait adds the customer columns, relationships and scopes to your `User` model, and the `Shopper\Core\Models\Address` model holds each customer's address book. Team members live in the same table and are told apart by their roles, as described on the [Team](/3.x/team) page. Customers sign up through the Store API, are created by a merchant in the admin panel, or come from your own sign-up code. Shopper gives the customers it creates the customer role, named `user` by default. ## User Model Integration [#user-model-integration] Shopper does not create a separate Customer model. Your `App\Models\User` uses the `Shopper\Traits\InteractsWithShopper` trait and implements the `Shopper\Models\Contracts\ShopperUser` contract, as set up in [Installation](/3.x/installation#prepare-your-user-model). Shopper writes customers with Eloquent's `create()` and `update()`: the admin form, the Store API registration and the anonymization action pass arrays of attributes. Declare these columns as fillable on your model. The Shopper migration renames the `name` column of the Laravel skeleton to `last_name`, so `name` leaves the list: ```php title="app/Models/User.php" orders() ->latest() ->take(5) ->get(); $completedOrders = $customer->orders() ->where('status', OrderStatus::Completed) ->count(); ``` ### Addresses [#addresses] `addresses()` is a `HasMany` relation on the `user_id` column of the address table. A customer has at most one default shipping address and one default billing address: ```php $shippingAddress = $customer->addresses() ->where('shipping_default', true) ->first(); $billingAddress = $customer->addresses() ->where('billing_default', true) ->first(); ``` ### Discounts [#discounts] `discounts()` is a `MorphToMany` relation to the discounts linked to the customer in the `sh_discountables` table. That link is how a discount is limited to selected customers: the cart only applies such a discount to a signed-in customer on the list. The [Discounts](/3.x/discounts) page covers eligibility. ## Query Scopes [#query-scopes] `customers()` keeps the users who have neither the admin nor the manager role, plus every user with the `user` role. A user with no role at all matches it, and so does a team member whose only role is a custom role you created. `administrators()` keeps the users with the admin or the manager role. The role names come from [Role Configuration](#role-configuration): ```php use App\Models\User; $customers = User::query() ->customers() ->latest() ->paginate(25); $administrators = User::query() ->administrators() ->get(); ``` The customer list of the admin panel uses `customers()`. ## Role Checking [#role-checking] Four methods answer questions about a user. `isAdmin()` and `isManager()` check the roles named in `config('shopper.admin.roles')`. `canAccessDashboard()` returns `true` for admins, managers and users with the `system.dashboard` permission. `isVerified()` returns `true` once `email_verified_at` is set: ```php $user->isAdmin(); $user->isManager(); $user->canAccessDashboard(); $user->isVerified(); ``` ## Computed Attributes [#computed-attributes] Three attributes are computed from the columns: - `full_name` joins the first and last names, or returns the last name alone when there is no first name. - `roles_label` lists the display names of the user's roles, separated by commas with each word capitalized, or `N/A` when the user has no role. It runs a query each time it is read. - `picture` returns the profile picture URL. When `avatar_type` is `storage`, it is the URL of `avatar_location` on the disk set by `shopper.media.storage.disk_name`. Otherwise it is an avatar generated by the ui-avatars.com service from the full name, in the colors of `shopper.admin.avatar.color` and `shopper.admin.avatar.bg_color`. ```php $customer->full_name; $customer->roles_label; $customer->picture; ``` `HasProfilePhoto` appends `picture` to the array and JSON form of the user, so it appears whenever you serialize a user. ## Address Model [#address-model] The model configured for addresses is `Shopper\Core\Models\Address`. It implements the `Shopper\Core\Models\Contracts\Address` contract and is registered under the `address` key of `config/shopper/models.php`. It uses `HasPublicId`, so each address gets a ULID in `public_id`, and it guards no column: `create()` and `update()` accept every column. ### Extending the Address Model [#extending-the-address-model] To add your own casts or scopes, extend the core class: ```php title="app/Models/Address.php" 'array', ]; } #[Scope] protected function shipping(Builder $query): void { $query->where('type', AddressType::Shipping); } } ``` Then point the `address` key of the configuration to your class: ```php title="config/shopper/models.php" 'address' => App\Models\Address::class, ``` The `addresses()` relation of your user model and the address observer follow the swap. The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ### Address Relationships [#address-relationships] Each address belongs to a user and, optionally, to a country. `user()` reads the user class from `config('auth.providers.users.model')`; `country()` returns a `Shopper\Core\Models\Country`, or `null` when the country was deleted: ```php $address->user->email; $address->country?->translated_name; $address->country?->cca2; ``` ### Address Methods [#address-methods] `isShippingDefault()` and `isBillingDefault()` read the two default flags, and `full_name` joins the first and last names the same way as on the user: ```php $address->isShippingDefault(); $address->isBillingDefault(); $address->full_name; ``` ## Observer Behavior [#observer-behavior] Two hooks keep the address book consistent. `Shopper\Core\Observers\AddressObserver` runs when an address is created or updated. When the address has `shipping_default` set, the observer removes the flag from the customer's previous default shipping address; it does the same for `billing_default`. The flags are exclusive per customer whatever the address type, so setting `shipping_default` on a billing address takes the flag from the shipping address that held it. The observer saves the previous default quietly: that address fires no model event. When a user is deleted, the `deleting` hook of `InteractsWithShopper` detaches all of its roles and deletes its addresses with a single query, so no address model event fires. Orders and carts stay, with their customer set to `null`. Deleting a default address leaves the customer without a default of that kind: Shopper promotes no other address. ## Anonymization [#anonymization] The admin panel anonymizes a customer instead of deleting the account, so orders keep their customer and the sales reports stay complete. A merchant with the `customers.delete` permission runs the Anonymize action from the customer page. In one transaction it: - replaces the first and last names with the translated `Deleted` and `Customer` (the `shopper::pages/customers.anonymize` keys); - replaces the email with `anonymized_{id}_{random}@anonymized.local`, where `{random}` is eight random characters; - sets `phone_number`, `gender`, `avatar_location`, `birth_date`, `email_verified_at`, `last_login_at`, `last_login_ip`, `store_two_factor_secret` and `store_two_factor_recovery_codes` to `null`; - sets `opt_in` to `false` and `avatar_type` to `gravatar`, so `picture` returns a generated avatar; - deletes all the customer's addresses. The user row stays, with its ID, public ID, password and roles. Each order keeps the email and the addresses captured when it was placed, in its own columns and in the order addresses table, and each cart keeps its email and its cart addresses. Shopper dispatches no event when it anonymizes a customer, and the action exists only in the admin panel: there is no action class, Artisan command or Store API endpoint for it. To offer a "Delete my account" page on your storefront, apply the same changes from your own code. This example also revokes the customer's Store API tokens: ```php title="app/Http/Controllers/AccountDeletionController.php" user(); DB::transaction(function () use ($customer): void { $customer->update([ 'first_name' => __('shopper::pages/customers.anonymize.first_name'), 'last_name' => __('shopper::pages/customers.anonymize.last_name'), 'email' => 'anonymized_'.$customer->id.'_'.Str::random(8).'@anonymized.local', 'phone_number' => null, 'gender' => null, 'avatar_type' => 'gravatar', 'avatar_location' => null, 'birth_date' => null, 'email_verified_at' => null, 'last_login_at' => null, 'last_login_ip' => null, 'store_two_factor_secret' => null, 'store_two_factor_recovery_codes' => null, 'opt_in' => false, ]); $customer->addresses()->delete(); $customer->tokens()->delete(); }); Auth::guard('web')->logout(); $request->session()->invalidate(); return redirect('/'); } } ``` ## Configuration [#configuration] Customers have no feature flag: the customers section of the admin panel is always registered. Their settings are the role names, the address model key described in [Extending the Address Model](#extending-the-address-model) and the admin components. ### Role Configuration [#role-configuration] Role names are defined in `config/shopper/admin.php`. Shopper gives new customers the role named by `shopper.admin.roles.user`, and the scopes and role checks read the same keys: ```php title="config/shopper/admin.php" 'roles' => [ 'admin' => 'administrator', 'manager' => 'manager', 'user' => 'user', ], ``` Read the role through `config('shopper.admin.roles.user')` in your code rather than writing `'user'`. The [Access Control](/3.x/acl#roles) page describes what each role can do. ### Components [#components] The customers section of the admin panel is made of three pages and three components. To replace one with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish customer ``` The command creates `config/shopper/components/customer.php`: ```php title="config/shopper/components/customer.php" use Shopper\Livewire; use Shopper\Livewire\Components; return [ 'pages' => [ 'customer-index' => Livewire\Pages\Customers\Index::class, 'customer-create' => Livewire\Pages\Customers\Create::class, 'customer-show' => Livewire\Pages\Customers\Show::class, ], 'components' => [ 'customers.addresses' => Components\Customers\Addresses::class, 'customers.orders' => Components\Customers\Orders::class, 'customers.profile' => Components\Customers\Profile::class, ], ]; ``` The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below use `App\Models\User` for customers and resolve the address class from its contract, so they keep working after you swap the address model. ### Creating Customers [#creating-customers] Create the user, give it the customer role and add its first address in one transaction. The admin panel and the Store API dispatch `CustomerRegistered` after creating a customer; dispatch it from your own sign-up code as well, so your listeners and webhooks see every new customer: ```php use App\Models\User; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Shopper\Core\Enum\AddressType; use Shopper\Core\Enum\GenderType; use Shopper\Core\Events\Customers\CustomerRegistered; use Shopper\Core\Models\Country; $customer = DB::transaction(function () use ($request): User { $customer = User::query()->create([ 'first_name' => 'Jane', 'last_name' => 'Cooper', 'email' => 'jane.cooper@example.com', 'password' => Hash::make($request->string('password')), 'gender' => GenderType::Female, 'phone_number' => '+1 212 555 0148', 'opt_in' => true, ]); $customer->assignRole(config('shopper.admin.roles.user')); $customer->addresses()->create([ 'first_name' => 'Jane', 'last_name' => 'Cooper', 'street_address' => '350 Fifth Avenue', 'city' => 'New York', 'state' => 'NY', 'postal_code' => '10118', 'country_id' => Country::query()->where('cca2', 'US')->value('id'), 'type' => AddressType::Shipping, 'shipping_default' => true, ]); event(new CustomerRegistered($customer)); return $customer; }); ``` `CustomerRegistered` waits for the transaction to commit before it reaches its listeners. ### Retrieving Customers [#retrieving-customers] The `customers()` scope combines with any Eloquent query. A newsletter export keeps the customers who opted in and verified their email: ```php use App\Models\User; $customers = User::query() ->customers() ->withCount('orders') ->latest() ->paginate(25); $newsletterAudience = User::query() ->customers() ->where('opt_in', true) ->whereNotNull('email_verified_at') ->get(['id', 'first_name', 'last_name', 'email']); $customer = User::findByPublicId($publicId); ``` To search customers by name or email, use Laravel Scout and restrict the results with the scope: ```php use App\Models\User; use Illuminate\Database\Eloquent\Builder; $matches = User::search('cooper') ->query(fn (Builder $query) => $query->customers()) ->get(); ``` The admin customer page counts an order as paid when its status is `Processing` or `Completed` and its payment status is `Paid`, and sums the `price_amount` of those orders in the default currency of the store, returned by `shopper_currency()`. The same lifetime value in your code, in [cents](/3.x/money): ```php use App\Models\User; use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Enum\PaymentStatus; $paidOrders = fn (Builder $query) => $query ->whereIn('status', [OrderStatus::Processing, OrderStatus::Completed]) ->where('payment_status', PaymentStatus::Paid) ->where('currency_code', shopper_currency()); $customer = User::query() ->customers() ->withCount(['orders as paid_orders_count' => $paidOrders]) ->withSum(['orders as lifetime_value' => $paidOrders], 'price_amount') ->findOrFail($customerId); ``` ### Managing Addresses [#managing-addresses] Add an address through the `addresses()` relation, which fills `user_id`. Countries are referenced by ID; look one up by its two-letter `cca2` code. Pass `shipping_default` or `billing_default` to make the address the customer's default: ```php use Shopper\Core\Enum\AddressType; use Shopper\Core\Models\Country; $address = $customer->addresses()->create([ 'first_name' => 'Jane', 'last_name' => 'Cooper', 'company_name' => 'Cooper Studio', 'street_address' => '1600 Amphitheatre Parkway', 'city' => 'Mountain View', 'state' => 'CA', 'postal_code' => '94043', 'phone_number' => '+1 650 555 0199', 'country_id' => Country::query()->where('cca2', 'US')->value('id'), 'type' => AddressType::Billing, 'billing_default' => true, ]); ``` To change the default, set the flag on the new address. The [observer](#observer-behavior) removes it from the previous default, so there is nothing to clear first: ```php $address->update(['shipping_default' => true]); ``` When the address comes from a request, scope the lookup to the signed-in customer so that one customer can never read or change another's address. Look addresses up by public ID, as the Store API does: ```php use Shopper\Core\Models\Contracts\Address; $address = resolve(Address::class)::query() ->whereBelongsTo($request->user(), 'user') ->wherePublicId($publicId) ->firstOrFail(); $address->delete(); ``` The address book is separate from checkout. A cart stores its own shipping and billing addresses, with different field names, and placing an order copies the cart addresses to the order without writing to the address book. To prefill a checkout from a saved address, map the fields to the cart address fields described on the [Cart](/3.x/cart) page: | Address column | Cart address field | |----------------|--------------------| | `first_name` | `first_name` | | `last_name` | `last_name` | | `company_name` | `company` | | `street_address` | `address_1` | | `street_address_plus` | `address_2` | | `city` | `city` | | `state` | `state` | | `postal_code` | `postal_code` | | `phone_number` | `phone` | | `country->cca2` | `country_code` | ### Storefront Example [#storefront-example] An account controller for a Blade storefront: the account page with orders and addresses, the profile form and the address form: ```php title="app/Http/Controllers/AccountController.php" user(); return view('account.show', [ 'customer' => $customer, 'orders' => $customer->orders()->latest()->paginate(10), 'addresses' => $customer->addresses()->with('country')->get(), ]); } public function updateProfile(Request $request): RedirectResponse { $validated = $request->validate([ 'first_name' => ['nullable', 'string', 'max:255'], 'last_name' => ['required', 'string', 'max:255'], 'phone_number' => ['nullable', 'string', 'max:255'], 'birth_date' => ['nullable', 'date', 'before:today'], 'gender' => ['nullable', Rule::enum(GenderType::class)], 'opt_in' => ['boolean'], ]); $request->user()->update($validated); return back()->with('status', 'profile-updated'); } public function storeAddress(Request $request): RedirectResponse { $validated = $request->validate([ 'first_name' => ['required', 'string', 'max:255'], 'last_name' => ['required', 'string', 'max:255'], 'company_name' => ['nullable', 'string', 'max:255'], 'street_address' => ['required', 'string', 'max:255'], 'street_address_plus' => ['nullable', 'string', 'max:255'], 'city' => ['required', 'string', 'max:255'], 'state' => ['nullable', 'string', 'max:255'], 'postal_code' => ['required', 'string', 'max:255'], 'phone_number' => ['nullable', 'string', 'max:255'], 'country_id' => ['required', Rule::exists(shopper_table('countries'), 'id')], 'type' => ['required', Rule::enum(AddressType::class)], 'shipping_default' => ['boolean'], 'billing_default' => ['boolean'], ]); $request->user()->addresses()->create($validated); return back()->with('status', 'address-added'); } } ``` `shopper_table()` adds the Shopper table prefix, so the `exists` rule checks `sh_countries`. ## Events [#events] Shopper dispatches one customer event, `Shopper\Core\Events\Customers\CustomerRegistered`, with the new user in `public Authenticatable $customer`. It fires when a merchant creates a customer in the admin panel and when a customer signs up through the Store API, once the surrounding transaction commits. Your own sign-up code dispatches it itself, as shown in [Creating Customers](#creating-customers). The `customer.registered` [webhook](/3.x/webhooks) sends it to other systems: ```php title="app/Providers/AppServiceProvider.php" use App\Notifications\WelcomeCustomer; use Illuminate\Support\Facades\Event; use Shopper\Core\Events\Customers\CustomerRegistered; public function boot(): void { Event::listen(function (CustomerRegistered $event): void { $event->customer->notify(new WelcomeCustomer()); }); } ``` Shopper also listens to `OrderCreated` and gives the customer of each new order the customer role. Addresses dispatch only the Eloquent model events. The [Events](/3.x/events#customer-events) page lists the sign-in events of the Store API. ## Permissions [#permissions] The admin panel checks four permissions of the `customers` resource: | Permission | Allows | |------------|--------| | `customers.browse` | Opening the customers list, seeing the Customers sidebar item and the customer figures of the dashboard | | `customers.read` | Opening a customer page | | `customers.create` | Opening and saving the form for a new customer | | `customers.delete` | Anonymizing a customer | `customers.edit` is seeded with the others, but the admin panel never checks it: there is no form to edit a customer. Shopper 2.x named these permissions `browse_customers`, `add_customers` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants manage customers under Customers. The list shows each customer's name, email, the country of their first address, the number of paid orders and the registration date, filters by email verification and registration date, and sits under four figures: total customers, customers registered in the last 30 days, customers with a paid order, and the average lifetime value in the store currency. The create form takes the name, email, phone, gender, a password and a shipping address, with the marketing consent. The customer page shows the profile, the shipping and billing addresses, the orders and the paid order totals, and holds the Anonymize action. Merchants cannot edit a customer's profile or addresses. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API handles sign-up and the customer account under the `store` prefix, set by `SHOPPER_API_PREFIX`. Sign-up and sign-in return a Laravel Sanctum token in `meta.token`, which the storefront sends as a bearer token. Your `User` model needs Sanctum's `HasApiTokens` trait, which `php artisan shopper:api:install` offers to add. Tokens expire after `shopper.api.token_expiration` minutes (`SHOPPER_API_TOKEN_EXPIRATION`, 30 days by default). | Endpoint | Does | |----------|------| | `POST /store/auth/register` | Creates a customer with the `user` role, dispatches `CustomerRegistered` and answers 201 with a token. A guest `cart_id` sent with the request is attached to the new account | | `POST /store/auth/login` | Answers with a token. After `shopper.http.login_failures` failed attempts (5 by default) for one email and IP address, it refuses further attempts for one minute | | `POST /store/auth/logout` | Revokes the token of the request | | `POST /store/auth/forgot-password` | Sends a password reset link | | `POST /store/auth/reset-password` | Sets a new password from a reset token | A signed-in customer manages their account under `/store/customers/me`: | Endpoint | Does | |----------|------| | `GET /store/customers/me` | Returns the customer | | `PATCH /store/customers/me` | Updates `first_name`, `last_name`, `phone_number`, `birth_date`, `gender` and `opt_in` | | `POST /store/customers/me/avatar` | Uploads a profile picture, an image of up to 1024 KB | | `DELETE /store/customers/me/avatar` | Removes the picture, so `avatar` returns the generated one | | `GET /store/customers/me/addresses` | Lists the addresses, newest first | | `POST /store/customers/me/addresses` | Creates an address, with the country given as `country_code`, and answers 201 | | `PATCH /store/customers/me/addresses/{id}` | Updates an address of the customer | | `DELETE /store/customers/me/addresses/{id}` | Deletes an address of the customer and answers 204 | | `GET /store/customers/me/orders` | Lists the customer's orders, newest first | | `GET /store/customers/me/orders/{id}` | Returns one order of the customer | | `GET /store/customers/me/orders/{orderId}/items/{itemId}/files/{fileId}` | Returns a five-minute download link for a file of a paid order, described in [Downloadable Files](/3.x/products#downloadable-files) | A customer resource has the type `customers` and carries `first_name`, `last_name`, `email`, `avatar` (the `picture` URL), `avatar_type`, `phone_number`, `gender`, `birth_date`, `opt_in`, `email_verified` (a boolean) and `created_at`. An address resource has the type `addresses`, carries the address columns except `metadata`, with `country_code` in place of `country_id`, and is identified by its public ID. An address or an order of another customer answers 404. The Store API changes neither the email nor the password of a signed-in customer outside the reset flow, and has no endpoint to delete or anonymize an account. The Store API [Customers](/3.x/store-api/customers) guide covers the profile and address endpoints. # Dashboard (/3.x/dashboard) The dashboard is the first screen after login. A new store sees a setup guide that walks through the first products, shipping, payments and taxes. Once the guide is done, the dashboard shows the month's revenue, orders and customers, a 12-month revenue chart, the best-selling products and the latest orders. ## Widgets [#widgets] The dashboard page renders four Livewire components. The stat cards, the top products and the recent orders load lazily: the page shows a placeholder for each and fills it once the first paint is done, so a slow query never holds the whole page. Revenue is counted the same way in the stat card and the chart: the order totals with a payment status of Paid, Partially refunded or Refunded, minus the settled `OrderRefund` records of the period. Shopper's payment service does not create these records, so a refund only lowers the revenue once your application records it, as described in [Order Refunds](/3.x/payments#order-refunds). ### Stat Cards [#stat-cards] Four cards compare the current month, from the 1st to today, with the same span of the previous month: | Card | Value | Permission | |------|-------|------------| | Revenue this month | Net revenue of the month in the store's default currency | `orders.browse` | | Total Products | Total number of products | `products.browse` | | Total Orders | Total number of orders, excluding Cancelled and Archived orders | `orders.browse` | | Total Customers | Total number of customers (users matched by the `customers` scope) | `customers.browse` | Each card shows the change against the previous month with a green or red trend indicator, and links to its admin section. A user only sees the cards their permissions allow. ### Revenue Chart [#revenue-chart] A bar chart of the net revenue for each of the last 12 months, the current one included. When the store has several currencies, a dropdown switches the chart from one currency to another; the default currency is selected first. ### Top Selling Products [#top-selling-products] The 6 products sold in the largest quantities over the last 90 days, counting only orders that bear revenue. Sales of variants are added to their parent product. Each row shows the product thumbnail, its name, the units sold and the average rating of its reviews. ### Recent Orders [#recent-orders] The 7 latest orders, excluding Cancelled and Archived orders. Each row shows the order number, the first product with its thumbnail, the total and the order status, and opens the order on click. The revenue chart, the top products and the recent orders are shown only to users with the `orders.browse` permission. ## Setup Guide [#setup-guide] A new store sees a checklist in place of the widgets. Each step is ticked automatically when the matching data exists in the database, and links to the screen where the merchant creates it: | Step | Completed when | Permission | |------|----------------|------------| | Add a product | At least one product exists | `products.create` | | Create a collection | At least one collection exists | `collections.create` | | Set up shipping zones | At least one enabled zone exists | `system.settings` | | Set up payment methods | At least one enabled payment method exists | `system.settings` | | Configure taxes | At least one tax zone exists | `system.settings` | The seeders create an enabled cash on delivery payment method, so a fresh install starts at 1 of 5. When the dashboard loads with every step complete, and the user is an administrator or has the `system.settings` permission, the guide saves the `setup_guide_done` setting and the widgets replace it. The guide does not come back after that. The same users can also dismiss it before the end. ## Caching [#caching] Each widget caches its data with Laravel's `Cache::flexible()`. While the value is fresh, it is served from the cache. Between the fresh and the stale limits, the cached value is still served and Laravel recomputes it after the response is sent. Past the stale limit, the next request recomputes it. | Widget | Cache key | Fresh | Stale | |--------|-----------|-------|-------| | Stat cards | `dashboard:stat-cards:{locale}:{currency}` | 5 min | 30 min | | Revenue chart | `dashboard:revenue:{currency}` | 5 min | 30 min | | Top selling products | `dashboard:top-products` | 5 min | 30 min | | Recent orders | `dashboard.orders:recent-ids` | 1 min | 5 min | After a bulk import or a data fix, forget the keys to see the new figures at once: ```php use Illuminate\Support\Facades\Cache; Cache::forget('dashboard:stat-cards:en:USD'); Cache::forget('dashboard:revenue:USD'); Cache::forget('dashboard:top-products'); Cache::forget('dashboard.orders:recent-ids'); ``` ## Access Requirements [#access-requirements] Every page of the admin panel behind the login, the dashboard included, goes through the same middleware. It checks two things: - The user is an administrator, a manager, or has the `system.dashboard` permission. Otherwise Shopper redirects to its forbidden page. - The store has an email and a street address in its settings. Otherwise Shopper redirects to the store setup wizard, which asks for them on the first login. The roles and permissions are described on the [Permissions](/3.x/acl) page. ## Customizing the Dashboard [#customizing-the-dashboard] You can replace the whole page, replace one widget, or add content above and below the widgets. ### Replacing the Page [#replacing-the-page] The dashboard page is registered in a component configuration file. Publish it: ```bash php artisan shopper:component:publish dashboard ``` The command creates `config/shopper/components/dashboard.php`: ```php title="config/shopper/components/dashboard.php" use Shopper\Livewire\Components; use Shopper\Livewire\Pages; return [ 'pages' => [ 'dashboard' => Pages\Dashboard::class, ], 'components' => [ 'locale-switcher' => Components\LocaleSwitcher::class, ], ]; ``` Point the `dashboard` entry to your own Livewire component: ```php title="config/shopper/components/dashboard.php" 'pages' => [ 'dashboard' => App\Livewire\Shopper\Dashboard::class, ], ``` Extend `Shopper\Livewire\Pages\AbstractPageComponent` so that your component renders inside the admin panel layout, like every Shopper page. A minimal version: ```php title="app/Livewire/Shopper/Dashboard.php" namespace App\Livewire\Shopper; use Illuminate\Contracts\View\View; use Shopper\Livewire\Pages\AbstractPageComponent; final class Dashboard extends AbstractPageComponent { public function render(): View { return view('livewire.shopper.dashboard') ->title(__('Dashboard')); } } ``` ### Replacing a Widget [#replacing-a-widget] To swap one widget, for example the revenue chart for a report of your own, override the dashboard view. Shopper has no publish tag for its views: copy `vendor/shopper/framework/resources/views/livewire/pages/dashboard.blade.php` to `resources/views/vendor/shopper/livewire/pages/dashboard.blade.php`, and Laravel loads your copy instead of the package view. The view shows the setup guide until it is done, then the widgets: ```blade title="resources/views/vendor/shopper/livewire/pages/dashboard.blade.php" @if ($this->showSetupGuide) @else @can('orders.browse') @endcan @endif ``` Replace any tag with your own Livewire component or Blade content. Your copy no longer follows changes to the package view, so compare it with the original after each Shopper upgrade. ### Adding Content with Render Hooks [#adding-content-with-render-hooks] To add content without replacing anything, register a view on the `DASHBOARD_START` or `DASHBOARD_END` render hook in the `boot` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; public function boot(): void { Shopper::renderHook( LayoutRenderHook::DASHBOARD_START, fn (): string => view('shopper.dashboard.stock-alerts')->render(), ); Shopper::renderHook( LayoutRenderHook::DASHBOARD_END, fn (): string => view('shopper.dashboard.monthly-report')->render(), ); } ``` Both hooks render on the setup guide too, so a banner registered there is seen from the first login. # Discounts (/3.x/discounts) A discount takes an amount off a cart: 20% off the whole order with the `SUMMER20` code, $10.00 off orders above $50.00, or 15% off the Classic T-Shirt for a list of customers. The customer enters a code, or the cart applies an automatic discount without one. Several discounts can apply to the same cart, in the order their exclusivity class and priority decide. Each discount carries its own rules: dates, usage limits, a minimum purchase, the customers who can use it and the zone it is sold in. A [campaign](/3.x/campaigns) can group several discounts under a shared budget. The models and enums live in `shopper/core`. The rules that decide whether a discount applies and how much it takes off live in `shopper/cart`, in `Shopper\Cart\Discounts\DiscountValidator` and `Shopper\Cart\Discounts\PromotionResolver`, which the [calculation pipeline](/3.x/cart#calculation-pipeline) runs every time a cart is calculated. ## Models [#models] Shopper uses three models for discounts: | Model | Purpose | |-------|---------| | `Shopper\Core\Models\Discount` | The discount: code, type, value and rules | | `Shopper\Core\Models\DiscountDetail` | Links a discount to a product it applies to or a customer who can use it | | `Shopper\Core\Models\OrderPromotion` | One discount applied to an order, documented on the [Orders](/3.x/orders) page | `Discount` implements the `Shopper\Core\Models\Contracts\Discount` contract. None of these models has a key in `config/shopper/models.php`, so they are always loaded with their own class: write `Shopper\Core\Models\Discount` in your code, and add a relationship with `resolveRelationUsing()`, as shown in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). The `HasPublicId` trait fills the `public_id` of a discount with a ULID when it is created, so you can find a discount with `Discount::findByPublicId()` or the `wherePublicId()` scope, described in [Public IDs](/3.x/models#public-ids). ## Database Schema [#database-schema] Discounts use two tables: one row per discount, and one row per product or customer linked to a discount. ### Discount Table [#discount-table] The `sh_discounts` table holds one row per discount (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `code` | string | yes | null | Code the customer enters, unique; null for an automatic discount | | `trigger` | string | no | `code` | `code` or `automatic`, cast to `PromotionSource` | | `type` | string | no | - | `percentage` or `fixed_amount`, cast to `DiscountType` | | `value` | integer | no | - | Percentage, or amount in cents | | `is_active` | boolean | no | `false` | Turns the discount on | | `apply_to` | string | no | - | `order` or `products`, a `DiscountApplyTo` value | | `min_required` | string | no | - | `none`, `price` or `quantity`, a `DiscountRequirement` value | | `min_required_value` | string | yes | null | Minimum subtotal in cents, or minimum quantity | | `eligibility` | string | no | - | Key of the eligibility rule, such as `everyone` or `customers` | | `usage_limit` | unsigned integer | yes | null | Uses allowed across all customers, null for no limit | | `usage_limit_per_user` | boolean | no | `false` | Allows one use per customer | | `total_use` | unsigned integer | no | 0 | Uses so far | | `start_at` | datetime | no | - | Start of the discount | | `end_at` | datetime | yes | null | End of the discount, null when it never expires | | `zone_id` | bigint | yes | null | Zone the discount is limited to, null for every zone | | `campaign_id` | bigint | yes | null | Campaign of the discount | | `exclusivity_class` | string | no | `order` | `order`, `product` or `shipping`, cast to `ExclusivityClass` | | `combinable` | boolean | no | `false` | Lets the discount stack with another discount of its class | | `priority` | integer | no | 0 | Order within the class, highest first | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | `start_at` has no default, so pass it when you create a discount. Several automatic discounts can have a null `code`: the unique index accepts more than one null. Deleting a zone or a campaign sets `zone_id` or `campaign_id` to null. Shopper updates `total_use` at checkout; leave it out of your own writes. ### Discountable Table (Pivot) [#discountable-table-pivot] The `sh_discountables` table holds the `DiscountDetail` rows, one per product or customer linked to a discount: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `discount_id` | bigint | no | - | Foreign key to the discount, rows are deleted with it | | `discountable_type` | string | no | - | Morph type of the linked model | | `discountable_id` | unsigned bigint | no | - | ID of the linked model | | `condition` | string | yes | null | `apply_to` or `eligibility`, cast to `DiscountCondition` | | `total_use` | unsigned integer | no | 0 | Not updated by Shopper | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A unique index on `discount_id`, `discountable_type` and `discountable_id` links a model to a discount once. The orders table copies the discount that took the largest amount into its `discount_id`, `discount_code`, `discount_type`, `discount_value_at_apply` and `discount_currency_code` columns, and the `sh_order_promotions` table keeps every discount applied to the order. The [Orders](/3.x/orders) page documents both. ## Discount Type [#discount-type] The `type` column is cast to `Shopper\Core\Enum\DiscountType`, which sets what `value` means: | Case | Value | `value` holds | |------|-------|---------------| | `DiscountType::Percentage` | `percentage` | The percentage, from 1 to 100 | | `DiscountType::FixedAmount` | `fixed_amount` | The amount, in [cents](/3.x/money) | A percentage is computed on each line the discount applies to and rounded to the nearest cent per line. A fixed amount is capped at the subtotal of the lines it applies to, then split between them in proportion to their subtotals; the last line takes what is left, so the parts always add up to the amount. ## Discount Application [#discount-application] The `apply_to` column holds a `Shopper\Core\Enum\DiscountApplyTo` value: | Case | Value | Lines the discount reduces | |------|-------|----------------------------| | `DiscountApplyTo::Order` | `order` | Every line of the cart | | `DiscountApplyTo::Products` | `products` | The lines of the products linked to the discount, and of their variants | A discount reduces line subtotals: the shipping amount is never discounted. The cart records what each discount takes off each line, and tax is computed on the line subtotal minus those amounts, as described on the [Taxes](/3.x/taxes) page. ## Discount Eligibility [#discount-eligibility] The `eligibility` column holds the key of an eligibility rule, which decides who can use the discount. `Shopper\Cart\Discounts\DiscountEligibilityManager` holds the rules, and Shopper registers two of them, whose keys are the cases of `Shopper\Core\Enum\DiscountEligibility`: | Key | Rule | Passes when | |-----|------|-------------| | `everyone` | `Shopper\Cart\Discounts\Eligibility\EveryoneEligibilityRule` | Always | | `customers` | `Shopper\Cart\Discounts\Eligibility\CustomersEligibilityRule` | The cart belongs to a customer linked to the discount | The `customers` rule refuses a guest cart with "Discount requires a logged-in customer." and a customer who is not linked with "Customer is not eligible for this discount.". Eligible customers are `DiscountDetail` rows with the `Eligibility` condition and the class of your user model, `config('auth.providers.users.model')`, as `discountable_type`. To set the eligible customers of a discount, call `Shopper\Cart\Discounts\SyncDiscountEligibilityAction`. It replaces the eligibility rows of the discount with the IDs you pass, using the morph type of the rule. It does not change the `eligibility` column, so set the column yourself, as shown in [VIP Customer Discount](#vip-customer-discount). ### Custom Eligibility Rules [#custom-eligibility-rules] A rule implements `Shopper\Cart\Contracts\DiscountEligibilityRule`. `key()` is the value stored in the `eligibility` column, `label()` and `description()` appear in the admin panel, `discountableType()` is the morph type of the models the rule links to a discount (null when it links none), and `passes()` decides for a cart. This rule keeps a discount for customers who never ordered: ```php title="app/Discounts/FirstOrderEligibilityRule.php" cart->customer_id; if ($customerId === null) { return new DiscountValidationResult(false, __('Sign in to use this discount.')); } $hasOrdered = resolve(Order::class)::query() ->where('customer_id', $customerId) ->exists(); if ($hasOrdered) { return new DiscountValidationResult(false, __('This discount is for your first order.')); } return new DiscountValidationResult(true); } } ``` Register the rule in the `boot` method of a service provider that every process loads (web requests, the Store API and queue workers), so the cart finds it wherever it is calculated: ```php title="app/Providers/AppServiceProvider.php" use App\Discounts\FirstOrderEligibilityRule; use Shopper\Cart\Discounts\DiscountEligibilityManager; public function boot(): void { resolve(DiscountEligibilityManager::class)->register(new FirstOrderEligibilityRule); } ``` The discount form of the admin panel lists every registered rule with its label and description. A rule that links models, like `customers`, also needs a field to pick them: `Shopper\Discounts\DiscountEligibilityFieldRegistry` from the admin package holds these fields, and its `register()` method takes the rule key, the form state key, a closure that returns the Filament schema component, and a closure that keeps the allowed IDs among the submitted ones. A rule that links nothing, like the one above, needs no field. ## Discount Requirements [#discount-requirements] The `min_required` column holds a `Shopper\Core\Enum\DiscountRequirement` value, and `min_required_value` the minimum: | Case | Value | `min_required_value` | |------|-------|----------------------| | `DiscountRequirement::None` | `none` | Not used | | `DiscountRequirement::Price` | `price` | Minimum subtotal, in cents | | `DiscountRequirement::Quantity` | `quantity` | Minimum number of items | The price requirement compares the subtotal of the whole cart before any discount (unit price times quantity, for every line), whatever `apply_to` is. The quantity requirement adds up the quantities of every line. `min_required_value` is a string column: the cart reads it as an integer. ## Discount Condition [#discount-condition] The `condition` column of a `DiscountDetail` row is cast to `Shopper\Core\Enum\DiscountCondition` and says why the model is linked: | Case | Value | Linked model | |------|-------|--------------| | `DiscountCondition::ApplyTo` | `apply_to` | A product the discount applies to | | `DiscountCondition::Eligibility` | `eligibility` | A customer who can use the discount | ## Relationships [#relationships] A discount has its linked products and customers, a zone, a campaign and the orders it was used on. ### Items (DiscountDetail) [#items-discountdetail] `items()` returns the `DiscountDetail` rows of the discount, a `HasMany` on `discount_id`. Each row points to its model through the polymorphic `discountable()` relationship, and `discount()` returns its discount: ```php use Shopper\Core\Enum\DiscountCondition; use Shopper\Core\Models\Discount; $discount = Discount::query()->where('code', 'TSHIRT15')->firstOrFail(); $products = $discount->items() ->where('condition', DiscountCondition::ApplyTo) ->with('discountable') ->get() ->pluck('discountable'); ``` Link a product with its morph alias, `$product->getMorphClass()` (`product` in the [morph map](/3.x/models#morph-map)), so that `$product->discounts` finds the discount. Link a customer with the class of your user model, which `SyncDiscountEligibilityAction` does for you. ### Zone [#zone] `zone()` returns the zone the discount is limited to, or null when it applies in every [zone](/3.x/zones). A cart in another zone is refused with "Discount is not available in this zone.". The zone also sets the currency of a fixed amount: a fixed-amount discount applies only to carts in the currency of its zone, or in the store default currency (`shopper_currency()`) when it has no zone. Once a fixed-amount discount has been used, its zone is frozen: saving a new `zone_id` throws `Shopper\Core\Exceptions\DiscountZoneFrozenException`, so past orders keep the currency they were discounted in. ### Campaign [#campaign] `campaign()` returns the campaign of the discount, or null. A campaign adds a currency check and a shared budget to the rules of its discounts, as described in [Campaigns and Discounts](/3.x/campaigns#campaigns-and-discounts). ### Orders [#orders] Every order a discount was applied to has an `OrderPromotion` row with the code, type, value and amount at checkout. `orders()` is a `HasMany` on the `discount_id` column of the orders table, which holds only the discount that took the largest amount from each order. To list every order that used a discount, query the promotions: ```php use Shopper\Core\Models\OrderPromotion; $orderIds = OrderPromotion::query() ->where('discount_id', $discount->id) ->pluck('order_id'); ``` From the order side, `$order->promotions` returns its `OrderPromotion` rows. ## Value Handling [#value-handling] The `value` of a percentage discount is the percentage as a whole number: `20` takes 20% off. The `value` of a fixed-amount discount is in [cents](/3.x/money): `1000` takes $10.00 off. `Shopper\Core\Observers\DiscountObserver` checks the value each time a discount is saved and throws `Shopper\Core\Exceptions\InvalidDiscountValueException` when it is 0 or less, or when a percentage is above 100. Once a discount has been used (`total_use` above 0), its terms are frozen: saving a new `code`, `type` or `value` throws `Shopper\Core\Exceptions\DiscountTermsFrozenException`, so past orders keep matching the discount they used. To offer different terms, create a new discount, or duplicate the used one from the admin panel and change the copy. ## Dates [#dates] `start_at` is required: a discount applies from that moment. `end_at` is optional, and a discount without one never expires. The cart compares both dates with the current time on every calculation. Before `start_at`, the code is refused with "Discount has not started yet.", and after `end_at` with "Discount has expired.". The checkout checks the dates again when it creates the order. A discount stays off until `is_active` is `true`, whatever its dates. The `active()` scope combines the three columns with the usage limit, as shown in [Retrieving Discounts](#retrieving-discounts). ## Discount Status [#discount-status] The `status` attribute returns a `Shopper\Core\Enum\DiscountStatus`, computed when you read it. The first matching row wins: | Status | When | |--------|------| | `Draft` | The discount is not saved yet | | `Disabled` | `is_active` is `false` | | `Expired` | `end_at` is in the past | | `LimitReached` | `total_use` reached `usage_limit` | | `Scheduled` | `start_at` is in the future | | `Inapplicable` | The discount applies to products and every linked product was deleted | | `Active` | None of the above | Each case has `getLabel()`, `getColor()` and `getIcon()` for display. The status reads the discount alone: it does not check the campaign budget, the eligibility or a cart. ## Automatic Discounts [#automatic-discounts] An automatic discount applies without a code. Its `trigger` column is `automatic` (`Shopper\Core\Enum\PromotionSource::Automatic`) instead of the default `code`, and it usually has no code. The `ApplyAutomaticPromotions` step of the [calculation pipeline](/3.x/cart#calculation-pipeline) loads the automatic discounts of the `active()` scope on every calculation. It attaches each one to the cart, as a `CartPromotion` of source `automatic`, when the discount passes its rules and would take at least one cent off the cart. It removes the ones the cart no longer qualifies for, and the ones whose discount was turned off or switched back to a code. The step does nothing while the cart holds a payment session with a provider, so the amount being paid does not change. An automatic discount follows the same rules as a code: dates, usage limits, eligibility, zone, minimum requirement and campaign budget. It also competes with the codes of the cart under the rules of [Priority and Combination](#priority-and-combination). A limit reached at checkout names it "automatic promotion" in the exception message, since it has no code. ## Priority and Combination [#priority-and-combination] Three columns decide how the discounts of a cart stack. `exclusivity_class` (`Shopper\Core\Enum\ExclusivityClass`) puts the discount in the `order`, `product` or `shipping` class, `priority` orders the discounts within a class, and `combinable` lets a discount share its class with another one. On each calculation, `PromotionResolver` sorts the valid promotions of the cart by class (`order`, then `product`, then `shipping`), then by `priority` from highest to lowest, then by the order they were attached to the cart, and applies them in that order: - The first discount applied in a class always applies. - A later discount in the same class stacks only when it and the first discount of the class are both combinable. Otherwise it stays on the cart with an amount of 0. - Discounts of different classes always stack. - Each discount is computed on the line subtotals before any discount, and capped at what the earlier discounts left on each line, so a line never goes below 0. - A discount that takes nothing off, or that its campaign budget cannot absorb, is skipped and does not count as the first of its class. - Once `config('shopper.cart.max_promotions')` discounts have applied (5 by default), the others stay on the cart with an amount of 0. The `shipping` class sorts last. A discount of that class reduces line subtotals like the others; Shopper has no discount on the shipping amount. A cart holds two Classic T-Shirts at $25.00 and a Hoodie at $60.00, so its line subtotals are 5000 and 6000 cents. It carries three discounts: | Discount | Class | Priority | Combinable | Classic T-Shirt line | Hoodie line | |----------|-------|----------|------------|----------------------|-------------| | `SUMMER20`, 20% off the order | `order` | 10 | no | 1000 | 1200 | | `WELCOME10`, 10% off the order | `order` | 0 | no | 0 | 0 | | `TSHIRT10`, 10% off the Classic T-Shirt | `product` | 0 | no | 500 | - | `SUMMER20` comes first: it is in the `order` class with the highest priority. `WELCOME10` is in the same class and neither discount is combinable, so it is suppressed. `TSHIRT10` is in another class and stacks: 10% of 5000, within the 4000 left on the line. The cart total discount is 2700 cents. With `combinable` set on both `SUMMER20` and `WELCOME10`, `WELCOME10` would add 500 and 600 cents. ## Usage Limit Enforcement [#usage-limit-enforcement] Two columns limit how often a discount is used: `usage_limit` caps the uses across all customers, and `usage_limit_per_user` allows one use per customer. `total_use` counts the uses. The cart checks both limits on every calculation, so a customer sees that a code is used up before paying. The checkout checks them again in the transaction that creates the order, because another checkout may have taken the last use in the meantime. ### Global Usage Limit [#global-usage-limit] When the checkout creates the order, it increments `total_use` with a conditional update that only matches while `total_use` is below `usage_limit`. Two checkouts cannot both take the last use: the update of the second one matches no row, `DiscountLimitReachedException::global()` is thrown and the order transaction rolls back. On MySQL and MariaDB, the checkout also locks the discount rows of the cart, in ID order, at the start of the transaction. When the payment provider already collected the payment before the order is created, the checkout honors the discount the customer paid with: it records the use even when the limit was reached in between, so `total_use` can end above `usage_limit`. `total_use` is never decremented: a cancelled or refunded order keeps its use, while the [campaign budget](/3.x/campaigns#budgets) of the discount is given back. ### Per-User Limit [#per-user-limit] When `usage_limit_per_user` is `true`, the cart and the checkout look for an earlier order of the same customer with an `OrderPromotion` row for the discount: by `customer_id` for a signed-in customer, and by the email of the cart for a guest. The cart refuses the code with "Discount already used by this customer.", and the checkout throws `DiscountLimitReachedException::perUser()`. The Store API requires an email before it completes a cart. A checkout you build yourself sets it with `setEmail()` on `CartManager` before it creates the order. ### Helpers [#helpers] `hasReachedLimit()` returns `true` once `total_use` reached `usage_limit`, and always `false` for a discount without a limit: ```php $discount->hasReachedLimit(); $remaining = $discount->usage_limit === null ? null : max(0, $discount->usage_limit - $discount->total_use); ``` `total_use` can pass `usage_limit` when a collected payment is honored, so floor the remaining uses at 0. ### Handling DiscountLimitReachedException [#handling-discountlimitreachedexception] `Shopper\Cart\Actions\CreateOrderFromCartAction` throws an exception when a discount of the cart stopped holding during checkout. The transaction rolls back and the cart keeps its promotions: calculate it again to show the new total, where the discount has an amount of 0. ```php title="app/Http/Controllers/CheckoutController.php" use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Exceptions\DiscountLimitReachedException; use Shopper\Cart\Exceptions\PromotionUnavailableException; use Shopper\Cart\Facades\Cart; try { $order = resolve(CreateOrderFromCartAction::class)->execute(Cart::current() ?? abort(404)); } catch (DiscountLimitReachedException|PromotionUnavailableException $exception) { return back()->with('error', $exception->getMessage()); } ``` | Exception | Thrown when | |-----------|-------------| | `DiscountLimitReachedException::global($code)` | The discount reached its `usage_limit` | | `DiscountLimitReachedException::perUser($code)` | The customer already used a discount limited to one use per customer | | `PromotionUnavailableException` | The discount was deleted, or its terms stopped holding (turned off, expired, out of zone, minimum no longer reached) | | `Shopper\Core\Exceptions\CampaignBudgetExceededException` | The campaign budget cannot absorb the discount, see [Budget Exceeded Exception](/3.x/campaigns#budget-exceeded-exception) | The messages of `DiscountLimitReachedException` read "The discount "SUMMER20" has reached its usage limit and can no longer be applied." and "You have already used the discount "SUMMER20", which is limited to one use per customer.". The [Cart](/3.x/cart#discount-limit-exceptions) page covers the other checks of the checkout. ## Discount Validation [#discount-validation] `DiscountValidator` holds the discount rules. The pipeline runs it on every promotion of the cart, and you can call it yourself, for example to check a code before attaching it: `applyCoupon()` only checks that the code exists. `validate()` runs the checks below in order and stops at the first failure. `validateTerms()` runs the first eleven, which describe the discount and the cart, without the usage limits and the campaign budget. Both return a `Shopper\Cart\Discounts\DiscountValidationResult` with a `valid` boolean and a `failureReason`: | Check | Fails when | Message key | |-------|------------|-------------| | Active | `is_active` is `false` | `not_active` | | Value | `value` is 0 or less | `invalid_value` | | Percentage | A percentage is above 100 | `invalid_percentage` | | Start | `start_at` is in the future | `not_started` | | End | `end_at` is in the past | `expired` | | Campaign currency | The campaign currency differs from the cart currency | `currency_mismatch` | | Eligibility | The rule of the `eligibility` key refuses the cart | Set by the rule | | Zone | The cart is in another zone than `zone_id` | `not_available_in_zone` | | Fixed amount currency | The currency of the zone, or the store default currency, differs from the cart currency | `currency_mismatch` | | Minimum amount | The cart subtotal is below `min_required_value` | `min_amount_not_reached` | | Minimum quantity | The cart quantity is below `min_required_value` | `min_quantity_not_reached` | | Usage limit | `hasReachedLimit()` is `true` | `usage_limit_reached` | | Campaign budget | The campaign reached its budget | `campaign_budget_reached` | | One per customer | The customer already used the discount | `already_used` | The keys live in the `shopper-cart::messages.discount` group. To change a message, override it in `lang/vendor/shopper-cart/en/messages.php`. The validator needs a calculated cart context: ```php use Shopper\Cart\CartManager; use Shopper\Cart\Discounts\DiscountValidator; use Shopper\Cart\Facades\Cart; use Shopper\Core\Models\Discount; $context = resolve(CartManager::class)->calculate(Cart::current() ?? abort(404)); $discount = Discount::query()->where('code', 'SUMMER20')->firstOrFail(); $result = resolve(DiscountValidator::class)->validate($discount, $context); if (! $result->valid) { return back()->withErrors(['code' => $result->failureReason]); } ``` A valid discount can still take nothing off the cart: a product discount on a cart without its products, or a discount suppressed by another one of its class, as described in [Priority and Combination](#priority-and-combination). ## Configuration [#configuration] Discounts are on by default. Their settings are the feature flag, the cap on stacked promotions and the admin components; the model has no configuration key. ### Disabling Discounts [#disabling-discounts] If your store does not use discounts, disable the feature in `config/shopper/features.php`: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'discount' => FeatureState::Disabled, ]; ``` The discount pages are no longer registered and the Promotions item leaves the Sales group of the sidebar. The flag only changes the admin panel: the cart keeps applying the active discounts, so turn them off with `is_active` if the store must stop honoring them. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Maximum Stacked Promotions [#maximum-stacked-promotions] `config('shopper.cart.max_promotions')` caps the number of discounts that apply to one cart, 5 by default. It lives in `config/shopper/cart.php`, described in the [Configuration](/3.x/cart#configuration) section of the Cart page. A suppressed discount does not count against the cap. ### Components [#components] The discounts section of the admin panel is made of two pages and four components. To replace any of them with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish discount ``` The command creates `config/shopper/components/discount.php`: ```php title="config/shopper/components/discount.php" use Shopper\Livewire; return [ 'pages' => [ 'discount-index' => Livewire\Pages\Discount\Index::class, 'discount-edit' => Livewire\Pages\Discount\Edit::class, ], 'components' => [ 'slide-overs.add-promotion' => Livewire\SlideOvers\AddPromotion::class, 'slide-overs.products-picker' => Livewire\SlideOvers\ProductsPicker::class, 'slide-overs.customers-picker' => Livewire\SlideOvers\CustomersPicker::class, 'discounts.stats-panel' => Livewire\Components\Discounts\StatsPanel::class, ], ]; ``` The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below work with the core models directly, from a seeder, a command or the controllers of a storefront. ### Creating Discounts [#creating-discounts] Create a discount with its type, value, rules and dates. `type`, `trigger` and `exclusivity_class` are cast to enums; `apply_to`, `min_required` and `eligibility` are plain strings, so pass the enum `value`. Each example below lists only the imports the earlier ones did not need. #### Percentage Discount for All Orders [#percentage-discount-for-all-orders] A `SUMMER20` code takes 20% off every order for a month: ```php use Shopper\Core\Enum\DiscountApplyTo; use Shopper\Core\Enum\DiscountEligibility; use Shopper\Core\Enum\DiscountRequirement; use Shopper\Core\Enum\DiscountType; use Shopper\Core\Models\Discount; $discount = Discount::query()->create([ 'code' => 'SUMMER20', 'type' => DiscountType::Percentage, 'value' => 20, 'apply_to' => DiscountApplyTo::Order->value, 'min_required' => DiscountRequirement::None->value, 'eligibility' => DiscountEligibility::Everyone->value, 'is_active' => true, 'start_at' => now(), 'end_at' => now()->addMonth(), ]); ``` #### Fixed Amount Discount with Minimum Order [#fixed-amount-discount-with-minimum-order] A `SAVE10` code takes $10.00 off orders of $50.00 or more, for the first 500 orders. Both amounts are in [cents](/3.x/money), in the store default currency since the discount has no zone: ```php $discount = Discount::query()->create([ 'code' => 'SAVE10', 'type' => DiscountType::FixedAmount, 'value' => 1000, 'apply_to' => DiscountApplyTo::Order->value, 'min_required' => DiscountRequirement::Price->value, 'min_required_value' => '5000', 'eligibility' => DiscountEligibility::Everyone->value, 'usage_limit' => 500, 'is_active' => true, 'start_at' => now(), ]); ``` #### Product-Specific Discount [#product-specific-discount] A `TSHIRT15` code takes 15% off the Classic T-Shirt and its variants. Resolve the product through its contract so a swapped model is honored, and link it with its morph alias: ```php use Shopper\Core\Enum\DiscountCondition; use Shopper\Core\Enum\ExclusivityClass; use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query()->where('slug', 'classic-t-shirt')->firstOrFail(); $discount = Discount::query()->create([ 'code' => 'TSHIRT15', 'type' => DiscountType::Percentage, 'value' => 15, 'apply_to' => DiscountApplyTo::Products->value, 'min_required' => DiscountRequirement::None->value, 'eligibility' => DiscountEligibility::Everyone->value, 'exclusivity_class' => ExclusivityClass::Product, 'is_active' => true, 'start_at' => now(), ]); $discount->items()->create([ 'condition' => DiscountCondition::ApplyTo, 'discountable_type' => $product->getMorphClass(), 'discountable_id' => $product->id, ]); ``` The `product` class lets the discount stack with an order discount such as `SUMMER20`. #### VIP Customer Discount [#vip-customer-discount] A `VIP25` code takes 25% off, once per customer, for a list of customers. Set the `eligibility` column, then link the customers: ```php use App\Models\User; use Shopper\Cart\Discounts\SyncDiscountEligibilityAction; $discount = Discount::query()->create([ 'code' => 'VIP25', 'type' => DiscountType::Percentage, 'value' => 25, 'apply_to' => DiscountApplyTo::Order->value, 'min_required' => DiscountRequirement::None->value, 'eligibility' => DiscountEligibility::Customers->value, 'usage_limit_per_user' => true, 'is_active' => true, 'start_at' => now(), ]); $vipCustomerIds = User::query() ->whereIn('email', ['amelia@example.com', 'noah@example.com']) ->pluck('id') ->all(); resolve(SyncDiscountEligibilityAction::class)->execute( $discount, DiscountEligibility::Customers->value, $vipCustomerIds, ); ``` Calling the action again with another list replaces the eligible customers. #### Automatic Discount [#automatic-discount] An automatic discount takes 10% off every order of $100.00 or more, without a code: ```php use Shopper\Core\Enum\PromotionSource; $discount = Discount::query()->create([ 'trigger' => PromotionSource::Automatic, 'type' => DiscountType::Percentage, 'value' => 10, 'apply_to' => DiscountApplyTo::Order->value, 'min_required' => DiscountRequirement::Price->value, 'min_required_value' => '10000', 'eligibility' => DiscountEligibility::Everyone->value, 'is_active' => true, 'start_at' => now(), ]); ``` The next calculation of every qualifying cart attaches it, as described in [Automatic Discounts](#automatic-discounts). ### Retrieving Discounts [#retrieving-discounts] The `active()` scope keeps the discounts that are active, started, not expired and below their usage limit: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Enum\PromotionSource; use Shopper\Core\Models\Discount; $running = Discount::query()->active()->get(); $summerSale = Discount::query()->where('code', 'SUMMER20')->first(); $automatic = Discount::query() ->active() ->where('trigger', PromotionSource::Automatic->value) ->get(); $forZone = Discount::query() ->active() ->where(fn (Builder $query) => $query->whereNull('zone_id')->orWhere('zone_id', $zone->id)) ->get(); $summerSale->status->getLabel(); ``` The scope does not check eligibility, the zone, the minimum requirement or the campaign budget. To know whether a discount applies to a cart, use the validator, as shown in [Discount Validation](#discount-validation). ### Updating Discounts [#updating-discounts] Dates, limits, requirements, eligibility and the stacking columns can change at any time, and the next calculation of each cart uses the new values: ```php $summerSale->update([ 'end_at' => now()->addWeeks(2), 'usage_limit' => 1000, ]); ``` The code, type and value are frozen once the discount has been used, and so is the zone of a used fixed-amount discount, as described in [Value Handling](#value-handling). Deleting a discount deletes its `DiscountDetail` rows. Orders, order promotions and cart promotions keep their rows with a null `discount_id`, and each `OrderPromotion` keeps the code, type, value and amount of the discount. ### Storefront Example [#storefront-example] A Blade or Livewire storefront attaches a code with `applyCoupon()` on `CartManager`, described in [Applying Coupons](/3.x/cart#applying-coupons). `applyCoupon()` attaches any existing code, and the calculation then gives it an amount of 0 when it does not apply. To tell the customer right away, validate the discount first: ```php title="app/Http/Controllers/CouponController.php" validate(['code' => ['required', 'string']]); $cart = Cart::current() ?? abort(404); $discount = Discount::query()->where('code', $request->input('code'))->first(); if ($discount === null || ! $this->validator->validate($discount, $this->manager->calculate($cart))->valid) { return back()->withErrors(['code' => __('This code does not apply to your cart.')]); } $this->manager->applyCoupon($cart, $discount->code); return back()->with('status', __('Discount applied.')); } public function destroy(): RedirectResponse { $this->manager->removeCoupon(Cart::current() ?? abort(404)); return back(); } } ``` `removeCoupon()` without a code removes every code of the cart; automatic discounts stay while the cart qualifies. ### Use Cases [#use-cases] The columns combine into the usual promotions: | Scenario | Type | Apply To | Eligibility | Requirement | Trigger | |----------|------|----------|-------------|-------------|---------| | Site-wide sale | Percentage | Order | Everyone | None | Code | | $10.00 off orders over $50.00 | Fixed amount | Order | Everyone | Price | Code | | Buy 3 or more, get 10% off | Percentage | Order | Everyone | Quantity | Code | | 10% off orders over $100.00, no code | Percentage | Order | Everyone | Price | Automatic | | VIP member exclusive | Percentage | Order | Customers | None | Code | | Product clearance | Percentage | Products | Everyone | None | Automatic | | First order discount | Fixed amount | Order | A [custom rule](#custom-eligibility-rules) | None | Code | ## Events [#events] Shopper dispatches no discount event: nothing fires when a discount is created, used or reaches its limit, as noted in [Cart and Discount Events](/3.x/events#cart-and-discount-events). The cart dispatches `CouponApplied` and `CouponRemoved` from `Shopper\Cart\Events` when a code is added to or removed from a cart; that section lists their payloads. To react to a use, listen to the Eloquent `created` event of `OrderPromotion`. The checkout increments `total_use` with a query, so the `updated` event of `Discount` does not fire when a discount is used: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\OrderPromotion; public function boot(): void { OrderPromotion::created(function (OrderPromotion $promotion): void { Cache::forget("discounts.{$promotion->discount_id}.remaining"); }); } ``` The promotion is created inside the checkout transaction. The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks four permissions of the `discounts` resource, in the Sales group: | Permission | Allows | |------------|--------| | `discounts.browse` | Opening the discounts page and seeing the Promotions sidebar item | | `discounts.create` | Creating a discount with the wizard, and duplicating one | | `discounts.edit` | Opening the edit page and saving changes | | `discounts.delete` | Deleting a discount, from the list (one at a time or in bulk) or from its edit page | `discounts.read` is seeded with the others, but the admin panel never checks it. The 2.x names, such as `browse_discounts`, are gone: a store upgraded from 2.x follows [Upgrading from 2.x](/3.x/acl#upgrading-from-2x). ## In the Admin [#in-the-admin] Merchants manage discounts under Sales, Promotions. The list shows each discount with its code, method (code or automatic), type, amount, what it applies to, eligibility, status, dates, usage limit, redemptions, zone and campaign, and filters by active state, method, campaign, application, eligibility, zone and start date. A discount can be edited, duplicated (the copy is inactive, gets a new code and starts at 0 uses) or deleted. New discounts go through a three-step wizard: Type, Conditions and Campaign. The edit page groups the fields in General, Configuration, Targeting, Combinations and Advanced, locks the zone of a used fixed-amount discount and the campaign of a used discount, and shows the uses, remaining uses, gross revenue, discount cost, orders and average order value of the paid orders that used it. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API applies and removes codes on a cart and reports the discounts of the cart. It has no endpoint that lists discounts, so a storefront cannot show the available codes from it: | Request | Discount effect | |---------|-----------------| | `POST /store/carts/{cartId}/promotion` | Attaches the discount of the `code` in the body when it is active, passes its rules and takes something off the cart. A code suppressed by a discount of higher priority is accepted. Any refusal is a 422 error with code `promotion_not_applicable` on the `/data/attributes/code` pointer, which does not say why | | `DELETE /store/carts/{cartId}/promotion` | Removes the discount of the `code` sent, or every code when none is sent. Automatic discounts stay | | `GET /store/carts/{cartId}` | `promotions` lists each discount of the cart with its `code`, `source` (`code` or `automatic`), `amount` and `status` (`applied`, or `suppressed` with an amount of 0). `discount_total` holds their sum, and each line has its own `discount_total` | | `POST /store/carts/{cartId}/complete` | A discount that stopped holding answers a 422 error on the `/data/attributes/promotion` pointer: `promotion_limit_reached` for a usage limit, `promotion_not_applicable` for its terms, `promotion_budget_reached` for its campaign budget. The cart is priced again without the discount: show the new total and let the customer confirm | Both promotion endpoints use the checkout rate limit. Amounts are in cents. The `store` prefix is set by `SHOPPER_API_PREFIX`. The Store API [Cart](/3.x/store-api/cart#promotion-codes) guide covers promotion codes, and the [Errors](/3.x/store-api/errors#error-codes) page lists every error code. # Events (/3.x/events) Shopper dispatches Laravel events when an order is placed, paid, shipped or cancelled, when a payment fails, when a product changes and when a customer signs up. Your application listens to them to send emails, sync an ERP or a warehouse, or feed analytics, without changing Shopper's code. Each package keeps its events in its own namespace: | Namespace | Package | Events | |-----------|---------|--------| | `Shopper\Core\Events\Orders` | `shopper/core` | Orders, order items and shipments | | `Shopper\Core\Events\Products` | `shopper/core` | Products and product imports | | `Shopper\Core\Events\Customers` | `shopper/core` | Customer sign-ups | | `Shopper\Core\Events\Payments` | `shopper/core` | Payments received without an order | | `Shopper\Payment\Events` | `shopper/payment` | Failed payments | | `Shopper\Cart\Events` | `shopper/cart` | Checkout, coupons and cart prices | | `Shopper\Events` | `shopper/framework` | Admin panel | ## Listening to Events [#listening-to-events] Laravel 12 and 13 discover the listeners stored in `app/Listeners`: a class whose `handle` method type-hints a Shopper event is registered for that event, with no other step. ```php title="app/Listeners/RecordSaleInAccounting.php" namespace App\Listeners; use App\Services\Accounting; use Shopper\Core\Events\Orders\OrderPaid; class RecordSaleInAccounting { public function __construct(private Accounting $accounting) {} public function handle(OrderPaid $event): void { $this->accounting->recordSale($event->order); } } ``` Every event exposes its payload as public properties, such as `$event->order` above. Order, product and cart payloads are typed with the model contracts, so a listener receives your own model when you replace one: orders and products in `config/shopper/models.php`, as the [Models](/3.x/models) page explains, and carts in the `models` key of `config/shopper/cart.php`. A listener stored in another directory is registered in the `boot` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Warehouse\CancelPickingList; use Illuminate\Support\Facades\Event; use Shopper\Core\Events\Orders\OrderCancelled; public function boot(): void { Event::listen(OrderCancelled::class, CancelPickingList::class); } ``` Register each listener one way only: a listener in `app/Listeners` that is also passed to `Event::listen()` runs twice. To see every listener attached to a Shopper event, Shopper's own included, run: ```bash php artisan event:list --event=Shopper ``` ### Dispatched After Commit [#dispatched-after-commit] Most Shopper events implement Laravel's `ShouldDispatchAfterCommit` contract. When such an event is dispatched inside a database transaction, Laravel holds it until the transaction commits, and drops it if the transaction rolls back. A listener therefore never sees a half-written order: `OrderCreated` is dispatched when the order row is inserted, yet the checkout writes the items, the addresses and the promotions in the same transaction, and the listener finds all of them. Outside a transaction, the event is dispatched at once. The [reference table](#all-events-reference) shows which events wait for the commit. Waiting for the commit does not put a listener on the queue. Listeners still run during the request that dispatched the event, unless you queue them. ### Queueing Listeners [#queueing-listeners] A listener that calls an external service or sends an email should not slow down the checkout or the admin panel. Implement `ShouldQueue` and Laravel pushes the listener to the queue instead of running it during the request: ```php title="app/Listeners/RecordSaleInAccounting.php" namespace App\Listeners; use App\Services\Accounting; use Illuminate\Contracts\Queue\ShouldQueue; use Shopper\Core\Events\Orders\OrderPaid; class RecordSaleInAccounting implements ShouldQueue { public $queue = 'accounting'; public function __construct(private Accounting $accounting) {} public function handle(OrderPaid $event): void { $this->accounting->recordSale($event->order); } } ``` The `$queue` property sends the job to a named queue. Without it, the job goes to the default queue. The queue worker must listen to every queue your listeners use, as described in [Installation](/3.x/installation#queue-worker). Most Shopper events use Laravel's `SerializesModels` trait: the queued job stores the IDs of the models and loads them again when it runs. The listener reads the order as it is when the job runs, which can differ from the order at dispatch time. ## Order Events [#order-events] Order events follow an order from checkout to completion, cancellation or archiving. They live in the `Shopper\Core\Events\Orders` namespace. ### Available Events [#available-events] The order events carry the order as `public Order $order`, typed with the `Shopper\Core\Models\Contracts\Order` contract. `OrderItemCreated` carries `public OrderItem $orderItem`, an instance of `Shopper\Core\Models\OrderItem`. | Event | Payload | Dispatched when | |-------|---------|-----------------| | `OrderCreated` | `Order $order` | An order row is inserted, at checkout or from your own code | | `OrderItemCreated` | `OrderItem $orderItem` | An order item row is inserted | | `OrderPaid` | `Order $order` | The payment status becomes Paid, see [Payment Events](#payment-events) | | `OrderShipped` | `Order $order` | The shipping status of the order becomes Shipped, see [Shipment Events](#shipment-events) | | `OrderCompleted` | `Order $order` | The order moves to Completed | | `OrderCancelled` | `Order $order` | The order moves to Cancelled | | `OrderArchived` | `Order $order` | The order is archived from the admin panel | | `OrderNoteAdded` | `Order $order` | A private note is saved on the order in the admin panel | | `OrderDeleted` | `Order $order` | An order is deleted, soft or forced | `OrderCreated`, `OrderItemCreated` and `OrderDeleted` come from model observers, so they fire wherever the row is created or deleted. An order inserted by your own code outside a transaction dispatches `OrderCreated` at once, before you add its items. The admin panel never deletes an order: `OrderDeleted` only fires when your code deletes one. ### Order Lifecycle [#order-lifecycle] An order carries three statuses: `status` for the order itself, `payment_status` for its payment and `shipping_status` for its packages. The order status follows the `Shopper\Core\Enum\OrderStatus` state machine: | Status | Can move to | |--------|-------------| | New | Processing, Completed, Cancelled, Archived | | Processing | Completed, Cancelled, Archived | | Completed | Cancelled, Archived | | Cancelled | Archived | | Archived | None | `$order->transitionTo()` refuses any other move with a `Shopper\Core\Exceptions\InvalidOrderStatusTransitionException`. It dispatches no event: the code that moves the order dispatches the matching event after the transition. Shopper moves orders in these places: | Move | Triggered by | Event | |------|--------------|-------| | Created as New | The checkout turns a cart into an order | `OrderCreated` | | New to Processing | Start processing or Mark as paid in the admin panel, or the carrier picking up the first package | None | | Processing to Completed | Mark complete in the admin panel, offered once the order is paid, or automatically once the order is paid and every item is delivered | `OrderCompleted` | | To Cancelled | Cancel Order in the admin panel, a cancellation reported by the payment provider on an unpaid order, or the hourly `shopper:orders:reclaim` command for orders left unpaid | `OrderCancelled` | | To Archived | Archive in the admin panel, offered for orders neither paid nor completed | `OrderArchived` | The automatic completion runs in two places: when the last package of a paid order is delivered, and when an order whose items are all delivered gets paid, through the `OrderPaid` listener Shopper registers. An item whose package came back is never counted as delivered, so an order with a returned package is not completed automatically. The delay before `shopper:orders:reclaim` cancels an unpaid order is set by `reclaim_pending_after_hours` in `config/shopper/orders.php`, described on the [Configuration](/3.x/configuration) page. When your own code moves an order, dispatch the matching event after the transition so that your listeners and the webhooks see the change: ```php use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Events\Orders\OrderCompleted; $order->transitionTo(OrderStatus::Completed); OrderCompleted::dispatch($order); ``` ## Payment Events [#payment-events] The payment status follows its own state machine, `Shopper\Core\Enum\PaymentStatus`: Pending moves to Authorized, Paid or Voided; Authorized to Paid or Voided; Paid to Partially refunded or Refunded; Partially refunded to Partially refunded or Refunded. Only the move to Paid dispatches an event. Amounts in payment events are in cents. | Event | Namespace | Payload | Dispatched when | |-------|-----------|---------|-----------------| | `OrderPaid` | `Shopper\Core\Events\Orders` | `Order $order` | The payment status becomes Paid | | `PaymentFailed` | `Shopper\Payment\Events` | `Order $order`, `TransactionType $type`, `?string $reason` | The provider declines an authorization, a capture or a refund | | `PaymentOrphaned` | `Shopper\Core\Events\Payments` | `string $driver`, `string $reference`, `?int $amount`, `?string $cartId` | A payment authorized or captured by the provider still has no order | | `OrphanedPaymentRefunded` | `Shopper\Core\Events\Payments` | `string $driver`, `string $reference`, `?int $amount` | An orphaned payment is refunded | `OrderPaid` is dispatched by `$order->transitionPaymentTo(PaymentStatus::Paid)`, whatever moved the payment: Mark as paid in the admin panel for offline payments such as cash on delivery, Capture payment in the admin panel for an authorized payment, or the capture event of the payment provider, applied at checkout, from the provider's webhook or by the `shopper:payments:reconcile` command. `PaymentFailed` carries `$type`, a `Shopper\Payment\Enum\TransactionType` case (`Authorize`, `Capture` or `Refund`), and `$reason`, the message returned by the provider. A payment failure reported by the provider's webhook only dispatches the event while the payment is still pending: the order keeps its reserved stock so that the customer can try again. A refund the provider reports as failed dispatches it with the `Refund` type whatever the payment status, as described in [Pending Refunds](/3.x/payments#pending-refunds). ### Orphaned Payments [#orphaned-payments] A customer can pay and lose the connection before the checkout creates the order. Every 15 minutes, the scheduled `shopper:payments:reconcile` command looks for provider authorizations and captures that still have no order after `reconciliation.orphan_after_minutes` in `config/shopper/payment.php` (30 by default, set with `PAYMENT_ORPHAN_AFTER_MINUTES`), and dispatches `PaymentOrphaned` for each one the provider has not since reported as refunded or canceled. A refund the provider has reported as failed does not count. Listeners run during the command and answer through three methods of the event: | Method | Meaning | |--------|---------| | `recognize()` | The payment belongs to one of the store's carts | | `resolve()` | The listener created the order for this payment | | `defer()` | The payment is checked again on the next run | Shopper's cart package recognizes a payment whose reference matches a cart. With the Store API installed, a second listener completes that cart and calls `resolve()`, or `defer()` when the cart is locked or the provider does not answer. A payment recognized but not resolved is reported to your exception handler, then refunded when `config('shopper.payment.reconciliation.orphans')` is `refund` (`PAYMENT_ORPHANS`, `alert` by default). A successful refund dispatches `OrphanedPaymentRefunded`, with `$amount` set to `null`. The provider's refund webhook also dispatches it for a payment without an order, with the refunded amount when the provider sends one. A refund the provider reports as failed for a payment without an order is reported to your exception handler. A storefront that completes its checkout without the Store API can listen to `PaymentOrphaned` and complete the cart the same way. ## Shipment Events [#shipment-events] An order ships in one or more packages, each an `OrderShipping` model with its own status. A package is created from the order page of the admin panel. Its status then changes when an administrator records a tracking event or marks it delivered, or when the carrier reports it, through its webhook or the `shopper:shipments:sync-tracking` command. The [Fulfillment](/3.x/fulfillment) page describes the shipment statuses. ### Available Events [#available-events-1] Shipment events live in `Shopper\Core\Events\Orders` with the order events. They carry the order and the package, an instance of `Shopper\Core\Models\OrderShipping`: | Event | Payload | Dispatched when | |-------|---------|-----------------| | `OrderShipmentCreated` | `Order $order`, `OrderShipping $shipment` | A package is created, with the status Pending | | `OrderShipmentDelivered` | `Order $order`, `OrderShipping $shipment` | The package reaches Delivered | | `OrderShipmentDeliveryFailed` | `Order $order`, `OrderShipping $shipment` | The package reaches Delivery failed | | `OrderShipmentReturned` | `Order $order`, `OrderShipping $shipment` | The package reaches Returned | | `OrderShipmentEventRecorded` | `Order $order`, `OrderShipping $shipment`, `OrderShippingEvent $event`, `bool $statusChanged` | A tracking event is recorded on the package | | `OrderShipped` | `Order $order` | The shipping status of the order becomes Shipped | `OrderShipmentEventRecorded` fires each time a tracking event is recorded on an existing package, after the event of the status it reached. The Pending event written when the package is created only dispatches `OrderShipmentCreated`. `$event` is the `Shopper\Core\Models\OrderShippingEvent` row. `$statusChanged` is `false` when a carrier scan is logged without changing the package status, such as a scan older than the current status. A carrier event already recorded under the same external ID is ignored and dispatches nothing. ```php title="app/Listeners/PushTrackingToCustomerApp.php" namespace App\Listeners; use App\Services\PushNotifications; use Shopper\Core\Events\Orders\OrderShipmentEventRecorded; class PushTrackingToCustomerApp { public function __construct(private PushNotifications $push) {} public function handle(OrderShipmentEventRecorded $event): void { if (! $event->statusChanged) { return; } $this->push->send($event->order->customer, $event->shipment->tracking_number, $event->event->status); } } ``` ### Shipment vs Order Events [#shipment-vs-order-events] Shipment events fire per package, order events per order. A status recorded on a package also updates its items and the order: - The first time a package reaches Picked up or a later status other than Returned, its items become Shipped, a New order moves to Processing, and the shipping status of the order is computed again. `OrderShipped` fires when every item of the order is shipped and none is delivered or returned yet. - When a package is delivered, its items become Delivered, and the order is completed if it is paid, in Processing, and every item is delivered. - When a package is returned, its items become Cancelled and the shipping status of the order is computed again: Returned when every item came back, Partially returned when the other items are all shipped or delivered. - Delivery failed changes nothing else. For a paid order of three items sent in two packages, the events arrive in this order: | Step | Events, in dispatch order | |------|---------------------------| | Package A is created with two items | `OrderShipmentCreated` | | The carrier picks up package A | `OrderShipmentEventRecorded` | | Package B is created with the last item | `OrderShipmentCreated` | | The carrier picks up package B while A is in transit | `OrderShipped`, `OrderShipmentEventRecorded` | | The first delivery attempt of package A fails | `OrderShipmentDeliveryFailed`, `OrderShipmentEventRecorded` | | Package A is delivered | `OrderShipmentDelivered`, `OrderShipmentEventRecorded` | | Package B is delivered | `OrderCompleted`, `OrderShipmentDelivered`, `OrderShipmentEventRecorded` | A package that comes back to the store dispatches `OrderShipmentReturned`, then `OrderShipmentEventRecorded`. `OrderShipped` never fires when a package is delivered before the last package is picked up: the shipping status of the order goes from Partially delivered to Delivered without passing through Shipped. To follow every package, listen to the shipment events. ## Product Events [#product-events] Product events live in `Shopper\Core\Events\Products`. The product events carry `public Product $product`, typed with the `Shopper\Core\Models\Contracts\Product` contract. The admin panel and the CSV import dispatch them, no model observer does: `Product::create()` in your own code or in a seeder dispatches nothing. | Event | Payload | Dispatched when | |-------|---------|-----------------| | `ProductCreated` | `Product $product` | A product is created in the admin panel, or a CSV import creates a new product | | `ProductUpdated` | `Product $product` | The main product form is saved in the admin panel | | `ProductDeleted` | `Product $product` | A product is deleted from the admin panel, just before the deletion | | `ProductImportCompleted` | `ProductImport $import` | A CSV import finishes | `ProductUpdated` only fires from the main form of the product page: name, description, visibility, publication date, channels, brand, categories, collections and tags. Saving the pricing, inventory, media, files, shipping, SEO, attributes or variants of a product, or updating an existing product through a CSV import, dispatches no event. Products are soft deleted, so a queued listener of `ProductDeleted` still loads the product it receives. `ProductImportCompleted` carries the `Shopper\Core\Models\ProductImport` record. Its `status` is `Completed` or `CompletedWithErrors` (`Shopper\Core\Enum\ImportStatus`), next to the `total_products`, `imported_count`, `failed_count` and `errors` columns. An import that fails before its rows are read ends with the status `Failed` and dispatches no event. The [Import](/3.x/import) page covers the CSV format. ## Customer Events [#customer-events] `Shopper\Core\Events\Customers\CustomerRegistered` carries `public Authenticatable $customer`, an instance of your user model. It fires when a customer is created in the admin panel, or signs up through `POST /store/auth/register`, the [registration endpoint](/3.x/store-api/authentication#registering-a-customer) of the Store API. A sign-up handled by your own code dispatches no Shopper event. The Store API also dispatches two Laravel events: `Illuminate\Auth\Events\Lockout` when a login is refused after too many failed attempts, and `Illuminate\Auth\Events\PasswordReset` when a customer resets their password. ## Cart and Discount Events [#cart-and-discount-events] Cart events live in `Shopper\Cart\Events` and carry the cart as `public Cart $cart`, typed with the `Shopper\Cart\Models\Contracts\Cart` contract. Shopper dispatches no event when a discount or a campaign is created, changed or used up: the coupon events come from the cart. | Event | Payload | Dispatched when | |-------|---------|-----------------| | `CartCompleted` | `Cart $cart`, `Order $order` | The checkout turns the cart into an order | | `CouponApplied` | `Cart $cart`, `string $code` | A coupon code is applied to the cart | | `CouponRemoved` | `Cart $cart` | Coupon codes are removed from the cart | | `CartLinesRepriced` | `Cart $cart`, `Collection $changes` | The unit price of one or more lines changes | `CartCompleted` is dispatched once the order, its items and the cart are committed, after `OrderCreated` and `OrderItemCreated`. `CouponRemoved` does not say which code left the cart. It fires when the customer removes a code through `DELETE /store/carts/{cartId}/promotion`, which removes every code when the request names none, and when Shopper drops a code that no longer applies after the currency or the zone of the cart changes, or when a signed-in customer takes over a guest cart. It also fires when the code to remove was not on the cart. `CartLinesRepriced` fires when Shopper prices a cart again and at least one unit price changed: when the zone or the channel of the cart changes, when a signed-in customer takes over or merges a guest cart, before a payment session is created, and when the checkout is refused because a unit price went up. Each item of `$changes` is an array with `line`, the `Shopper\Cart\Models\CartLine`, and `from` and `to`, the unit price before and after, in cents. ## Admin Panel Events [#admin-panel-events] The `shopper/framework` package dispatches three events from the admin panel: | Event | Payload | Dispatched when | |-------|---------|-----------------| | `Shopper\Events\LoadShopper` | None | On every request to the admin panel, Livewire requests included | | `Shopper\Events\TwoFactor\TwoFactorAuthenticationEnabled` | `$user` | An admin user turns on two-factor authentication from their profile | | `Shopper\Events\TwoFactor\TwoFactorAuthenticationDisabled` | `$user` | Never dispatched | `Shopper::serving()` attaches a closure to `LoadShopper`, to run code only when the admin panel is serving a request, and `Shopper::isServing()` tells whether the current request belongs to the admin panel. Both come from the `Shopper\Facades\Shopper` facade. `TwoFactorAuthenticationDisabled` exists, but Shopper does not dispatch it when a user turns two-factor authentication off, so a listener on it never runs. The [Two-Factor Authentication](/3.x/two-factor) page covers the feature. The sidebar of the admin panel is built through its own `Shopper\Sidebar\SidebarBuilder` event. The [Navigation](/3.x/extending/navigation) page shows how to add menu groups and items with it. ## Listeners Shopper Registers [#listeners-shopper-registers] Shopper listens to some of its own events. Check this list before writing a listener, so that yours does not repeat their work: | Event | Listener | What it does | Runs | |-------|----------|--------------|------| | `OrderCreated` | `Shopper\Listeners\EnsureCustomerRole` | Gives the order's customer the role set in `config('shopper.admin.roles.user')` | During the request | | `OrderPaid` | `Shopper\Core\Listeners\Orders\CompleteFulfilledOrderListener` | Completes the order when every item is already delivered | During the request | | `OrderCancelled` | `Shopper\Core\Listeners\Orders\RestoreOrderStockListener` | Puts the stock reserved by the order back on sale | Default queue | | `OrderCancelled` | `Shopper\Core\Listeners\Orders\ReleaseCampaignBudgetListener` | Gives the discount budget spent by the order back to its campaign | Default queue | | `PaymentOrphaned` | `Shopper\Cart\Listeners\RecognizeOrphanedPayment` | Recognizes a payment that matches a cart | During the command | | `PaymentOrphaned` | `Shopper\Api\Listeners\CompleteOrphanedCart` | Completes the cart the payment belongs to, with the Store API installed | During the command | | `OrphanedPaymentRefunded` | `Shopper\Cart\Listeners\ForgetRefundedPaymentSession` | Clears the refunded payment session from its cart | During the request or the command | When `notifications.database.enabled` is `true` in `config/shopper/admin.php` (`false` by default), the admin panel also notifies its administrators under the bell of the top bar on `OrderCreated`, `OrderPaid`, `PaymentFailed` and `ProductImportCompleted`. These four listeners run on a queue named `notifications`, so the queue worker must listen to it. The [Notifications](/3.x/notifications) page describes them. ## Example: Order Notification System [#example-order-notification-system] A store emails the customer when the order is placed, then again when each package arrives. Two queued listeners in `app/Listeners` cover it, each with a mailable created by `php artisan make:mail`: ```php title="app/Listeners/SendOrderConfirmation.php" namespace App\Listeners; use App\Mail\OrderConfirmation; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Mail; use Shopper\Core\Events\Orders\OrderCreated; class SendOrderConfirmation implements ShouldQueue { public function handle(OrderCreated $event): void { Mail::to($event->order->email)->send(new OrderConfirmation($event->order)); } } ``` The Store API checkout always stores the customer's email on the order, for guests and signed-in customers alike. `OrderCreated` fires as soon as the order exists, before a card payment is captured: to confirm paid orders only, listen to `OrderPaid` instead. ```php title="app/Listeners/SendDeliveryConfirmation.php" namespace App\Listeners; use App\Mail\PackageDelivered; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Mail; use Shopper\Core\Events\Orders\OrderShipmentDelivered; class SendDeliveryConfirmation implements ShouldQueue { public function handle(OrderShipmentDelivered $event): void { $event->shipment->load('items'); Mail::to($event->order->email)->send(new PackageDelivered($event->order, $event->shipment)); } } ``` `OrderShipmentDelivered` sends one email per package, with the items it carried. `OrderCompleted` fires once per order and suits a single thank-you email, sent when the last package is delivered on a paid order. ## Webhooks [#webhooks] Fourteen of these events can also reach external systems as signed HTTP requests. A webhook subscription picks events by their public name, given in the Webhook column of the [reference table](#all-events-reference), such as `order.paid` or `shipment.delivered`. The other events are never sent as webhooks. The map from event class to name lives in the `events` key of `config/shopper/webhooks.php`, and the `Shopper\Core\Webhooks\Facades\Webhooks` facade registers your own events with `Webhooks::register()`. The [Webhooks](/3.x/webhooks) page covers subscriptions, payloads, signatures and retries. ## All Events Reference [#all-events-reference] The After commit column marks the events that implement `ShouldDispatchAfterCommit`. | Event | Namespace | After commit | Webhook | |-------|-----------|--------------|---------| | `OrderCreated` | `Shopper\Core\Events\Orders` | Yes | `order.created` | | `OrderItemCreated` | `Shopper\Core\Events\Orders` | Yes | None | | `OrderPaid` | `Shopper\Core\Events\Orders` | Yes | `order.paid` | | `OrderShipped` | `Shopper\Core\Events\Orders` | Yes | `order.shipped` | | `OrderCompleted` | `Shopper\Core\Events\Orders` | Yes | `order.completed` | | `OrderCancelled` | `Shopper\Core\Events\Orders` | Yes | `order.cancelled` | | `OrderArchived` | `Shopper\Core\Events\Orders` | Yes | None | | `OrderNoteAdded` | `Shopper\Core\Events\Orders` | Yes | None | | `OrderDeleted` | `Shopper\Core\Events\Orders` | Yes | None | | `OrderShipmentCreated` | `Shopper\Core\Events\Orders` | Yes | `shipment.created` | | `OrderShipmentDelivered` | `Shopper\Core\Events\Orders` | Yes | `shipment.delivered` | | `OrderShipmentDeliveryFailed` | `Shopper\Core\Events\Orders` | Yes | `shipment.delivery_failed` | | `OrderShipmentReturned` | `Shopper\Core\Events\Orders` | Yes | `shipment.returned` | | `OrderShipmentEventRecorded` | `Shopper\Core\Events\Orders` | Yes | None | | `PaymentFailed` | `Shopper\Payment\Events` | Yes | None | | `PaymentOrphaned` | `Shopper\Core\Events\Payments` | No | None | | `OrphanedPaymentRefunded` | `Shopper\Core\Events\Payments` | No | None | | `ProductCreated` | `Shopper\Core\Events\Products` | Yes | `product.created` | | `ProductUpdated` | `Shopper\Core\Events\Products` | Yes | `product.updated` | | `ProductDeleted` | `Shopper\Core\Events\Products` | Yes | `product.deleted` | | `ProductImportCompleted` | `Shopper\Core\Events\Products` | No | None | | `CustomerRegistered` | `Shopper\Core\Events\Customers` | Yes | `customer.registered` | | `CartCompleted` | `Shopper\Cart\Events` | Yes | `cart.completed` | | `CouponApplied` | `Shopper\Cart\Events` | No | None | | `CouponRemoved` | `Shopper\Cart\Events` | No | None | | `CartLinesRepriced` | `Shopper\Cart\Events` | No | None | | `LoadShopper` | `Shopper\Events` | No | None | | `TwoFactorAuthenticationEnabled` | `Shopper\Events\TwoFactor` | No | None | | `TwoFactorAuthenticationDisabled` | `Shopper\Events\TwoFactor` | No | None | # Fulfillment (/3.x/fulfillment) Shopper fulfills an order through shipments. A shipment is one physical package sent to the customer: an `OrderShipping` row with its own carrier, tracking number, status and set of order items. An order ships in one package or in several, and each package moves through its own statuses until it is delivered or returned. Three statuses work together. Each package has a shipment status (`ShipmentStatus`) and a timeline of tracking events (`OrderShippingEvent`). Each order item has a fulfillment status (`FulfillmentStatus`). The order has a shipping status (`ShippingStatus`), computed from its items. Each time a package is picked up, delivered or returned, Shopper updates the items of the package and the shipping status of the order, whether the event comes from the admin panel, from your code or from the carrier. Carriers, shipping rates and carrier drivers are described on the [Carriers](/3.x/carriers) page. The order itself, its statuses and its items are on the [Orders](/3.x/orders) page. ## Models [#models] A shipment is a `Shopper\Core\Models\OrderShipping`. It implements the `Shopper\Core\Models\Contracts\OrderShipping` contract, which declares the `order` and `carrier` relationships. Each entry of its timeline is a `Shopper\Core\Models\OrderShippingEvent`. Neither model has a key in `config/shopper/models.php`, so you cannot swap them: add a relationship to them with `resolveRelationUsing()`, as shown in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). Two traits change what you can do with a shipment. `HasFulfillmentTransitions` holds the allowed status changes and the methods described in [Shipment Transitions](#shipment-transitions). `HasPublicId` fills `public_id` with a ULID when a shipment is created, and the Store API identifies a shipment by it, as described in [Public IDs](/3.x/models#public-ids). Tracking events carry a `public_id` as well. `OrderShipping` casts `status` to `ShipmentStatus`, `shipped_at`, `received_at` and `returned_at` to dates, and `voucher` to an array. `OrderShippingEvent` casts `status` to `ShipmentStatus`, `source` to `ShipmentEventSource`, `occurred_at` to a date, `latitude` and `longitude` to `decimal:7`, and `metadata` to an array. ## Database Schema [#database-schema] Shipments and their tracking events are stored in two tables, `sh_order_shipping` and `sh_order_shipping_events` (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)). Two columns of `sh_order_items` link an item to its shipment. ### OrderShipping Table [#ordershipping-table] The `sh_order_shipping` table holds one row per package: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `status` | string(32) | yes | null | Shipment status, cast to `ShipmentStatus`, indexed | | `order_id` | bigint | no | - | Order of the package. Deleting the order deletes its shipments | | `carrier_id` | bigint | yes | null | [Carrier](/3.x/carriers) of the package, set to `null` when the carrier is deleted | | `shipped_at` | datetime (with time zone) | yes | null | Date of the first event at or past Picked up, other than Returned | | `received_at` | datetime (with time zone) | yes | null | Date of the first Delivered event | | `returned_at` | datetime (with time zone) | yes | null | Date of the first Returned event | | `tracking_number` | string | yes | null | Carrier tracking number, indexed | | `tracking_url` | string | yes | null | Tracking page for the customer | | `voucher` | json | yes | null | Stored for your own code, such as label data. Shopper does not read it | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### OrderShippingEvent Table [#ordershippingevent-table] The `sh_order_shipping_events` table holds the timeline of each package, one row per status report: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `order_shipping_id` | bigint | no | - | Shipment of the event. Deleting the shipment deletes its events | | `status` | string(32) | no | - | Shipment status the event reports, cast to `ShipmentStatus` | | `external_id` | string | yes | null | Carrier identifier of the event, unique per shipment | | `source` | string(16) | no | `manual` | `manual` or `carrier`, cast to `ShipmentEventSource` | | `causer_id` | bigint (unsigned) | yes | null | ID of the user authenticated when the event was recorded, without a foreign key | | `description` | text | yes | null | Event description | | `location` | string | yes | null | Location name | | `latitude` | decimal(11,7) | yes | null | GPS latitude | | `longitude` | decimal(10,7) | yes | null | GPS longitude | | `occurred_at` | datetime (with time zone) | no | - | When the event happened | | `metadata` | jsonb | yes | null | Extra event data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### OrderItem Fulfillment Columns [#orderitem-fulfillment-columns] Two columns of `sh_order_items` carry the fulfillment of each item: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `order_shipping_id` | bigint | yes | null | Shipment that carries the item, set to `null` when the shipment is deleted | | `fulfillment_status` | string | yes | null | Fulfillment status, cast to `FulfillmentStatus`. The model sets `pending` on every new item | ## Relationships [#relationships] An order has many shipments, a shipment has many items and many tracking events, and an item belongs to one shipment at most. ### Order to Shipments [#order--shipments] `$order->shippings` returns the packages of an order. Load their carrier, items and timeline in one query when you display them: ```php $order->load('shippings.carrier', 'shippings.items', 'shippings.events'); ``` Read the shipping progress of the whole order from its `shipping_status`, described in [Shipping Status (Order Level)](#shipping-status-order-level). `$order->isShipped()` is `true` while the shipping status is Shipped, and `$order->isShippingPending()` while it is Unfulfilled. ### OrderShipping to Items and Events [#ordershipping--items--events] A shipment has five relationships: `order`, `carrier` (`null` when the package has no carrier), `items` (the order items in the package), `events` (its tracking timeline) and `taxLines` (the [tax lines](/3.x/taxes) charged on the package). The `events` relationship has no order of its own, so sort the timeline when you read it: ```php $timeline = $shipment->events()->oldest('occurred_at')->get(); ``` ### OrderItem to Shipment [#orderitem--shipment] `$item->shipment` returns the package that carries an order item, or `null` while the item is not on a shipment: ```php $item->shipment?->tracking_url; ``` ## Fulfillment Status [#fulfillment-status] The `Shopper\Core\Enum\FulfillmentStatus` enum tracks each order item. A new item starts as Pending, and Shopper moves it when its package is picked up, delivered or returned: | Case | Value | Admin label | Set by | |------|-------|-------------|--------| | `Pending` | `pending` | Awaiting fulfillment | Every new order item | | `ForwardedToSupplier` | `forwarded_to_supplier` | Forwarded to Supplier | Your code, see [Dropshipping Workflow](#dropshipping-workflow) | | `Processing` | `processing` | Preparing | Your code | | `Shipped` | `shipped` | Shipped | The pickup of the item's package | | `Delivered` | `delivered` | Delivered | The delivery of the item's package | | `Cancelled` | `cancelled` | Cancelled | The return of the item's package | Shopper checks no transition between item statuses: your code can write `fulfillment_status` directly, then call [SyncOrderShippingStatusAction](#syncordershippingstatusaction) so the order follows. The pickup of a package moves only its Pending items to Shipped. An item you set to Processing or Forwarded to Supplier keeps that status until its package is delivered, so set it to Shipped yourself when its package is picked up. Such an item is also left out of the Create Shipping Label form of the admin panel, which lists Pending items only. ## Shipping Status (Order Level) [#shipping-status-order-level] The `Shopper\Core\Enum\ShippingStatus` enum lives on the order, in its `shipping_status` column, and answers whether the order has shipped. A new order starts as Unfulfilled. Shopper computes the status from the fulfillment statuses of the items, as described in [SyncOrderShippingStatusAction](#syncordershippingstatusaction): | Case | Value | Meaning | |------|-------|---------| | `Unfulfilled` | `unfulfilled` | No item shipped or delivered yet | | `PartiallyShipped` | `partially_shipped` | Some items shipped, others still waiting | | `Shipped` | `shipped` | Every item shipped, none delivered or returned yet | | `PartiallyDelivered` | `partially_delivered` | Some items delivered | | `Delivered` | `delivered` | Every item delivered | | `PartiallyReturned` | `partially_returned` | Some items returned, all the others shipped or delivered | | `Returned` | `returned` | Every item returned | An order that is Delivered, Partially delivered, Returned or Partially returned can no longer be cancelled. ## Shipment Status (Package Level) [#shipment-status-package-level] The `Shopper\Core\Enum\ShipmentStatus` enum lives on the shipment and tracks the delivery of one package. Each package of an order goes through these statuses on its own: | Case | Value | Admin label | Meaning | |------|-------|-------------|---------| | `Pending` | `pending` | Label created | The shipment exists, the carrier has not collected it | | `PickedUp` | `picked_up` | Picked up | The carrier collected the package | | `InTransit` | `in_transit` | In transit | On the way | | `AtSortingCenter` | `at_sorting_center` | At sorting center | At a sorting facility | | `OutForDelivery` | `out_for_delivery` | Out for delivery | With the local delivery driver | | `Delivered` | `delivered` | Delivered | Delivered to the customer | | `DeliveryFailed` | `delivery_failed` | Delivery failed | A delivery attempt failed | | `Returned` | `returned` | Returned | Back to the sender | `isFinal()` is `true` for Delivered and Returned, and `ShipmentStatus::open()` returns the six other cases. The tracking sync stops polling a package once its status is final, as described in [Tracking Sync](#tracking-sync). ### Shipment Transitions [#shipment-transitions] The `HasFulfillmentTransitions` trait on `OrderShipping` lists the statuses a package can move to from each status. These transitions apply to the events recorded from the admin panel and from your code; carrier events follow the ranks described in [Tracking Events](#tracking-events): | From | Allowed next statuses | |------|-----------------------| | No status | Pending | | Pending | Picked up, Returned | | Picked up | In transit, Out for delivery, Delivery failed, Returned | | In transit | At sorting center, Out for delivery, Delivery failed, Returned | | At sorting center | In transit, Out for delivery, Delivery failed, Returned | | Out for delivery | Delivered, Delivery failed, Returned | | Delivered | Returned | | Delivery failed | In transit, Out for delivery, Returned | | Returned | None, the status is final | Only an Out for delivery package can be delivered, and every status except Returned can move to Returned. Three methods read the table: ```php use Shopper\Core\Enum\ShipmentStatus; $shipment->canTransitionTo(ShipmentStatus::InTransit); $shipment->allowedTransitions(); $shipment->canBeDelivered(); ``` `allowedTransitions()` returns an array of `ShipmentStatus` cases, and `canBeDelivered()` is `canTransitionTo(ShipmentStatus::Delivered)`. ### Transitioning Shipment Status [#transitioning-shipment-status] Change the status of a package with `RecordShipmentEventAction`. It checks the transition, updates the status, writes the tracking event, then updates the items and the order and dispatches the shipment events, as described in [RecordShipmentEventAction](#recordshipmenteventaction): ```php use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\ShipmentStatus; resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp, [ 'description' => 'Package collected by UPS', 'location' => 'New York, NY', 'latitude' => 40.7128, 'longitude' => -74.006, ]); ``` The model also has `transitionTo()`. It checks the transition, updates the status and writes the tracking event, and stops there: the items, the order, the `shipped_at`, `received_at` and `returned_at` dates and the shipment events stay as they were. When the transition is not allowed, it throws `Shopper\Core\Exceptions\InvalidShipmentStatusTransitionException` with a message such as `Cannot transition a shipment from "pending" to "delivered".` ### Tracking Events [#tracking-events] Each shipment keeps a timeline of `OrderShippingEvent` rows: the Pending event written when the shipment is created, then one row for each status report. The `source` column tells who reported it. `ShipmentEventSource::Manual` marks the events recorded from the admin panel and from your code, and `ShipmentEventSource::Carrier` the events that come from the carrier. `causer_id` holds the ID of the authenticated user, if any. A manual event must follow the [transitions](#shipment-transitions), and its `occurred_at` cannot be earlier than the latest event of the shipment. `RecordShipmentEventAction` returns `null` and records nothing when either check fails. Carriers report scans late and out of order, so a carrier event skips the transitions check. Each status has a rank instead: Pending 0, Picked up 10, In transit and At sorting center 20, Out for delivery and Delivery failed 30, Delivered 40, Returned 100. A carrier event moves the package when its status ranks higher than the current one, or when it ranks the same, differs from the current status and is not older than the latest event of the current status. Any other carrier event joins the timeline without changing the status, and `OrderShipmentEventRecorded` fires with `$statusChanged` set to `false`. A carrier event whose `external_id` is already on the shipment is ignored. A carrier can therefore move a package from Pending straight to Delivered. The changes of the pickup still apply: `shipped_at` is set, the Pending items become Shipped and a New order moves to Processing before the delivery is recorded. `$shipment->logEvent()` adds a row to the timeline and changes nothing else, the same as creating the row through `$shipment->events()`. Use it for a note that does not change the status of the package: ```php use Shopper\Core\Enum\ShipmentStatus; $shipment->logEvent(ShipmentStatus::InTransit, [ 'description' => 'Delayed by weather in Memphis', 'location' => 'Memphis, TN', 'metadata' => ['facility_code' => 'MEM-04'], ]); ``` ## Carrier Tracking [#carrier-tracking] A carrier driver of the `shopper/shipping` package reports tracking in one of two ways: it pushes updates to a webhook, or Shopper asks it for the tracking of each open package on a schedule. Both paths hand a `Shopper\Shipping\DataTransferObjects\TrackingInfo` to `Shopper\Shipping\Actions\ApplyTrackingInfoAction`, which records each scan of the carrier through `RecordShipmentEventAction` as a carrier event. Each scan becomes one tracking event. Its `external_id` is the identifier the carrier gives the scan, or a fingerprint of its status, time and location when the carrier gives none, so a scan received twice is recorded once. A tracking answer without a list of scans becomes one event with the overall status of the package. The FedEx and UPS drivers support tracking. The USPS and manual drivers do not, and none of the drivers Shopper ships supports webhooks. A [custom shipping driver](/3.x/carriers#custom-shipping-drivers) can add both. Your own integration, such as a warehouse or a carrier without a driver, records carrier events with the same action: ```php use Illuminate\Support\Carbon; use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\ShipmentStatus; resolve(RecordShipmentEventAction::class)->execute( $shipment, ShipmentStatus::AtSortingCenter, [ 'external_id' => 'scan-58213', 'location' => 'Memphis, TN', 'occurred_at' => Carbon::parse('2026-11-16 22:41:00'), ], fromCarrier: true, ); ``` ### Carrier Webhooks [#carrier-webhooks] The `shopper/api` package registers `POST /store/webhooks/shipping/{driver}` for carriers that push their updates, where `{driver}` is the name of a driver whose `supportsWebhooks()` returns `true`, and `store` is the API prefix set by `config('shopper.http.prefix')`. The bundled UPS, FedEx and USPS drivers return `false`: their packages are refreshed by the [tracking sync](#tracking-sync). The route passes the request to the `handleWebhook()` method of the driver, which verifies that the request comes from the carrier and returns a `TrackingInfo`, or `null` for a notification that has nothing to record. Shopper matches the package by its tracking number among the shipments whose carrier uses that driver. When several open packages share the tracking number, nothing is recorded and a warning is logged. The route answers `{"received": true}`, `404` for a driver that is unknown, not configured or without webhook support, and `400` when `handleWebhook()` throws. ### Tracking Sync [#tracking-sync] For carriers without webhooks, the scheduler runs `shopper:shipments:sync-tracking` every 30 minutes while `shopper.shipping.tracking.sync` is on. The command selects the configured drivers that support tracking and do not support webhooks, then queues one `Shopper\Shipping\Jobs\SyncShipmentTrackingJob` for each package that has a tracking number, a status other than Delivered or Returned, and a carrier using one of those drivers. Run it by hand to refresh the packages now: ```bash php artisan shopper:shipments:sync-tracking ``` The job calls `track()` on the driver and applies the answer. It skips a package that reached Delivered or Returned after it was queued, and logs a warning when the carrier does not know the tracking number. The job is unique per package for one hour, so a slow queue never holds two refreshes of the same package, and it retries after the delays of `tracking.backoff`. A package that is already Delivered is no longer polled, so a return after delivery reaches Shopper through a webhook or a manual event. The [Scheduler](/3.x/installation#scheduler) section of the installation guide lists the scheduled tasks. ## Configuration [#configuration] The tracking settings live under the `tracking` key of `config/shopper/shipping.php`, published with the `shopper-config` tag described in [Configuration Files](/3.x/configuration#configuration-files). The units and the rates cache of the same file belong to [Carriers](/3.x/carriers). | Key | Default | Description | |-----|---------|-------------| | `tracking.sync` | `true` (`SHIPPING_TRACKING_SYNC`) | Schedules `shopper:shipments:sync-tracking` every 30 minutes | | `tracking.queue` | `null` (`SHIPPING_TRACKING_QUEUE`) | Queue of the tracking jobs. `null` uses the default queue | | `tracking.backoff` | `[60, 300, 900]` | Seconds to wait before each retry of a failed tracking job. The job runs once more than the number of delays | A store with many packages in transit keeps the tracking jobs off the default queue, where they would wait in front of payment and order jobs. Name a queue and run a worker for it: ```bash title=".env" SHIPPING_TRACKING_QUEUE=tracking ``` The carrier drivers keep their access tokens in the default cache store, so use a shared cache store when several servers run the queue. ## Creating Shipments [#creating-shipments] `Shopper\Core\Actions\CreateShipmentAction` creates a package for some or all items of an order. In one database transaction, it creates the shipment with the Pending status, writes the first tracking event, attaches the items and dispatches `OrderShipmentCreated`. The optional `description` becomes the description of that first event. The new package has no `shipped_at`, and its items keep their fulfillment status: both change when the carrier picks the package up. An item already on another shipment is skipped. When none of the items can be attached, the action throws `Shopper\Core\Exceptions\CannotCreateEmptyShipmentException` and the transaction rolls back, so no empty shipment is saved. ### Single Shipment (All Items Together) [#single-shipment-all-items-together] When the whole order fits in one box, pass the IDs of all its items: ```php use Shopper\Core\Actions\CreateShipmentAction; use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\ShipmentStatus; use Shopper\Core\Models\Contracts\Order; $order = resolve(Order::class)::query()->with('items')->findOrFail($orderId); $shipment = resolve(CreateShipmentAction::class)->execute( $order, carrierId: $ups->id, itemIds: $order->items->modelKeys(), trackingNumber: '1Z999AA10123456784', trackingUrl: 'https://www.ups.com/track?tracknum=1Z999AA10123456784', ); resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp); ``` Pass `null` as `carrierId` for a package without a [carrier](/3.x/carriers), such as a local delivery. Recording the pickup sets `shipped_at`, moves the items to Shipped and a New order to Processing, and sets the shipping status of the order to Shipped. ### Partial Shipment (Split Across Packages) [#partial-shipment-split-across-packages] When the items leave from different warehouses or on different days, create one shipment per package, each with the items it carries and its own carrier. The items you leave out stay without a shipment and keep the Pending status, ready for a later package: ```php use Shopper\Core\Actions\CreateShipmentAction; $createShipment = resolve(CreateShipmentAction::class); $firstPackage = $createShipment->execute( $order, carrierId: $colissimo->id, itemIds: [$classicTShirt->id, $leatherBelt->id], trackingNumber: 'LP123456789FR', trackingUrl: 'https://www.laposte.fr/outils/suivre-vos-envois?code=LP123456789FR', ); $secondPackage = $createShipment->execute( $order, carrierId: $ups->id, itemIds: [$woolCoat->id], trackingNumber: '1Z999AA10987654321', trackingUrl: 'https://www.ups.com/track?tracknum=1Z999AA10987654321', ); ``` Each package follows its own statuses, and the shipping status of the order follows the items: Partially shipped once the first package is picked up, Shipped once the second one is, then Partially delivered and Delivered as the packages arrive. When a package is delivered before the last one is picked up, the order goes from Partially shipped to Partially delivered and never reaches Shipped. The [Shipment Events](/3.x/events#shipment-events) section shows the events of a split order in the order they fire. ### Marking as Delivered [#marking-as-delivered] `MarkShipmentDeliveredAction` records the Delivered status on a package. It does nothing when the package cannot be delivered, which is the case for every status except Out for delivery: ```php use Shopper\Core\Actions\MarkShipmentDeliveredAction; resolve(MarkShipmentDeliveredAction::class)->execute($shipment, [ 'description' => 'Left with the building concierge', 'location' => 'Brooklyn, NY', ]); ``` The delivery sets `received_at`, moves the items of the package to Delivered and computes the shipping status of the order again. When the order is in Processing, paid, and every one of its items is delivered, Shopper completes it and dispatches `OrderCompleted`. An order with a returned item is never completed this way, since a returned item is Cancelled. ## Dropshipping Workflow [#dropshipping-workflow] The items of a supplier's product ship the same way, with the tracking number the supplier sends back. The [Dropshipping Workflow](/3.x/suppliers#dropshipping-workflow) of the Suppliers page covers marking the items as Forwarded to Supplier, creating their shipment, and recording the pickup and the delivery. An order that mixes your own products and supplier products takes one shipment per sender: create yours with the items you pack, and the supplier's once its tracking number arrives. ## Querying Fulfillment Data [#querying-fulfillment-data] Shipments, items and orders can be queried by their statuses. `OrderShipping` and `OrderItem` cannot be swapped, so query them directly. Resolve the order class from its contract so a swapped model is used. ### Items by Status [#items-by-status] The items waiting for a package are the Pending items that are on no shipment, the same items the admin panel offers in its Create Shipping Label form: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Enum\FulfillmentStatus; use Shopper\Core\Models\OrderItem; $awaitingShipment = OrderItem::query() ->whereNull('order_shipping_id') ->where(fn (Builder $query) => $query ->whereNull('fulfillment_status') ->orWhere('fulfillment_status', FulfillmentStatus::Pending)) ->with('order.customer') ->get(); $awaitingSupplier = OrderItem::query() ->where('fulfillment_status', FulfillmentStatus::ForwardedToSupplier) ->with('product') ->get(); ``` ### Orders Needing Attention [#orders-needing-attention] The shipping status of the order tells which orders still have items to send, and the shipment status which packages need a follow-up with the carrier: ```php use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Enum\ShipmentStatus; use Shopper\Core\Enum\ShippingStatus; use Shopper\Core\Models\Contracts\Order; use Shopper\Core\Models\OrderShipping; $ordersToFulfill = resolve(Order::class)::query() ->whereIn('status', [OrderStatus::New, OrderStatus::Processing]) ->whereIn('shipping_status', [ShippingStatus::Unfulfilled, ShippingStatus::PartiallyShipped]) ->with('items', 'shippings') ->get(); $failedDeliveries = OrderShipping::query() ->where('status', ShipmentStatus::DeliveryFailed) ->with('order', 'carrier') ->get(); ``` ### Shipment History [#shipment-history] The packages of one customer, newest first, come from the `order` relationship of the shipment: ```php use Shopper\Core\Models\OrderShipping; $customerShipments = OrderShipping::query() ->whereRelation('order', 'customer_id', $customer->id) ->with(['carrier', 'items', 'order']) ->latest() ->get(); ``` ## Handling Returns [#handling-returns] A package that comes back is recorded with the Returned status. Every status except Returned can move to Returned, so the same call records a package refused by the customer and a return after delivery: ```php use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\ShipmentStatus; resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::Returned, [ 'description' => 'Returned by the customer: wrong size', ]); ``` The return sets `returned_at`, moves every item of the package to Cancelled, computes the shipping status of the order again and dispatches `OrderShipmentReturned`. Returned is final: no status follows it. A return does not refund the customer nor put the products back in stock. Refund the payment as described on the [Payments](/3.x/payments) page, and adjust the stock as described on the [Products](/3.x/products) page. ## Actions [#actions] Shopper changes fulfillment data through actions of the `Shopper\Core\Actions` namespace. They keep the shipment, its items and the order consistent, and dispatch the events. Resolve them from the container. ### RecordShipmentEventAction [#recordshipmenteventaction] `execute(OrderShipping $shipment, ShipmentStatus $status, array $context = [], bool $fromCarrier = false)` records a tracking event and returns the `OrderShippingEvent`, or `null` when nothing was recorded. The context takes `description`, `location`, `latitude`, `longitude`, `occurred_at` (a Carbon date, now by default), `external_id`, `metadata` and `causer_id` (the authenticated user by default). `fromCarrier: true` records a carrier event, with the rules described in [Tracking Events](#tracking-events). The action runs in a database transaction and locks the shipment and its order, so an event from the carrier and an event from the admin panel never update the same order at the same time. When the status changes, the new status brings more changes: | Status reached | What else changes | |----------------|-------------------| | The first status at or past Picked up, except Returned | `shipped_at` is set, the Pending items of the package become Shipped, a New order moves to Processing, and the shipping status of the order is computed again | | Delivered | `received_at` is set, the items that are not Delivered or Cancelled become Delivered, the shipping status is computed again, the order is completed when it is in Processing, paid and fully delivered, and `OrderShipmentDelivered` fires | | Delivery failed | `OrderShipmentDeliveryFailed` fires | | Returned | `returned_at` is set, every item of the package becomes Cancelled, the shipping status is computed again, and `OrderShipmentReturned` fires | Each date is set from the `occurred_at` of the event, and only once. Every status change then dispatches `OrderShipmentEventRecorded` with `$statusChanged` set to `true`. ### MarkShipmentDeliveredAction [#markshipmentdeliveredaction] `execute(OrderShipping $shipment, array $context = [])` records the Delivered status with `RecordShipmentEventAction` when `canBeDelivered()` is `true`, and does nothing otherwise. Its context takes `description`, `location`, `latitude`, `longitude` and `metadata`, and the event is dated now. The admin panel calls it from its Mark as delivered action. ### SyncOrderShippingStatusAction [#syncordershippingstatusaction] `execute(Order $order)` computes the `shipping_status` of an order from the fulfillment statuses of its items. Shopper runs it when a package is picked up, delivered or returned. Call it after your code writes `fulfillment_status` itself: ```php use Shopper\Core\Actions\SyncOrderShippingStatusAction; resolve(SyncOrderShippingStatusAction::class)->execute($order); ``` The action counts the Shipped, Delivered and Cancelled items and keeps the first row that matches. It does nothing for an order without items: | Condition | Shipping status | |-----------|-----------------| | Every item cancelled | `Returned` | | Some items cancelled, all the others shipped or delivered | `PartiallyReturned` | | No item shipped or delivered | `Unfulfilled` | | Every item delivered | `Delivered` | | Some items delivered | `PartiallyDelivered` | | Every item shipped, delivered or cancelled | `Shipped` | | Any other case | `PartiallyShipped` | When the status becomes Shipped from another status, the action dispatches `OrderShipped`. ## Events [#events] Shipments dispatch six events of the `Shopper\Core\Events\Orders` namespace: `OrderShipmentCreated`, `OrderShipmentEventRecorded`, `OrderShipmentDeliveryFailed`, `OrderShipmentDelivered` and `OrderShipmentReturned` for a package, and `OrderShipped` for the order. They are dispatched once the database transaction commits. The [Shipment Events](/3.x/events#shipment-events) section lists their payloads and the order in which they fire. Shopper sends no email when a package ships or arrives: listen to these events to notify the customer. Outgoing webhooks send five of them to your endpoints as `shipment.created`, `shipment.delivered`, `shipment.delivery_failed`, `shipment.returned` and `order.shipped`, as described on the [Webhooks](/3.x/webhooks) page. ## Permissions [#permissions] Shipments use the permissions of the `orders` resource, described on the [Access Control](/3.x/acl) page: | Permission | Allows | |------------|--------| | `orders.browse` | Opening the Shipments page and seeing its sidebar item | | `orders.read` | Opening the detail of a shipment and the form to add a tracking event | | `orders.edit` | Creating a shipment from the order page, saving a tracking event, marking a shipment as delivered, editing its carrier and tracking details | ## In the Admin [#in-the-admin] The order page shows the fulfillment steps (New, Processing, Shipped, Completed) and a Create Shipping Label button while the order is not cancelled, archived or completed and some of its items are on no shipment. The button opens a slide-over with the carrier, preset to the carrier of the shipping option the customer chose, the tracking number and URL, and the items to fulfill, all the Awaiting fulfillment items by default: remove the ones that go in a later package. It records the shipment and does not buy a label from the carrier. The Shipments page, under Orders in the sidebar, lists every package with the tabs All, Label created, In transit, Delivered and Delivery failed, and filters by status, order and carrier. From a row, Mark as delivered appears once the package is Out for delivery, Edit changes the carrier and the tracking details, and Manage shipment opens the timeline, where Add event records one of the allowed next statuses with its date, location and description. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes shipments read-only. A signed-in customer reads the packages of an order with `GET /store/customers/me/orders/{orderId}?include=shippings,shippings.events`, where each package comes with the name of its carrier, and the order itself carries its `shipping_status`. The order lookup at `GET /store/orders/{orderId}` does not include shipments. `GET /store/shipments/{shipmentId}?include=events` returns one package by its public ID. `events` is the only include it accepts, and the events come oldest first. A package is an `order-shippings` resource with the attributes `status`, `carrier_name`, `tracking_number`, `tracking_url`, `shipped_at`, `received_at` and `returned_at`. An event is an `order-shipping-events` resource with `status`, `description`, `location`, `latitude`, `longitude`, `occurred_at` and `created_at`. The Store API [Orders](/3.x/store-api/orders#tracking-a-shipment) guide shows how a storefront tracks a shipment. ### Order Tracking Page [#order-tracking-page] A storefront rendered by Laravel reads the same data from the models. This controller shows the packages of an order to the customer who placed it: ```php title="app/Http/Controllers/OrderTrackingController.php" namespace App\Http\Controllers; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Http\Request; use Illuminate\View\View; use Shopper\Core\Models\Contracts\Order; class OrderTrackingController extends Controller { public function show(Request $request, string $number): View { $order = resolve(Order::class)::query() ->where('customer_id', $request->user()->id) ->where('number', $number) ->with([ 'shippings.carrier', 'shippings.items', 'shippings.events' => fn (HasMany $events) => $events->latest('occurred_at'), ]) ->firstOrFail(); return view('orders.tracking', ['order' => $order]); } } ``` The view lists each package with its status, its items and the link to the carrier's tracking page: ```blade title="resources/views/orders/tracking.blade.php" @foreach ($order->shippings as $shipment)

    {{ $shipment->carrier?->name }}: {{ $shipment->status?->getLabel() }}

      @foreach ($shipment->items as $item)
    • {{ $item->quantity }} x {{ $item->name }}
    • @endforeach
    @if ($shipment->tracking_url) Track {{ $shipment->tracking_number }} @endif
    @endforeach ``` # Introduction (/3.x/getting-started) Shopper is an open-source headless e-commerce package for Laravel. It adds an admin panel, a Store API for your storefront, and the commerce logic a store needs (catalog, carts, orders, payments, shipping, taxes) to the Laravel application you already have, without taking over your codebase. Shopper 3.0 ## Why Shopper? [#why-shopper] There are several ways to add e-commerce to a Laravel application. You could integrate an external platform like Shopify, adopt a full e-commerce system like Lunar or Bagisto, or build everything from scratch. Each approach has trade-offs. Shopper takes a different path. It is a Laravel package, not a platform. You install it into your existing application the same way you would install `spatie/laravel-permission` or `laravel/cashier`. Your routes, your middleware, your authentication, your deploy pipeline stay unchanged. You add e-commerce to your app, not the other way around. ### Building Blocks, Not a Monolith [#building-blocks-not-a-monolith] Most e-commerce systems assume one-size-fits-all. But selling cars is not the same as selling sneakers, and a subscription box service has nothing in common with a marketplace. Shopper recognizes this by giving you composable building blocks instead of a rigid platform. The main Eloquent models (products, categories, orders and more) can be swapped for your own classes through configuration. The admin pages can be replaced with your own Livewire components. Optional sections such as brands, campaigns or reviews can be turned off. You start with a production-ready foundation and shape it to match your business. ### Headless from Day One [#headless-from-day-one] Shopper handles the commerce logic and the admin panel. You build the storefront with whatever stack your team already ships with: Blade, Livewire, Inertia, Next.js, Nuxt, React Native, or anything else. A storefront rendered by Laravel reads the Eloquent models directly. A storefront that runs elsewhere talks to the Store API, a [JSON:API](https://jsonapi.org) that exposes the catalog, carts, checkout, customer accounts and orders. Customers sign in with Laravel Sanctum tokens, and the official JavaScript SDK, `@shopperlabs/shopper-sdk`, calls the API from browsers, Node.js 18+, React Native and edge runtimes. ### A Package, Not a Platform [#a-package-not-a-platform] This distinction matters. A platform owns your application. You build on top of it, adapt to its conventions, and work within its constraints. A package is a tool you control. Shopper adds e-commerce capabilities to your Laravel application without replacing your User model, your authentication system, or your application structure. Your User model gains Shopper capabilities through a trait. The admin panel is a feature of your app, not the other way around. Your database is extended, not replaced. ## Tech Stack [#tech-stack] Shopper 3 runs on [Laravel](https://laravel.com) 12 or 13 and PHP 8.3 or higher. The admin panel is made of [Livewire](https://livewire.laravel.com) 4 pages that use [Filament](https://filamentphp.com) 5 tables, forms and actions, styled with [Tailwind CSS](https://tailwindcss.com). It is not a Filament panel plugin: it registers its own routes and layout. Although the admin panel uses Livewire, there is no requirement for the storefront to use Livewire. You can build your storefront with any stack. ## Packages [#packages] Shopper is made up of several Composer packages that work together. Installing `shopper/framework` pulls in `core`, `cart`, `payment`, `shipping` and `sidebar`; the others are installed when you need them. | Package | What it does | |---|---| | `shopper/core` | The e-commerce engine: models, contracts, migrations, enums and observers. It has no dependency on any UI layer. | | `shopper/framework` | The admin panel, for managing products, orders, customers, and more. It provides all Livewire pages and components, and adds [Spatie Media Library](https://spatie.be/docs/laravel-medialibrary) support to the catalog models. | | `shopper/cart` | Shopping carts, with totals calculated through a pipeline: lines, automatic promotions, discount codes, taxes. | | `shopper/payment` | A driver-based payment architecture, with webhook handling and reconciliation of pending payments. | | `shopper/stripe` | The official Stripe payment driver. | | `shopper/shipping` | Shipping rates and shipment tracking through drivers. Carriers and zones themselves are core models. | | `shopper/fedex`, `shopper/ups`, `shopper/usps` | Carrier drivers for live rates. FedEx and UPS also sync tracking. | | `shopper/api` | The Store API, served under `/store`. | | `shopper/http` | The Store API's HTTP layer: route group, rate limits, CORS, and middleware that resolves the channel, zone, locale and customer of each request. | | `shopper/sidebar` | The admin panel navigation, which you extend to add your own entries. | | `shopper/upgrade` | A temporary package that moves a 2.x store to 3.x with `php artisan shopper:upgrade`. | For storefronts written in JavaScript or TypeScript, two npm packages complete the set: `@shopperlabs/shopper-sdk`, the Store API client, and `@shopperlabs/shopper-types`, the type definitions of the objects it returns. The `core` package defines contracts (interfaces) for its models. When you swap a model via configuration, the entire system (admin panel, relationships, route bindings) uses your custom class automatically. ## Key Features [#key-features] Shopper ships with everything you need to run an online store: Variants, attributes, media, CSV import, and four product types (standard, virtual, external, variant). Full order lifecycle with independent payment, shipping, and order statuses. Unlimited hierarchical nesting with SEO fields and media. Manual or rule-based product grouping. Customer profiles, addresses, and order history. Discount codes and automatic promotions, with stacking rules, priorities, and campaigns with a budget. Multi-warehouse stock with allocation, reservations at checkout, and an audit trail. Carriers, zones, rates, and shipment tracking, with FedEx, UPS and USPS drivers. Driver-based payment processing, with an official Stripe driver. Tax zones, rates and rules, calculated in the cart and stored on each order. JSON:API endpoints for the catalog, carts, checkout, accounts and orders, with a JavaScript SDK. Signed outgoing webhooks for order, shipment, product and customer events. Organize products by brand with media and SEO. Customer product reviews and ratings, published after approval. Sales channels, with the Store API showing each channel only its own products. ## Extensibility [#extensibility] Shopper is designed to be extended, not forked. Three mechanisms make this possible. **Model swapping** lets you replace a model with your own class that extends it. The thirteen swappable models (products, variants, product attribute values, categories, brands, collections, orders, channels, inventories, suppliers, addresses, tax zones and tax rates) are listed in `config/shopper/models.php`. Point an entry to your class and the entire system uses it, including the admin panel, relationships, and route model binding. **Component overriding** lets you replace an admin panel page or form with your own Livewire component. Run `php artisan shopper:component:publish product` to get `config/shopper/components/product.php`, where each page and form of that section points to a class you can change. Pass `--all` to publish every section at once. **Feature toggling** lets you remove optional sections of the admin panel: attributes, brands, campaigns, categories, collections, discounts, reviews, suppliers and tags. Set a feature to `FeatureState::Disabled` in `config/shopper/features.php` and its pages and menu entries disappear. ## Stability and Versioning [#stability-and-versioning] Shopper follows [Semantic Versioning](https://semver.org/). Minor and patch releases never contain breaking changes. Every component is tested, and upgrade guides are published for every major version bump. For details on supported versions and maintenance windows, see the [Version Support Policy](/3.x/version-support-policy). If your store runs Shopper 2, the [upgrade guide](/3.x/upgrade) walks you through the move to 3.x. ## When Shopper Fits [#when-shopper-fits] Shopper is the right choice when you already have a Laravel application (or want to build one) and need to add e-commerce capabilities without adopting an opinionated platform. It works well when your storefront is non-standard: a product configurator, a subscription service, an auction site, or anything that does not fit the typical "browse and checkout" template. With the Store API, the same store can also serve a JavaScript storefront or a mobile app. If you need a store running in an hour, Shopify is a better fit. If you are not in the Laravel ecosystem, MedusaJS is worth considering. ## Next Steps [#next-steps] Check server requirements before installing. Install Shopper in your Laravel application. # Import (/3.x/import) Shopper imports products from a CSV file. One file creates or updates products with their variants, options, prices, stock, brand, categories, tags and images. Merchants start an import from the Products page of the admin panel, your code can start the same import, and an add-on can register another source, such as the export of another platform. An import runs on the queue. Shopper reads the file, groups its rows into products, and dispatches the products in chunks as a Laravel job batch. Each product is found by its handle, so importing the same file twice updates the products instead of duplicating them. ## Requirements [#requirements] An import relies on three parts of your application: - A running queue worker, as described in [Queue Worker](/3.x/installation#queue-worker). On the `sync` connection, the whole import runs inside the request that starts it. On the `deferred` connection, it runs after the response is sent. - The `job_batches` table of Laravel job batches. The default jobs migration of a Laravel application creates it. If your application does not have it, create it with `php artisan make:queue-batches-table`, then run `php artisan migrate`. A batch needs this table on every queue connection, `sync` included. - A default inventory location. The imported quantities go to that location, and they are ignored when the store has none. The [Locations](/3.x/locations) page covers inventory locations. ## The ProductImport Model [#the-productimport-model] Every import is a `Shopper\Core\Models\ProductImport` record in the `sh_product_imports` table. The model has no configuration key and no contract, so it is always loaded with its own class. `HasPublicId` fills `public_id` with a ULID when the import is created. | Column | Type | Description | |--------|------|-------------| | `id` | bigint | Primary key | | `public_id` | string(26), nullable | ULID set on creation | | `source` | string | The code of the import source, `csv` for a CSV file | | `disk` | string | The filesystem disk that holds the file | | `file_path` | string | The path of the file on that disk | | `status` | string | An `ImportStatus` value | | `total_products` | unsigned integer, default `0` | The number of products found in the file | | `imported_count` | unsigned integer, default `0` | The products created or updated | | `failed_count` | unsigned integer, default `0` | The products that could not be imported | | `mapping` | jsonb, nullable | The file column to read for each Shopper field | | `errors` | jsonb, nullable | A list of errors, each with a `handle` and a `message` | | `batch_id` | string, nullable | The ID of the Laravel job batch | | `user_id` | bigint, nullable | The ID of the user who started the import | | `started_at` | timestamp, nullable | When the rows were dispatched | | `finished_at` | timestamp, nullable | When the import ended | The model defines no relationship. `user_id` holds the ID of a record of your user model, without a foreign key constraint. ### Import Status [#import-status] The `status` column is cast to the `Shopper\Core\Enum\ImportStatus` enum. An import starts as `Pending`, moves to `Processing` when its jobs are dispatched, and ends in one of the last three statuses: | Case | Value | Label | Color | |------|-------|-------|-------| | `Pending` | `pending` | Pending | gray | | `Processing` | `processing` | Processing | info | | `Completed` | `completed` | Completed | success | | `CompletedWithErrors` | `completed_with_errors` | Completed with errors | warning | | `Failed` | `failed` | Failed | danger | `isFinished()` returns `true` for `Completed`, `CompletedWithErrors` and `Failed`: ```php use Shopper\Core\Models\ProductImport; $import = ProductImport::query()->latest()->first(); if ($import->status->isFinished()) { echo "{$import->imported_count} of {$import->total_products} products imported."; } ``` ## File Format [#file-format] The CSV source reads a file whose first row holds the column names. The admin panel links a sample file, which `php artisan shopper:link` also publishes at `/vendor/shopper/templates/product-import.csv`. The `handle` and `name` columns are required: a file without one of them fails before any product is read. Every other column is optional, and a blank cell counts as empty. | Column | Read from | Description | |--------|-----------|-------------| | `handle` | Every row | Groups the rows of one product and becomes its slug | | `name` | First row | The product name | | `description` | First row | The product description | | `brand` | First row | A brand name | | `category` | First row | A category path, segments separated by `>` | | `tags` | First row | Tag names separated by commas | | `published` | First row | `TRUE` or `FALSE`, sets the visibility, `TRUE` when empty | | `seo_title`, `seo_description` | First row | The SEO fields | | `option1_name`, `option2_name`, `option3_name` | First row | Up to three option names, such as `Size` and `Color` | | `option1_value`, `option2_value`, `option3_value` | Variant rows | The option values of the variant | | `sku`, `barcode`, `ean`, `upc` | Variant rows | The identifiers. A standard product stores the SKU and the barcode | | `price`, `compare_at_price`, `cost_per_item` | Variant rows | Decimal amounts, such as `19.99` | | `currency` | Variant rows | A currency code, the store default currency when empty | | `quantity` | Variant rows | The stock, `0` when empty | | `weight_value`, `weight_unit` | Variant rows | The weight, in `kg`, `g` or `lbs` | | `image_url` | Any row | One image URL, or several separated by `;` | | `image_position` | Any row | The position of the images of the row | | `image_alt` | Any row | The alternative text of the images of the row | | `variant_image_url` | Variant rows | The image of the variant | The sample file also has a `requires_shipping` column. Shopper reads it but stores it nowhere: set the shipping of a product in the admin panel. ### Products and Variants [#products-and-variants] Consecutive rows with the same handle form one product, and rows with an empty handle are skipped. Keep the rows of a product together: when a handle comes back after another product, its new rows are read as a separate product, which fails when its first row has no name. The first row holds the product columns. The first row is also a variant row, and so is every other row of the product that has a `sku`, a `price` or an `option1_value`. A row with none of them only adds images. A product with a single variant row and no option name is a standard product: its SKU, barcode, weight, price and stock go to the product. Any other product is a variant product, and each variant row creates or updates a variant. The import sets one of these two types on every product it creates or updates. A variant is named after its option values, such as `Small / Green`, or after the product when it has no option value. Shopper finds an existing variant by its SKU, or by its name when the row has no SKU, and adds new variants after the existing ones. The sample file imports the "Graphic T-Shirt" with three variants: ```csv handle,name,option1_name,option1_value,option2_name,option2_value,sku,price,quantity graphic-t-shirt,Graphic T-Shirt,Size,Small,Color,Green,TSHIRT-S-GREEN,19.99,47 graphic-t-shirt,,,Medium,,Green,TSHIRT-M-GREEN,19.99,40 graphic-t-shirt,,,Medium,,Red,TSHIRT-M-RED,19.99,56 ``` Each option name becomes a select attribute and each option value an attribute value, created when missing, and each variant is linked to its values. The import does not attach the attributes to the product itself: the Attributes section of the product editor and the `options` include of the Store API stay empty for an imported product until the attributes are added to it, as described on the [Attributes](/3.x/attributes) page. ### Brand, Categories and Tags [#brand-categories-and-tags] The `brand` column holds a brand name. Shopper uses the brand with that name, or creates it, enabled, when none exists. The `category` column holds one path from a root category, such as `Apparel & Accessories > Clothing > T-Shirts`. Shopper looks up each segment by name under its parent, creates the missing ones, enabled, and attaches the product to the last one. The `tags` column holds tag names separated by commas, created when missing. Brands, categories and tags created by an import get a slug made from their name. The import adds categories and tags to a product and never removes the ones already attached. ### Prices [#prices] The `price`, `compare_at_price` and `cost_per_item` columns hold decimal amounts as merchants write them, such as `19.99`. Shopper multiplies them by 100 and rounds them to store them in cents, as described on the [Money](/3.x/money) page. The `currency` column takes the code of a currency enabled on the store, in any case. When it is empty, the price goes to the store default currency. A row with a price replaces the price of the product or variant in that currency, its compare-at and cost amounts included. A row without a price leaves the prices unchanged. The import multiplies every amount by 100, zero-decimal currencies included. A price of `15000` in XAF is stored as `1500000` and displays as 1,500,000 FCFA, while Shopper stores these currencies in whole units, as described in [Zero-Decimal Currencies](/3.x/money#zero-decimal-currencies). For a zero-decimal currency, divide the amounts of the file by 100, or set the prices in the admin panel after the import. ### Stock and Weight [#stock-and-weight] The `quantity` column sets the stock of the product or variant. Shopper records the difference with the current stock as a movement at the default inventory location, labeled "Product import" in the inventory history described in [Stock Management](/3.x/products#stock-management). An empty quantity counts as `0`, so importing a file without this column sets the stock of every product to 0. `weight_value` sets the weight in the unit of `weight_unit`: `kg`, `g` or `lbs`, in any case. An empty or unknown unit stores grams. A row without `weight_value` leaves the weight unchanged. ### Images [#images] The `image_url` column holds one image URL, or several separated by `;`. Every row of a product can add images to its gallery. `image_position` sets the position of the images of the row, and images without a position follow the order of the file. `image_alt` becomes the name of the media, which the Store API returns as `name`. `variant_image_url` adds one image to the gallery of the variant of that row, on a product with variants only. Shopper downloads the images in queued jobs once the product is saved, as described in [Image Downloads](#image-downloads), and skips a URL already imported for the same product or variant. ### Updating Products [#updating-products] Shopper finds an existing product by its slug, which must equal the handle. Write handles as slugs, in lowercase letters, digits and hyphens, such as `graphic-t-shirt`. A new product stores its handle as its slug, and Shopper turns any other value into a URL-safe slug: `Graphic T-Shirt` is stored as `graphic-t-shirt`, so the next import of that handle does not find the product and creates a second one. An update writes every product column read from the file, empty cells included: an empty description, brand or SEO cell clears that value on the product. The SKU and barcode of a standard product, and the SKU, barcode, EAN and UPC of the variants, are replaced the same way. The publication date of a new product is the date of the import, and an existing product keeps its own. The import also turns off backorders on every standard product and every variant it saves. ## How an Import Runs [#how-an-import-runs] `Shopper\Core\Import\StartProductImport` starts an import from a `ProductImport` record in the `Pending` status: 1. It resolves the source named in the `source` column, passes it the `mapping`, and reads the whole file from the path that `Storage::disk($import->disk)->path()` returns. The file must therefore sit on a local disk. 2. It splits the products into chunks of `shopper.core.import.chunk_size` products, one `Shopper\Core\Jobs\ImportProductsChunkJob` per chunk, then sets the status to `Processing`, the `total_products` and the `started_at` date. 3. It dispatches the jobs as a batch named `product-import-{id}` that allows failures, and stores its ID in `batch_id`. 4. Each job imports its products one by one, each in a database transaction. A product that throws an exception is added to `errors` and `failed_count`, and the next product goes on. The job adds the created and updated products to `imported_count`, then adds the image downloads of its products to the batch. 5. Once every job of the batch has run, the import gets the `CompletedWithErrors` status when it has errors or failed jobs, `Completed` otherwise, and its `finished_at` date. Shopper then dispatches the `ProductImportCompleted` event. A file with no product ends as `Completed` right away and dispatches the event as well. A job skips its products when the import has the `Failed` status or its batch is cancelled. Shopper indexes each product once it is saved, under the rules of the [Search](/3.x/search) page, and the imported products join the automatic [collections](/3.x/collections) whose rules they match, through the same queued sync as the products saved in the admin panel. ### Image Downloads [#image-downloads] `Shopper\Core\Jobs\DownloadProductImageJob` downloads one image into the gallery collection of a product or variant, named by `shopper.media.storage.collection_name` and described on the [Media](/3.x/media) page. The job tries three times, 10 then 60 seconds apart, and only once on the `sync` connection. It does not retry an image the collection refuses, a 4xx response other than 429, or a file larger than the `media-library.max_file_size` limit of Spatie Media Library, 10 MB by default. Shopper downloads `http` and `https` URLs only, follows at most three redirects and waits 30 seconds at most. The image host must resolve to a public IP address. An image that still fails adds an error to the import, under the slug of the product, while the import holds fewer than 100 errors. Image errors do not change `failed_count`. ## Errors [#errors] An import meets two kinds of errors. A file error stops the whole import. A product error skips one product, and the import goes on with the others. A file error is a missing required column, an unknown source, a file that cannot be read, or a batch that cannot be dispatched. The import gets the `Failed` status, its `finished_at` date and a single error with `*` as handle, then `execute()` throws the exception again. No `ProductImportCompleted` event is dispatched. A missing column gives this message: ```text The file does not match the product import template: missing the handle column. ``` Product errors keep the handle of the product and the message of the exception: | Message | Cause | |---------|-------| | `Product [graphic-t-shirt] has no name.` | The first row of the product has no `name` | | `Currency [EUR] is not enabled on this store.` | The `currency` column holds a currency the store does not sell in | | `Image [https://example.com/t-shirt.jpg] could not be imported: ...` | An image failed after its last attempt. The reason follows the colon, such as `Image host [example.com] is not a public address.` | Any other exception thrown while a product is saved is recorded with its own message. The admin panel does not display the errors, so read them from the model: ```php use Shopper\Core\Enum\ImportStatus; use Shopper\Core\Models\ProductImport; $import = ProductImport::query() ->where('status', ImportStatus::CompletedWithErrors) ->latest() ->first(); foreach ($import->errors ?? [] as $error) { echo "{$error['handle']}: {$error['message']}"; } ``` ## Configuration [#configuration] The number of products per job is set in `config/shopper/core.php`: ```php title="config/shopper/core.php" 'import' => [ 'chunk_size' => 25, ], ``` Each chunk runs in a single job, with its products, their categories, prices and stock. Lower the value when a chunk takes longer than the timeout of your queue worker. ## Importing From Code [#importing-from-code] Your code starts an import the way the admin panel does: store the file on a local disk, create a `ProductImport` in the `Pending` status, and pass it to `StartProductImport`. This controller imports the catalog a merchant uploads: ```php title="app/Http/Controllers/CatalogImportController.php" validate(['catalog' => ['required', 'file', 'mimes:csv,txt']]); $import = ProductImport::query()->create([ 'source' => 'csv', 'disk' => 'local', 'file_path' => $request->file('catalog')->store('shopper/imports', 'local'), 'mapping' => ['name' => 'Title', 'handle' => 'Slug', 'price' => 'Retail Price'], 'status' => ImportStatus::Pending, 'user_id' => $request->user()->id, ]); $startImport->execute($import); return back(); } } ``` The `mapping` keys are Shopper column names, and the values are the columns of your file. A column missing from the mapping is read under its own name, so a file that follows the sample needs no mapping. From code, you can map every column of the format, the options and images included; the admin panel offers 20 of them. `execute()` throws the exception of a file error after marking the import as failed. On a queue connection other than `sync`, it returns before the products are imported, and the `ProductImportCompleted` event tells you when the import ends. ## Custom Import Sources [#custom-import-sources] A source reads a file and returns the products it holds. Shopper ships the `csv` source, `Shopper\Core\Import\Sources\CsvSource`, and resolves sources through the `Shopper\Core\Import\ImportManager` singleton, a Laravel manager. To import another format, implement `Shopper\Core\Import\Contracts\ImportSource`: | Method | Returns | |--------|---------| | `code()` | The code stored in the `source` column of an import | | `name()`, `description()`, `icon()` | The name, description and icon shown in the source picker of the admin panel | | `isConfigured()` | Whether the source can run. The admin panel lists configured sources only | | `read(string $path)` | A `LazyCollection` of `Shopper\Core\Import\ProductRow` objects | `read()` builds the products with three readonly classes of `Shopper\Core\Import`: `ProductRow` for a product, `VariantRow` for each variant, and `ImageRow` for each image. This source reads a JSON feed from a supplier: ```php title="app/Import/SupplierFeedSource.php" map(fn (array $product): ProductRow => new ProductRow( handle: $product['slug'], name: $product['title'], description: $product['description'], brand: $product['brand'], published: true, variants: [ new VariantRow( sku: $product['sku'], price: $product['price'], quantity: $product['stock'], ), ], images: [new ImageRow(url: $product['image'])], )); } } ``` `ProductRow` and `VariantRow` take the same values as the CSV columns. `VariantRow` also takes `allowBackorder`, which the CSV source leaves at `false`. A product row with a single variant and no `optionNames` is a standard product. Register the source in the `boot()` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Import\SupplierFeedSource; use Shopper\Core\Import\ImportManager; public function boot(): void { resolve(ImportManager::class)->extend('supplier-feed', fn (): SupplierFeedSource => new SupplierFeedSource); } ``` An import whose `source` column holds `supplier-feed` now reads its file with this class. A source that also implements `Shopper\Core\Import\Contracts\SupportsColumnMapping` returns the columns of a file from `headers(string $path)` and receives the `mapping` of the import through `withMapping(array $mapping)`, which returns a configured copy of the source. In the admin panel, the **Import** action lists the configured sources and opens the slide-over registered as `slide-overs.import-{code}` for the one the merchant picks. Shopper ships the slide-over of the CSV source only. For your source, write a Livewire slide-over that stores the file and starts the import, as `Shopper\Livewire\SlideOvers\ImportCsv` does, publish the product components with `php artisan shopper:component:publish product`, and add your slide-over to the `components` array of `config/shopper/components/product.php`: ```php title="config/shopper/components/product.php" 'components' => [ 'slide-overs.import-supplier-feed' => \App\Livewire\SlideOvers\ImportSupplierFeed::class, ], ``` ## Events [#events] An import dispatches two events from `Shopper\Core\Events\Products`: | Event | Dispatched when | |-------|-----------------| | `ProductCreated` | The import creates a new product | | `ProductImportCompleted` | The import ends with the `Completed` or `CompletedWithErrors` status | Updating an existing product dispatches no event, and a failed import dispatches none either. `ProductImportCompleted` carries the import as `public ProductImport $import`: ```php title="app/Listeners/ReportProductImportErrors.php" import->status !== ImportStatus::CompletedWithErrors) { return; } Log::warning('The product import finished with errors.', [ 'import' => $event->import->public_id, 'errors' => $event->import->errors, ]); } } ``` When the database notifications of the admin panel are enabled, as described in [Notifications](/3.x/configuration#notifications), the `Shopper\Listeners\Notifications\SendProductImportCompletedNotification` listener stores a "Product import finished" notification for every administrator, with the number of products imported and failed. The listener is queued on the `notifications` queue, so your worker must listen to that queue. The [Events](/3.x/events#product-events) page lists the product events, and the [Notifications](/3.x/notifications) page lists the notifications. ## Permissions [#permissions] The admin panel checks these permissions for imports: | Permission | Checked for | |------------|-------------| | `products.browse` | The Products page that holds the **Import** action | | `products.create` | The **Import** action and the CSV slide-over | `StartProductImport` checks no permission: your code authorizes the user before it starts an import. The [Access Control](/3.x/acl) page lists every permission. ## In the Admin [#in-the-admin] Merchants import products from the **Products** page. **Import** opens a dialog that lists the configured sources, and **Next** opens the slide-over of the chosen one. The CSV slide-over has three steps: **Upload** takes the file and links the sample file, **Columns** matches each Shopper field with a column of the file and preselects the columns named after a field, and **Review** shows the number of products, variants and stock units with a preview of the first 50 products. **Import products** stores the file on the `local` disk under `shopper/imports`, starts the import and confirms it with a notification. The product list does not refresh by itself: reload the page to see the imported products. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API does not expose imports. Imported products are regular products, and a storefront reads them as described in the Store API [Catalog](/3.x/store-api/catalog) guide. # Installation (/3.x/installation) Shopper installs into an existing Laravel 12 or 13 application. If you do not have one yet, create a project first by following the [Laravel installation guide](https://laravel.com/docs/installation). Check the [requirements](/3.x/requirements) before you start: Composer refuses to install Shopper while a PHP extension is missing. ## Install the Package [#install-the-package] Install `shopper/framework` with Composer: ```bash composer require shopper/framework:"^3.0" ``` The package pulls in `shopper/core`, `shopper/cart`, `shopper/payment`, `shopper/shipping` and `shopper/sidebar`, along with Filament and Livewire. If you have a cached config from a previous setup, run `php artisan config:clear` before installing. ## Prepare Your User Model [#prepare-your-user-model] The admin panel signs users in with your application's `User` model. Add the `InteractsWithShopper` trait, implement the `ShopperUser` interface and replace the fillable columns with the ones Shopper writes: ```php title="app/Models/User.php" use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; #[Fillable([ 'first_name', 'last_name', 'email', 'password', 'phone_number', 'gender', 'birth_date', 'opt_in', 'email_verified_at', 'avatar_type', 'avatar_location', 'last_login_at', 'last_login_ip', 'store_two_factor_secret', 'store_two_factor_recovery_codes', ])] #[Hidden([ 'password', 'remember_token', 'store_two_factor_secret', 'store_two_factor_recovery_codes', ])] class User extends Authenticatable implements ShopperUser { use InteractsWithShopper; use Notifiable; } ``` The trait gives the model roles and permissions, orders, addresses, discounts, a profile photo and a public ID, and makes users searchable with Laravel Scout. Scout's default `collection` driver searches the database, so it needs no setup. Shopper creates and updates users with mass assignment, so the fillable list replaces Laravel's default `name`, `email` and `password`: a Shopper migration renames the `name` column to `last_name` and adds `first_name`. The [Customers](/3.x/customers#user-model-integration) page explains each column. `Notifiable` sends the welcome and password reset emails. The two extra hidden attributes hold the two-factor authentication secret and recovery codes, which must never appear in a JSON response. A model created before Laravel 13 lists these columns in the `$fillable` and `$hidden` properties instead. Two-factor authentication and passkeys need more contracts and traits on the model, described on the [Two-Factor Authentication](/3.x/two-factor) page. ## Run the Installer [#run-the-installer] The install command publishes the configuration files, links the storage and the panel assets, and offers to run the migrations and seeders: ```bash php artisan shopper:install ``` The installer performs these steps: 1. Publishes the Shopper config files to `config/shopper/` 2. Publishes the Spatie Media Library migrations 3. Publishes the Filament assets 4. Runs `php artisan shopper:link`: links `public/storage` to the `public` disk, where product, category and brand images are stored, and `public/vendor/shopper` to the panel assets 5. Asks whether to run the migrations and seed the database with roles, permissions and default data If `config/shopper/admin.php` already exists, the installer stops and prints the commands to publish the configuration, run the migrations and create the links by hand. It leaves the seeders out so that they never run twice on the same database. If the database has never been seeded, run them after the migrations. The first one creates the countries, currencies, legal pages, sales channel, carriers and payment methods, the second the roles and permissions: ```bash php artisan db:seed --class="Shopper\Core\Database\Seeders\ShopperSeeder" php artisan db:seed --class="Shopper\Database\Seeders\AuthTableSeeder" ``` The migrations change your `users` table: the `name` column is renamed to `last_name` (or created when the table has none), `password` becomes nullable, and columns such as `first_name`, `gender`, `phone_number`, `birth_date`, `timezone` and `last_login_at` are added. Update any code, factory or form of your application that reads or writes `name` before you migrate. All Shopper tables are prefixed with `sh_` by default so that they never collide with your own tables. To use another prefix, answer no when the installer asks to run the migrations, then follow the steps on the [Configuration](/3.x/configuration#database-table-prefix) page. ## Create an Admin User [#create-an-admin-user] Create your first admin user to sign in to the admin panel: ```bash php artisan shopper:user ``` The command asks for an email, a first name, a last name and a password (at least 6 characters). The user gets the administrator role, which exists only once the seeders have run. If you skipped them in the installer, the command stops before asking anything and prints the seeder to run: [run the seeders](#run-the-installer), then the command again. ## Access the Admin Panel [#access-the-admin-panel] If you use [Laravel Herd](https://herd.laravel.com) or [Laravel Valet](https://laravel.com/docs/valet), open the login page of your application: ``` http://your-project.test/cpanel/login ``` With `php artisan serve`, the admin panel is at `http://localhost:8000/cpanel/login`. The `/cpanel` prefix can be changed, see the [Configuration](/3.x/configuration) page. On the first login, a setup wizard asks for the store details in three steps: 1. Information: the store name and email, its country, the currencies it sells in and the default currency. 2. Address: the street address, postal code, state, city and phone number of the store. 3. Social Links: the store's social media pages. This step is optional. The admin panel opens once the wizard is saved. Until the store has an email and a street address, every admin page sends you back to the wizard, as described in [Access Requirements](/3.x/dashboard#access-requirements). ## Run the Scheduler and a Queue Worker [#run-the-scheduler-and-a-queue-worker] Shopper registers its own scheduled tasks and sends part of its work to the queue. Without the scheduler, unpaid orders keep their reserved stock and abandoned carts are never deleted. Without a queue worker, order notifications and webhooks are never sent. ### Scheduler [#scheduler] Your application only has to run Laravel's scheduler. In production, add the cron entry given in the [Laravel documentation](https://laravel.com/docs/scheduling#running-the-scheduler): ```bash * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1 ``` In development, run `php artisan schedule:work` in a terminal instead. The scheduler then runs these tasks: | Task | Frequency | What it does | |------|-----------|--------------| | `shopper:orders:reclaim` | Hourly | Cancels the pending orders still unpaid after 24 hours and releases their reserved stock. Orders with an offline payment method are never cancelled. Change the delay with `reclaim_pending_after_hours` in `config/shopper/orders.php`, or set it to `null` to turn the task off | | `shopper:webhooks:redispatch` | Every 15 minutes | Requeues the webhook deliveries that never reached the queue or were lost by a worker that stopped | | `model:prune` | Daily | Deletes successful webhook deliveries after 7 days and the other deliveries after 90 days, then the webhook events older than 90 days that have no delivery left | | `shopper:prune-carts` | Daily | Deletes the carts abandoned for more than 30 days, set by `prune_after_days` in `config/shopper/cart.php` | | `shopper:payments:reconcile --pull` | Every 15 minutes | Applies the payment provider events that arrived before their order existed, queues a check of pending payments with the provider, and settles the refunds still pending with the drivers that can look them up. Set `PAYMENT_RECONCILE_SCHEDULE=false` to turn it off | | `model:prune` | Daily | Deletes the payment provider events older than 90 days, except the authorizations and captures never applied to an order nor marked orphaned | | `shopper:shipments:sync-tracking` | Every 30 minutes | Queues a tracking refresh for every shipment with a tracking number that is neither delivered nor returned, when its carrier supports tracking and sends no tracking webhooks. Set `SHIPPING_TRACKING_SYNC=false` to turn it off | ### Queue Worker [#queue-worker] Shopper queues the work that should not slow down a request: order notifications, product imports, product image downloads, collection syncs, discount assignments, stock restores and webhook deliveries. Webhooks go to their own `webhooks` queue and the admin notifications to a `notifications` queue, so the worker listens to both as well as the default queue: ```bash php artisan queue:work --queue=default,webhooks,notifications ``` Change the name of the webhook queue with `SHOPPER_WEBHOOKS_QUEUE`. In production, keep the worker running with Supervisor or Laravel Horizon, as the [Laravel queue documentation](https://laravel.com/docs/queues#supervisor-configuration) explains. ## Install the Store API [#install-the-store-api] A storefront rendered by your Laravel application reads the Shopper models directly and does not need this step. For a storefront that runs elsewhere, such as Next.js, Nuxt or a mobile app, install the Store API: ```bash composer require shopper/api:"^3.0" php artisan shopper:api:install ``` The command publishes the Laravel Sanctum migrations and the Shopper configuration, offers to add Sanctum's `HasApiTokens` trait to your `User` model, and asks whether to run the migrations. When it finishes, it prints the next steps, from the `X-Shopper-Zone` header your storefront sends to the installation of the JavaScript SDK. The API is served under `/store`. The package also adds a daily `sanctum:prune-expired --hours=24` task to the scheduler, which deletes the customer tokens expired for more than 24 hours. The [Store API](/3.x/store-api) guides cover the API in detail. ## Next Steps [#next-steps] Change the admin prefix, swap models, turn off features and add settings pages. The dashboard widgets, the setup guide, and how to change the page. Build the storefront on the Store API or on the Shopper models. # Legal (/3.x/legal) Customers expect a store to publish its terms of use, its privacy policy, and how refunds and shipping work. Shopper keeps these texts as legal pages: each one has a title, a slug and rich text content that the merchant writes in the admin panel and enables when it is ready. Shopper does not render legal pages or register routes for them on your storefront. Your application reads the enabled pages and displays them, from Blade with the model or from any frontend through the Store API. ## Model [#model] Legal pages use the `Shopper\Core\Models\Legal` model. It has no key in `config/shopper/models.php`, so it is always loaded with its own class, as explained in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). The `Shopper\Core\Models\Contracts\Legal` interface it implements declares no method. The model uses the `HasSlug` trait, described in [Slugs](#slugs), and casts `is_enabled` to a boolean. ### Database Schema [#database-schema] Legal pages are stored in the `sh_legals` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `title` | string | no | - | Page title | | `slug` | string | yes | null | URL identifier, unique | | `content` | longtext | yes | null | Page content, HTML from the rich text editor | | `is_enabled` | boolean | no | false | Whether the page is published | | `created_at` | timestamp | yes | null | Creation date | | `updated_at` | timestamp | yes | null | Last update date | The table has no unique index on `title`. The admin form refuses a title that another page already uses. ## Default Legal Pages [#default-legal-pages] The installer seeds four legal pages, through `Shopper\Core\Database\Seeders\LegalsPageTableSeeder`: | Slug | Title | |------|-------| | `refund` | Refund policy | | `privacy` | Privacy policy | | `terms` | Terms of use | | `shipping` | Shipping policy | The titles are translated in the application locale at the time the installer runs. The four pages start enabled and without content: write their content before you link them from the storefront, or disable them until they are ready. ## Slugs [#slugs] The slug identifies a page in your routes and in the Store API. When you assign a slug, `HasSlug` turns it into a URL-safe value with `Str::slug()` and appends `-1`, `-2` and so on when another page already uses it. The trait does not build a slug from the title, so pass one when you create a page. `findBySlug()` returns the page with that slug, enabled or not, and throws a `ModelNotFoundException` when there is none: ```php use Shopper\Core\Models\Legal; $privacy = Legal::findBySlug('privacy'); ``` The admin form keeps the slug when a merchant saves a page, so renaming "Terms of use" to "Terms and conditions" leaves the URL of the page unchanged. ## Enabling a Legal Page [#enabling-a-legal-page] The `is_enabled` column decides whether a page is published. The `enabled` scope keeps the published pages, for a list of links in the footer: ```php use Shopper\Core\Models\Legal; $legalPages = Legal::query() ->enabled() ->orderBy('title') ->get(['title', 'slug']); ``` A disabled page stays in the admin panel, and the Store API leaves it out. To publish a page from code, update the column: ```php use Shopper\Core\Models\Legal; Legal::findBySlug('shipping')->update(['is_enabled' => true]); ``` ## Adding a Legal Page [#adding-a-legal-page] The admin panel edits the existing pages and has no button to create one. Add a page, such as a cookie policy, from a seeder: ```php title="database/seeders/CookiePolicySeeder.php" firstOrCreate( ['slug' => 'cookies'], ['title' => 'Cookie policy', 'is_enabled' => false], ); } } ``` The page appears as a new tab of the Legal settings page. The admin panel reads the label of that tab and the heading of its form from the translation key `shopper::pages/settings/global.legal.{slug}`. Add the key to your application's translations so the tab reads "Cookie policy": ```php title="lang/vendor/shopper/en/pages/settings/global.php" [ 'cookies' => 'Cookie policy', ], ]; ``` Laravel merges this file with the translations of the package, so the other keys keep their values. ## Retrieve Data [#retrieve-data] A storefront route loads an enabled page by its slug. Querying with the `enabled` scope and `firstOrFail()` answers with a 404 for a disabled page or an unknown slug: ```php title="app/Http/Controllers/LegalController.php" enabled() ->where('slug', $slug) ->firstOrFail(); return view('legal.show', ['legal' => $legal]); } } ``` ### Routes [#routes] One route serves every legal page. The controller already rejects the slugs that are not published, so the route needs no constraint: ```php title="routes/web.php" use App\Http\Controllers\LegalController; use Illuminate\Support\Facades\Route; Route::get('/legal/{slug}', [LegalController::class, 'show'])->name('legal.show'); ``` Link to a page by its slug, for example `route('legal.show', 'privacy')` for the privacy policy. ### Views [#views] The content is the HTML the merchant wrote in the rich text editor. Sanitize it before you print it unescaped, for example with the `sanitizeHtml()` string method that Filament registers: ```blade title="resources/views/legal/show.blade.php"

    {{ $legal->title }}

    Last updated on {{ $legal->updated_at->toFormattedDateString() }}

    {!! str($legal->content)->sanitizeHtml() !!}
    ``` The footer links to the enabled pages loaded in [Enabling a Legal Page](#enabling-a-legal-page): ```blade title="resources/views/components/footer.blade.php" ``` ## Events [#events] Shopper dispatches no legal page event of its own. Listen to the Eloquent model events of `Shopper\Core\Models\Legal` instead, for example to clear a cached footer when a merchant saves a page: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Legal; public function boot(): void { Legal::saved(fn () => Cache::forget('storefront.footer')); } ``` ## Permissions [#permissions] The Legal settings page checks the `system.settings` permission when it opens, and the form checks it again when a merchant saves a page. The [System Permissions](/3.x/acl#system-permissions) section lists what `system.settings` gives access to. ## In the Admin [#in-the-admin] Merchants edit legal pages under **Settings**, **Legal**, at `/cpanel/setting/legal`. Each page has its own tab, with its title, an **Enabled** toggle and a rich text editor for the content. The title and the content are required, and saving a page keeps its slug. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the enabled legal pages under the `store` prefix, set by `SHOPPER_API_PREFIX`, without authentication: | Endpoint | Returns | |----------|---------| | `GET /store/legals` | The enabled legal pages, paginated. Filter with `filter[title]` (partial match), sort with `sort=title` or `sort=updated_at` | | `GET /store/legals/{slug}` | One enabled legal page, or a 404 for a disabled page or an unknown slug | A legal page resource has the type `legals` and carries `title`, `slug`, `content` (the stored HTML) and `updated_at` (ISO 8601). Legal pages have no public ID, so the resource `id` is the primary key. The endpoints take no `include`: ```json { "data": { "id": "2", "type": "legals", "attributes": { "title": "Privacy policy", "slug": "privacy", "content": "

    What we collect

    We collect your name, email and shipping address to deliver your orders.

    ", "updated_at": "2026-03-02T10:15:00+00:00" } } } ``` The filter and the sorts come from the `filters()` and `sorts()` methods of `Shopper\Api\Http\Resources\LegalResource`, and [Extending the Allowlists](/3.x/store-api/json-api#extending-the-allowlists) shows how to change them. The JavaScript SDK wraps both endpoints: ```ts import Shopper from '@shopperlabs/shopper-sdk' const sdk = new Shopper({ baseUrl: 'https://example.com' }) const { data: legalPages } = await sdk.store.legal.list({ sort: ['title'] }) const privacy = await sdk.store.legal.retrieve('privacy') ``` The Store API [Store and Regions](/3.x/store-api/store#legal-pages) guide covers the legal page endpoints. # Locations (/3.x/locations) A location is a physical place where you keep stock and ship orders from: a warehouse, a retail store, a fulfillment center or a stockroom. Each location has its own address and its own stock, so a "Classic T-Shirt" can have 50 units in the Paris warehouse and 20 in the Lyon store. When the merchant finishes the [setup wizard](/3.x/setup-store), Shopper creates a default location from the store address. A store that ships from one place never has to create another one. A store that ships from several places adds a location for each, and Shopper draws the stock of each order from them in the priority order the merchant sets, as described in [Allocating Stock Across Locations](#allocating-stock-across-locations). This page covers the locations and the stock they hold. Reading and changing the stock of a product, and the inventory history, are on the [Products](/3.x/products#stock-management) page. ## Model [#model] The model is `Shopper\Core\Models\Inventory`. It implements the `Shopper\Core\Models\Contracts\Inventory` contract, which declares the `country` and `histories` relationships, and it is registered under the `inventory` key of `config/shopper/models.php`, so you can swap it. The `HasPublicId` trait fills `public_id` with a ULID when a location is created, and adds `findByPublicId()` and the `wherePublicId` scope, as described in [Public IDs](/3.x/models#public-ids). The model casts `is_default` to a boolean. ### Extending the Model [#extending-the-model] To add relationships or methods, extend the core class. The core model has no relationship to the stock levels of a location, which is a common addition: ```php title="app/Models/Inventory.php" hasMany(StockLevel::class); } } ``` Then register your class in `config/shopper/models.php`: ```php title="config/shopper/models.php" return [ 'inventory' => App\Models\Inventory::class, ]; ``` Run `php artisan config:cache` in production after the change. The [Models](/3.x/models#swapping-a-model) page explains what follows your class once it is registered. ## Database Schema [#database-schema] Locations are stored in the `sh_inventories` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Location name | | `code` | string | no | - | Identifier code, unique | | `description` | text | yes | null | Location description | | `email` | string | no | - | Contact email, unique | | `street_address` | string | no | - | Street address | | `street_address_plus` | string | yes | null | Additional address line | | `postal_code` | string | no | - | Postal or ZIP code | | `city` | string | no | - | City | | `state` | string | yes | null | State, province or region | | `phone_number` | string | yes | null | Phone number | | `priority` | integer | no | 0 | Allocation order, lower values first | | `latitude` | decimal(11,5) | yes | null | GPS latitude | | `longitude` | decimal(10,5) | yes | null | GPS longitude | | `is_default` | boolean | no | false | Whether this is the default location | | `country_id` | bigint | yes | null | Foreign key to `sh_countries` | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The `country_id` foreign key sets the column to `null` when the country is deleted. ## Relationships [#relationships] A location belongs to a country and has many inventory history rows, one for each stock movement recorded there. ### Country [#country] `country` returns the `Shopper\Core\Models\Country` of the location, or `null` when it has none: ```php $location->country; $location->country?->cca2; ``` ### Inventory Histories [#inventory-histories] Every stock movement of a product or variant is a row of the inventory history, the ledger, tied to the location it happened at. `histories` returns the rows of a location as `Shopper\Core\Models\InventoryHistory` instances. The [Products](/3.x/products#stock-management) page describes the ledger and the methods that write to it. ```php $movements = $location->histories() ->with('stockable') ->latest() ->take(20) ->get(); ``` ## Query Scopes [#query-scopes] The `default` scope keeps the default location. Resolve the model from its contract so that a swapped model is honored: ```php use Shopper\Core\Models\Contracts\Inventory; $defaultLocation = resolve(Inventory::class)::query()->default()->first(); ``` ## Stock Levels [#stock-levels] The stock a product or variant holds at each location is a row of `Shopper\Core\Models\StockLevel`, stored in the `sh_stock_levels` table. The ledger is the record of every movement; the stock level is the current quantity, kept so that reading the stock costs one query whatever the length of the history. Shopper writes the ledger row and updates the stock level in the same database transaction. | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `stockable_type` | string | no | - | Morph alias of the product or variant, such as `product` or `variant` | | `stockable_id` | bigint | no | - | ID of the product or variant | | `quantity` | integer | no | 0 | Current quantity at the location | | `inventory_id` | bigint | yes | null | Foreign key to `sh_inventories` | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A unique index on `stockable_type`, `stockable_id` and `inventory_id` keeps one row per product and location. `stockable` returns the product or variant, and `inventory` returns the location. The model has no contract and no public ID, and it cannot be swapped. Products and variants read their stock levels through the `stockLevels` relation. To show the stock of a product at each location, on a product page that offers in-store pickup for example: ```php $levels = $product->stockLevels() ->with('inventory') ->whereNotNull('inventory_id') ->where('quantity', '>', 0) ->get(); $availability = $levels->mapWithKeys(fn ($level) => [$level->inventory->name => $level->quantity]); ``` Never write to `sh_stock_levels` yourself: change the stock with the methods of the [Products](/3.x/products#modifying-stock) page, which write the ledger and the stock level together. If the two ever disagree, the `shopper:stock:reconcile` command rebuilds the stock levels from the ledger, as described in [Reconciling Stock Levels](#reconciling-stock-levels). ## How Locations Connect to Stock [#how-locations-connect-to-stock] Every method that writes stock takes the ID of a location: `mutateStock()`, `decreaseStock()`, `setStock()` and `clearStock()` on a [product](/3.x/products#modifying-stock) or a [variant](/3.x/product-variants). The movement is recorded at that location (`clearStock()` first erases the stock of every location), and the `stock` attribute of the product returns the sum over every location: ```php use Shopper\Core\Models\Contracts\Inventory; $warehouse = resolve(Inventory::class)::query()->where('code', 'WH-PARIS')->first(); $product->mutateStock( inventoryId: $warehouse->id, quantity: 100, event: 'Shipment received', ); $product->stockInventory($warehouse->id); $product->stock; ``` Shopper has no transfer method. To move stock from one location to another, record the two movements yourself, in one transaction so that a failure leaves both locations as they were: ```php use Illuminate\Support\Facades\DB; DB::transaction(function () use ($product, $warehouse, $lyonStore): void { $product->decreaseStock( inventoryId: $warehouse->id, quantity: 20, event: 'Transfer to Lyon store', userId: auth()->id(), ); $product->mutateStock( inventoryId: $lyonStore->id, quantity: 20, event: 'Transfer from Paris warehouse', userId: auth()->id(), ); }); ``` To load the stock of one location for a whole listing in one query, use `loadStockForInventory()`, described in [Avoiding N+1 Queries](/3.x/products#avoiding-n1-queries). ## Default Location [#default-location] One location at most is the default. When a location is saved with `is_default` set to `true`, Shopper sets `is_default` to `false` on every other location. Nothing requires a default to exist: a store can save its only location with `is_default` set to `false`. The setup wizard creates the default location when the merchant submits it, from the store name, email, street address, postal code, city, phone number and country. Its code is the store name as a slug. The wizard does not copy the state: set it on the location when your carriers need it. Shopper reads the default location in three places: - When the merchant creates a product or a variant in the admin panel with an initial quantity, the quantity is recorded at the default location. With no default location, the product is created without stock. - The product import records the imported quantities at the default location, and ignores them when there is none, as described in [Import](/3.x/import#stock-and-weight). - The Store API uses the default location as the origin address when it asks a carrier for live rates. With no default location, it uses the location with the lowest `priority`. The [Carriers](/3.x/carriers#calculating-shipping-rates) page describes the rate request. Deleting a location deletes its inventory history rows and keeps its stock levels with `inventory_id` set to `null`. Those orphaned rows still count in the `stock` of each product, but no order can draw from them, so a product can show as in stock and fail at checkout. Move the stock to another location before you delete one, or run `php artisan shopper:stock:reconcile --fix` after the deletion to set the orphaned rows to zero. ## Allocating Stock Across Locations [#allocating-stock-across-locations] When a customer places an order, Shopper reserves the stock of each line that tracks inventory, as described in [Stock Reservation](/3.x/cart#stock-reservation). Three services, bound in the container by `Shopper\Core\CoreServiceProvider`, decide which locations the stock comes from: | Contract | Default implementation | Role | |----------|------------------------|------| | `Shopper\Core\Contracts\InventoryResolver` | `Shopper\Core\Stock\DefaultInventoryResolver` | Lists the locations a product can draw from, in order | | `Shopper\Core\Contracts\StockAllocator` | `Shopper\Core\Stock\PriorityStockAllocator` | Splits the quantity over those locations | | `Shopper\Core\Contracts\StockReserver` | `Shopper\Core\Stock\LockingStockReserver` | Locks the product and records the movements | The default resolver returns every location, ordered by `priority` (lowest first), then by ID. It does not look at `is_default`. The allocator then picks the first location in that order that holds the whole quantity. When no single location does, it splits the quantity: it takes what each location holds, in the same order, until the quantity is covered. The reserver locks the product row, asks the allocator for the split, and records one `decreaseStock()` movement per location, with the event "Reserved for order" and the order as reference. When the locations together hold less than the quantity, it records nothing and the order is refused with a `Shopper\Cart\Exceptions\InsufficientStockException`. A product that allows backorders is not refused as long as one location exists: when the stock is short, the reserver draws the whole quantity from the first location of the resolver, whose stock goes negative. The cart itself checks the total stock of a product across every location when a customer adds it, as described in [Stock Validation](/3.x/cart#stock-validation). When an order is cancelled, a queued listener puts each reserved quantity back at the location it was taken from, with the event "Released from cancelled order". Unpaid orders are cancelled the same way when they expire, as described in [Reclaiming Pending Orders](/3.x/orders#reclaiming-pending-orders). ### Custom Inventory Resolver [#custom-inventory-resolver] Replace the resolver to change which locations an order draws from, or in which order. This resolver tries the default location first, then the others by priority: ```php title="app/Stock/DefaultFirstInventoryResolver.php" orderByDesc('is_default') ->orderBy('priority') ->orderBy('id') ->get(); } } ``` Bind it in the `register` method of a service provider of your application. The allocator and the reserver receive the resolver from the container, so they use yours: ```php title="app/Providers/AppServiceProvider.php" use App\Stock\DefaultFirstInventoryResolver; use Shopper\Core\Contracts\InventoryResolver; public function register(): void { $this->app->bind(InventoryResolver::class, DefaultFirstInventoryResolver::class); } ``` The resolver receives the product or variant, so it can also return a different list per product, such as only the locations that ship fragile goods. Bind your own `StockAllocator` the same way to change how the quantity is split. ## Reconciling Stock Levels [#reconciling-stock-levels] The `shopper:stock:reconcile` command compares the stock levels with the sum of the ledger for each product, variant and location, and reports every row that differs: ```bash php artisan shopper:stock:reconcile ``` Each drifted row prints as `[product:12:1] snapshot 40, ledger 38`: the morph alias, the ID of the product or variant, the location ID, the quantity of the stock level and the quantity of the ledger. A stock level whose location was deleted has an empty location ID and reports `ledger 0`. Without `--fix`, the command exits with a failure code when it finds a drifted row, which makes it usable as a check in a scheduled job or a deployment. Add `--fix` to rewrite each drifted stock level from the ledger. Stock levels without any ledger row are set to `0`: ```bash php artisan shopper:stock:reconcile --fix ``` Shopper does not schedule the command. The `shopper:upgrade` command runs it with `--fix` when you upgrade from Shopper 2.x, after the migration that builds the stock levels from the existing ledger, as described in [Upgrade](/3.x/upgrade). ## Configuration [#configuration] Locations have no feature flag. Besides the `inventory` model key described in [Extending the Model](#extending-the-model), their only config key is `Items\LocationSetting::class` in `config/shopper/settings.php`, which removes the entry from the settings screen, as shown in [Settings](/3.x/configuration#settings). The stock services in [Allocating Stock Across Locations](#allocating-stock-across-locations) are plain container bindings, replaced from your own service provider. ### Components [#components] The locations pages and form belong to the settings section of the admin panel. Publish its component file to replace any of them with your own Livewire component: ```bash php artisan shopper:component:publish setting ``` The command creates `config/shopper/components/setting.php`. The location entries are these four: | Key | Group | Default class | |-----|-------|---------------| | `location-index` | `pages` | `Shopper\Livewire\Pages\Settings\Locations\Index` | | `location-create` | `pages` | `Shopper\Livewire\Pages\Settings\Locations\Create` | | `location-edit` | `pages` | `Shopper\Livewire\Pages\Settings\Locations\Edit` | | `settings.locations.form` | `components` | `Shopper\Livewire\Components\Settings\Locations\InventoryForm` | The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below resolve the location class from its contract, so they keep working after you swap the model. ### Creating Locations [#creating-locations] The model accepts every column through `create()`. The admin form fills `code` with the name as a slug; in code, pass it yourself: ```php use Shopper\Core\Models\Contracts\Inventory; use Shopper\Core\Models\Country; $france = Country::query()->where('cca2', 'FR')->first(); $warehouse = resolve(Inventory::class)::query()->create([ 'name' => 'Paris Warehouse', 'code' => 'WH-PARIS', 'email' => 'paris@mystore.com', 'street_address' => '15 Rue du Commerce', 'city' => 'Paris', 'postal_code' => '75015', 'country_id' => $france->id, 'priority' => 1, 'latitude' => 48.8466, 'longitude' => 2.2958, ]); ``` `code` and `email` are unique: a second location with the same value fails on the database index. ### Retrieving Locations [#retrieving-locations] Load the locations in the order the default resolver allocates stock from: ```php use Shopper\Core\Models\Contracts\Inventory; $locations = resolve(Inventory::class)::query() ->with('country') ->orderBy('priority') ->orderBy('id') ->get(); ``` To find the location nearest to a customer, among those with coordinates: ```php use Shopper\Core\Models\Contracts\Inventory; $nearest = resolve(Inventory::class)::query() ->whereNotNull('latitude') ->whereNotNull('longitude') ->get() ->sortBy(fn ($location): float => hypot( ((float) $location->longitude - $customerLongitude) * cos(deg2rad($customerLatitude)), (float) $location->latitude - $customerLatitude, )) ->first(); ``` The distance is an approximation that ranks locations correctly within a country or a region. Shopper itself does not use the coordinates. ## Events [#events] Shopper dispatches no location event of its own. Listen to the Eloquent model events instead. They are dispatched under the core class name as well, so a listener registered on `Shopper\Core\Models\Inventory` keeps firing after you swap the model. The [Events](/3.x/events#listening-to-events) page covers listeners and queues. Stock movements at a location dispatch no event either. The restock of a cancelled order runs in `Shopper\Core\Listeners\Orders\RestoreOrderStockListener`, a queued listener of the `OrderCancelled` event. ## Permissions [#permissions] The admin panel checks four permissions of the `inventories` resource: | Permission | Allows | |------------|--------| | `inventories.browse` | Opening the locations page | | `inventories.create` | Opening the form for a new location and saving it | | `inventories.edit` | Editing a location | | `inventories.delete` | Deleting a location | `inventories.read` is seeded with the others, but the admin panel never checks it. Adding or removing stock on the product page requires `products.edit`. The [Access Control](/3.x/acl#access-by-section) page lists the permissions by section. ## In the Admin [#in-the-admin] Merchants manage locations under Settings, Inventories, at `/cpanel/setting/locations`, on a page titled Locations. The page lists each location with its name, a Default badge, its country, city and phone number. The location form has the name, email, description, a Set as default location toggle, the priority and the address, with the country and state. The default location has no delete button in the list. On the product page, the Stock & Inventory section records stock movements at a location chosen by the merchant and filters the history by location. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API does not expose locations: no endpoint lists them, and products return their total stock only. The only use of a location in the Store API is the origin address of live carrier rates. When no location can serve as the origin, because none exists or the chosen one has no street address, the shipping options of a cart carry the warning "Live carrier rates are unavailable: no inventory location can act as the shipment origin." The Store API [Checkout](/3.x/store-api/checkout#empty-lists-and-warnings) guide covers these warnings. # Media (/3.x/media) Shopper stores the images of products, variants, brands, categories, collections and attribute swatches with [Spatie Media Library](https://spatie.be/docs/laravel-medialibrary). Each image is a row of the `media` table attached to its model, a file on a storage disk and a set of resized copies called conversions. The `config/shopper/media.php` file sets the disks, the collection names, the accepted types, the upload sizes and the conversions. The core models declare their collections, and the admin models of the `Shopper\Models` namespace register them with Spatie Media Library. Only the admin classes have media methods such as `addMedia()`, `getMedia()` and `getThumbnailUrl()`: read [Core Models and Admin Models](/3.x/models#core-models-and-admin-models) before you swap one of these models. ## Configuration [#configuration] The `shopper:install` command publishes `config/shopper/media.php` with the other Shopper configuration files. It also publishes the migration of the `media` table, and runs `php artisan shopper:link`, which links `public/storage` to the `public` disk and `public/vendor/shopper` to the assets of the admin panel. ### Storage Disk [#storage-disk] The `storage` keys name the two image collections every catalog model has, a gallery that holds several images and a thumbnail that holds one, the disk of the images, and the disk of the files sold with virtual products. ```php title="config/shopper/media.php" 'storage' => [ 'collection_name' => 'uploads', 'thumbnail_collection' => 'thumbnail', 'disk_name' => 'public', 'files_disk' => 'local', ], ``` `disk_name` is any disk of `config/filesystems.php`. To keep the images on Amazon S3, install the `league/flysystem-aws-s3-v3` package, fill the `AWS_*` variables of the `s3` disk, and point Shopper to it: ```php title="config/shopper/media.php" 'disk_name' => 's3', ``` The disk applies to new uploads. Images already stored keep the disk recorded on their `media` row, so move their files and update that column yourself when you change it on a live store. Rename the collections before the first upload for the same reason: Shopper reads images by collection name, and the rows already stored keep the old one. `files_disk` holds the `files` collection of virtual products: the ebooks, font packs and templates that customers download after paying, through the temporary links described in [Downloadable Files](/3.x/products#downloadable-files). Keep it on a disk without public access, such as `local` or a private S3 bucket, never on `public`. The admin panel previews these files through temporary URLs, which the `local` disk serves when its `serve` option is `true`, as in the `config/filesystems.php` that Laravel ships. After you change `files_disk`, move the files already stored with `php artisan shopper:files:secure`. ### Accepts Mime Types [#accepts-mime-types] The `accepts_mime_types` list sets the image formats the gallery and the thumbnail collections accept on products, variants, brands, categories and collections. The admin panel applies the same list to the avatar of a team member and to the logo and cover of the store. ```php title="config/shopper/media.php" 'accepts_mime_types' => [ 'image/jpeg', 'image/png', 'image/webp', 'image/avif', ], ``` The collections refuse any other type, whether the file comes from the admin panel, a [product import](/3.x/import) or your code: Spatie Media Library throws `Spatie\MediaLibrary\MediaCollections\Exceptions\FileUnacceptableForCollection`. Attribute swatches accept the same four formats, from a list of their own that this key does not change. SVG is left out of the default list. An SVG file can embed scripts that run when someone opens the file from your storage URL, which lets a staff account attack the session of an administrator. Only add `image/svg+xml` if you understand and accept that risk. The `accepts_file_types` key lists the formats of the downloadable files of virtual products, described in [Downloadable Files](/3.x/products#downloadable-files). ### Media Filesize [#media-filesize] The `max_size` keys set the largest image the admin panel accepts, in kilobytes: ```php title="config/shopper/media.php" 'max_size' => [ 'thumbnail' => 1024, 'images' => 2048, ], ``` | Key | Default | Upload fields | |-----|---------|---------------| | `thumbnail` | `1024` | Thumbnail of a product or variant, image of a brand, category or collection, attribute swatch | | `images` | `2048` | Gallery of a product or variant | The logo and cover of the store and the avatar of a team member have a fixed limit of 1024 kilobytes. These keys apply to the admin forms only. Files added from your code or by an import are checked against the `max_file_size` key of Spatie Media Library, 10 MB by default. Publish its configuration to change it: ```bash php artisan vendor:publish --tag=medialibrary-config ``` ### Image Conversions [#image-conversions] The `conversions` keys list the resized copies generated for every image. Shopper ships two, `large` (800 by 800) and `medium` (500 by 500): ```php title="config/shopper/media.php" 'conversions' => [ 'large' => [ 'width' => 800, 'height' => 800, ], 'medium' => [ 'width' => 500, 'height' => 500, ], ], ``` Every conversion uses `Fit::Fill` and keeps the format of the original. The image is scaled down to fit inside the box without cropping, then centered on a white canvas of the exact size: a 1200 by 600 photo becomes a 500 by 250 image on a 500 by 500 square for `medium`. A smaller image is never enlarged. Add an entry to get another size, here a `small` copy for product cards: ```php title="config/shopper/media.php" 'conversions' => [ 'large' => ['width' => 800, 'height' => 800], 'medium' => ['width' => 500, 'height' => 500], 'small' => ['width' => 200, 'height' => 200], ], ``` New uploads get the new conversion. Generate it for the images already stored with the command of Spatie Media Library: ```bash php artisan media-library:regenerate --only=small ``` Spatie Media Library queues conversions by default, on the connection of `QUEUE_CONNECTION`. Keep a worker running, as described in [Queue Worker](/3.x/installation#queue-worker): until the job runs, the conversion does not exist and the helpers below return the original image. Conversions use GD unless you set `IMAGE_DRIVER=imagick`, as the [PHP Extensions](/3.x/requirements#php-extensions) section explains. ## Media Collections [#media-collections] Each model declares its collections in `getMediaCollections()`, which returns `Shopper\Core\Media\MediaCollectionConfig` objects keyed by collection name. The admin model registers each one with Spatie Media Library, with its disk, its accepted types and its fallback URL. | Model | Collection | Name | Images | |-------|------------|------|--------| | Product, ProductVariant, Brand, Category, Collection | Gallery | `shopper.media.storage.collection_name`, `uploads` by default | Several | | Product, ProductVariant, Brand, Category, Collection | Thumbnail | `shopper.media.storage.thumbnail_collection`, `thumbnail` by default | One | | AttributeProduct | Swatch | `swatch` | One | Adding an image to a single-image collection replaces the previous one. Every image of these models gets the conversions of `shopper.media.conversions`. Add images from an upload or from a URL, reading the collection name from the configuration: ```php title="app/Http/Controllers/BrandLogoController.php" validate([ 'logo' => ['required', 'image', 'mimetypes:'.implode(',', config('shopper.media.accepts_mime_types'))], ]); $brand = resolve(Brand::class)::query()->findOrFail($brandId); $brand->addMedia($request->file('logo')) ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); return back(); } } ``` From a URL, `addMediaFromUrl()` downloads the image and adds it to the gallery of the product: ```php $product->addMediaFromUrl('https://cdn.example.com/classic-t-shirt-back.jpg') ->toMediaCollection(config('shopper.media.storage.collection_name')); ``` ## Retrieving Images [#retrieving-images] The admin models add two methods. `getThumbnail()` returns the `Media` of the thumbnail collection, or else the first image of the gallery, or `null` when the model has neither. `getThumbnailUrl()` returns the URL of the same image, and the URL of the [placeholder image](#placeholder-image) when there is none. Pass a conversion name to get the resized copy; when that conversion has not been generated yet, it returns the original: ```blade title="resources/views/products/_card.blade.php" {{ $product->name }} ``` For the gallery, read the collection with the methods of Spatie Media Library. `getAvailableUrl()` returns the first generated conversion of the list, or the original: ```blade title="resources/views/products/show.blade.php" @foreach ($product->getMedia(config('shopper.media.storage.collection_name')) as $image) {{ $image->name }} @endforeach ``` `getFirstMediaUrl()` returns the URL of the first image of a collection. On an empty gallery or thumbnail collection, it returns the placeholder image: ```php $bannerUrl = $category->getFirstMediaUrl(config('shopper.media.storage.collection_name'), 'large'); ``` Load the `media` relation with your models to avoid one query per model in a listing: ```php use Shopper\Core\Models\Contracts\Product as ProductContract; $products = resolve(ProductContract::class)::query() ->with('media') ->latest() ->limit(12) ->get(); ``` ## Placeholder Image [#placeholder-image] When a gallery or thumbnail collection is empty, `getThumbnailUrl()` and `getFirstMediaUrl()` return the URL given by the `shopper_fallback_url()` helper: `/vendor/shopper/images/placeholder.jpg` on your application URL. The file ships with the admin panel and is served through the `public/vendor/shopper` link that `php artisan shopper:link` creates. When the placeholder answers 404, run that command again. The placeholder is the same for every model and has no configuration key. To show your own image, test `getThumbnail()`, which returns `null` instead of the placeholder: ```blade title="resources/views/products/_card.blade.php" {{ $product->name }} ``` The swatch collection has no placeholder: `getFirstMediaUrl('swatch')` returns an empty string when the attribute value has no swatch. ## Advanced Customization [#advanced-customization] To add a collection, swap the admin model as described in [Swapping a Model](/3.x/models#swapping-a-model) and merge your collection into `getMediaCollections()`. This product model adds a single-image size guide: ```php title="app/Models/Product.php" new MediaCollectionConfig( name: 'size-guide', disk: config('shopper.media.storage.disk_name'), singleFile: true, acceptsMimeTypes: config('shopper.media.accepts_mime_types'), ), ]); } } ``` `MediaCollectionConfig` takes the collection name, the disk (`public` by default), `singleFile` (`false` by default), the accepted types (an empty array accepts every type) and a fallback URL (none by default). The admin model registers the new collection like the others, and its images get the configured conversions: ```php $product->addMedia($request->file('size_guide'))->toMediaCollection('size-guide'); $sizeGuideUrl = $product->getFirstMediaUrl('size-guide', 'large'); ``` The admin panel shows no field for a collection you add. Add one in your own Livewire component, or publish the component configuration of the product section with `php artisan shopper:component:publish product` as described in [Components](/3.x/configuration#components). ## In the Admin [#in-the-admin] The **Media** page of a product holds the thumbnail and the gallery, and **Choose from images** copies a gallery image into the thumbnail collection. Variants have the same two fields, brands, categories and collections have one image field that fills their thumbnail collection, and the attributes page of a product has a swatch upload for each attribute value. The store logo and cover sit in the general settings, the avatar in the account page. The [user guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The [Store API](/3.x/store-api) returns each image as an object with its `id` (the UUID of the media), `url`, `conversions` (the URL of each conversion already generated, keyed by name), `name`, `extension`, `created_at` and `updated_at`. Products and variants carry `images`, the gallery, and `thumbnail`, which falls back to the first gallery image. Brands, categories and collections carry `thumbnail` only, without that fallback. A model without an image returns `null`: the Store API never sends the placeholder. The `files` of a virtual product are not images and carry no URL, as described in [Downloadable Files](/3.x/products#downloadable-files). ```json { "id": "9d4f6f0e-6a3b-4b8e-9b1e-2f7c1d2a5e10", "url": "https://shop.example.com/storage/42/classic-t-shirt-front.jpg", "conversions": { "large": "https://shop.example.com/storage/42/conversions/classic-t-shirt-front-large.jpg", "medium": "https://shop.example.com/storage/42/conversions/classic-t-shirt-front-medium.jpg" }, "name": "classic-t-shirt-front", "extension": "jpg", "created_at": "2026-03-12T09:41:07+00:00", "updated_at": "2026-03-12T09:41:09+00:00" } ``` # Models and Contracts (/3.x/models) Shopper stores its data with Eloquent models. Most of them live in `shopper/core` under the `Shopper\Core\Models` namespace, the cart and payment packages add their own, and the admin package (`shopper/framework`) extends the catalog models to give them images. Thirteen core models, the cart and its lines can be replaced with a class of your own, and Shopper then loads your class everywhere it uses that model. This page lists the models by domain, explains how swapping works and how Shopper resolves the class to use, and covers what the models share: morph aliases, the public ID and the table prefix. How the packages depend on each other is described in [Architecture and Packages](/3.x/architecture). ## Models by Domain [#models-by-domain] The tables below give each model, its table name without the prefix, and its key in `config/shopper/models.php` when the model can be swapped. Models are in `Shopper\Core\Models` unless the section says otherwise. Each swappable model implements a contract of the same name in `Shopper\Core\Models\Contracts`, such as `Shopper\Core\Models\Contracts\Product`, and the container binds that contract to the configured class. ### Catalog [#catalog] The catalog models hold what the store sells. Seven of them are swappable, and six of those are configured with the admin package's `Shopper\Models` subclasses, described in [Core Models and Admin Models](/3.x/models#core-models-and-admin-models). | Model | Table | `models.php` key | Page | |-------|-------|------------------|------| | `Product` | `products` | `product` | [Products](/3.x/products) | | `ProductVariant` | `product_variants` | `variant` | [Product Variants](/3.x/product-variants) | | `Attribute` | `attributes` | | [Attributes](/3.x/attributes) | | `AttributeValue` | `attribute_values` | | [Attributes](/3.x/attributes) | | `AttributeProduct` | `attribute_product` | `attribute_product` | [Attributes](/3.x/attributes) | | `Brand` | `brands` | `brand` | [Brands](/3.x/brands) | | `Category` | `categories` | `category` | [Categories](/3.x/categories) | | `Collection` | `collections` | `collection` | [Collections](/3.x/collections) | | `CollectionRule` | `collection_rules` | | [Collections](/3.x/collections) | | `ProductTag` | `product_tags` | | [Product Tags](/3.x/product-tags) | | `Price` | `prices` | | [Pricing](/3.x/pricing) | | `Review` | `reviews` | | [Reviews](/3.x/reviews) | | `Supplier` | `suppliers` | `supplier` | [Suppliers](/3.x/suppliers) | | `ProductImport` | `product_imports` | | [Import](/3.x/import) | ### Inventory [#inventory] An inventory is a location that holds stock, such as a warehouse or a shop. Stock movements are recorded in a ledger, and the stock level of each product or variant at each location is kept in its own table. | Model | Table | `models.php` key | Page | |-------|-------|------------------|------| | `Inventory` | `inventories` | `inventory` | [Locations](/3.x/locations) | | `InventoryHistory` | `inventory_histories` | | [Locations](/3.x/locations) | | `StockLevel` | `stock_levels` | | [Locations](/3.x/locations) | ### Orders and Taxes [#orders-and-taxes] An order keeps a copy of everything it needs once the cart is gone: its items, its addresses, its tax lines and its shipments. | Model | Table | `models.php` key | Page | |-------|-------|------------------|------| | `Order` | `orders` | `order` | [Orders](/3.x/orders) | | `OrderItem` | `order_items` | | [Orders](/3.x/orders) | | `OrderAddress` | `order_addresses` | | [Orders](/3.x/orders) | | `OrderRefund` | `order_refunds` | | [Payments](/3.x/payments) | | `OrderShipping` | `order_shipping` | | [Fulfillment](/3.x/fulfillment) | | `OrderShippingEvent` | `order_shipping_events` | | [Fulfillment](/3.x/fulfillment) | | `OrderTaxLine` | `order_tax_lines` | | [Taxes](/3.x/taxes) | | `TaxZone` | `tax_zones` | `tax_zone` | [Taxes](/3.x/taxes) | | `TaxRate` | `tax_rates` | `tax_rate` | [Taxes](/3.x/taxes) | | `TaxRateRule` | `tax_rate_rules` | | [Taxes](/3.x/taxes) | | `TaxProvider` | `tax_providers` | | [Taxes](/3.x/taxes) | ### Discounts and Campaigns [#discounts-and-campaigns] Discounts hold the promotion rules, `DiscountDetail` links a discount to the products or customers it applies to, and `OrderPromotion` records the promotions applied to an order. | Model | Table | `models.php` key | Page | |-------|-------|------------------|------| | `Discount` | `discounts` | | [Discounts](/3.x/discounts) | | `DiscountDetail` | `discountables` | | [Discounts](/3.x/discounts) | | `OrderPromotion` | `order_promotions` | | [Discounts](/3.x/discounts) | | `Campaign` | `campaigns` | | [Campaigns](/3.x/campaigns) | | `CampaignBudgetMovement` | `campaign_budget_movements` | | [Campaigns](/3.x/campaigns) | ### Cart and Payments [#cart-and-payments] The cart models are in `Shopper\Cart\Models` (`shopper/cart`) and the payment models in `Shopper\Payment\Models` (`shopper/payment`). The cart and its lines are swapped in `config/shopper/cart.php`, under the `models` key, and their contracts are `Shopper\Cart\Models\Contracts\Cart` and `Shopper\Cart\Models\Contracts\CartLine`. | Model | Table | `cart.php` key | Page | |-------|-------|----------------|------| | `Cart` | `carts` | `models.cart` | [Cart](/3.x/cart) | | `CartLine` | `cart_lines` | `models.cart_line` | [Cart](/3.x/cart) | | `CartAddress` | `cart_addresses` | | [Cart](/3.x/cart) | | `CartLineAdjustment` | `cart_line_adjustments` | | [Cart](/3.x/cart) | | `CartLineTaxLine` | `cart_line_tax_lines` | | [Cart](/3.x/cart) | | `CartPromotion` | `cart_promotions` | | [Cart](/3.x/cart) | | `PaymentTransaction` | `payment_transactions` | | [Payments](/3.x/payments) | | `PaymentWebhookEvent` | `payment_webhook_events` | | [Payments](/3.x/payments) | ### Customers and Store Setup [#customers-and-store-setup] Customers and team members are rows of your application's `users` table: Shopper does not ship a user model. Your `User` model uses the `Shopper\Traits\InteractsWithShopper` trait, as shown in [Installation](/3.x/installation), and roles and permissions use `Shopper\Models\Role` and `Shopper\Models\Permission`, which extend the Spatie permission models (see [Permissions](/3.x/acl)). The other models of this group describe the store itself. | Model | Table | `models.php` key | Page | |-------|-------|------------------|------| | `Address` | `user_addresses` | `address` | [Customers](/3.x/customers) | | `Geolocation` | `users_geolocation_history` | | [Customers](/3.x/customers) | | `Channel` | `channels` | `channel` | [Channels](/3.x/channels) | | `Zone` | `zones` | | [Zones](/3.x/zones) | | `Country` | `countries` | | [Zones](/3.x/zones) | | `Currency` | `currencies` | | [Currencies](/3.x/currencies) | | `Carrier` | `carriers` | | [Carriers](/3.x/carriers) | | `CarrierOption` | `carrier_options` | | [Carriers](/3.x/carriers) | | `PaymentMethod` | `payment_methods` | | [Payment Methods](/3.x/payment-methods) | | `Legal` | `legals` | | [Legal](/3.x/legal) | | `Setting` | `settings` | | [Settings](/3.x/settings) | | `WebhookSubscription` | `webhook_subscriptions` | | [Webhooks](/3.x/webhooks) | | `WebhookEvent` | `webhook_events` | | [Webhooks](/3.x/webhooks) | | `WebhookDelivery` | `webhook_deliveries` | | [Webhooks](/3.x/webhooks) | ## Core Models and Admin Models [#core-models-and-admin-models] The admin package ships six subclasses in the `Shopper\Models` namespace: `Product`, `ProductVariant`, `Brand`, `Category`, `Collection` and `AttributeProduct`. Each one extends the core class of the same name and implements Spatie Media Library's `HasMedia` interface, which adds the media collections and image conversions configured in `config/shopper/media.php`, and helpers such as `getThumbnailUrl()`. These are the classes `config/shopper/models.php` lists for those six keys. The seven other keys list a core class, because those models have no media. When you swap a model, extend the class `config/shopper/models.php` lists for its key: `Shopper\Models\Product` for `product`, `Shopper\Core\Models\Order` for `order`. The admin panel calls the media methods on catalog models, for example `getThumbnailUrl()` in the product pickers, so a product class that extends `Shopper\Core\Models\Product` breaks those screens. Shopper also checks the class when one of its models boots. If the configured class does not extend the Shopper class being booted, it throws a `Shopper\Core\Exceptions\InvalidModelConfigurationException` with a message such as `[App\Models\Product] must extend [Shopper\Core\Models\Product]`. Shopper's code names the core classes, so the check compares your class with the core class and does not catch a product class that extends `Shopper\Core\Models\Product` instead of `Shopper\Models\Product`. ## Swapping a Model [#swapping-a-model] Swap a model when you need your own methods, scopes, relationships or casts on it. Your class extends the Shopper class, so it keeps every column, relationship and behavior of the original. This product model adds a scope for the products the merchant marks as featured, and a relationship to a wishlist model of the application: ```php title="app/Models/Product.php" where('featured', true); } public function wishlistItems(): HasMany { return $this->hasMany(WishlistItem::class, 'product_id'); } } ``` Point the `product` key to your class: ```php title="config/shopper/models.php" 'product' => App\Models\Product::class, ``` Shopper reads the configured classes when the application boots. If you cache your configuration, run `php artisan config:cache` again after the change. Your scope and relationship are then available on every product Shopper loads, including the ones the admin panel and the Store API return: ```php use App\Models\Product; $featured = Product::query() ->featured() ->publish() ->latest('published_at') ->take(8) ->get(); ``` The Shopper models declare their casts in a `casts()` method. When you override it to cast a column you added, merge the parent casts with `array_merge(parent::casts(), [...])`, or the Shopper columns lose theirs. ### What Uses Your Class [#what-uses-your-class] Once a class is registered, Shopper uses it wherever it loads that model: - The container binds the contract, here `Shopper\Core\Models\Contracts\Product`, to your class. The admin panel, the Store API and the cart resolve models through these contracts. - Static calls on the Shopper class are forwarded to your class: `Shopper\Core\Models\Product::query()`, `::where()`, `::find()` and `::create()` return `App\Models\Product` instances. A model built with `new Shopper\Core\Models\Product` stays a Shopper instance, so create records with `create()` or with your own class. - Relationships read the class from the configuration: `$variant->product` and `$category->products` return instances of your class. - The morph map points the `product` alias to your class, so polymorphic relations such as order items and stock levels load it too. - The admin pages bind their route parameters to your class: the product edit page receives an `App\Models\Product`. - Shopper's observers are registered on your class, and the model events of your class are dispatched a second time under the core class name, such as `eloquent.created: Shopper\Core\Models\Product`. Listeners registered on the Shopper model keep firing after the swap. ### Swapping the Cart Models [#swapping-the-cart-models] The cart and its lines follow the same rules with their own configuration file. Extend `Shopper\Cart\Models\Cart` or `Shopper\Cart\Models\CartLine` and register the class under `models` in `config/shopper/cart.php`: ```php title="config/shopper/cart.php" 'models' => [ 'cart' => App\Models\Cart::class, 'cart_line' => Shopper\Cart\Models\CartLine::class, ], ``` ### Models You Cannot Swap [#models-you-cannot-swap] A model without a configuration key is always loaded with its own class: `$product->tags` returns `Shopper\Core\Models\ProductTag` instances and `$order->items` returns `Shopper\Core\Models\OrderItem` instances. To add a relationship to one of these models, register it from a service provider with Eloquent's `resolveRelationUsing()` method: ```php title="app/Providers/AppServiceProvider.php" use App\Models\GiftMessage; use Shopper\Core\Models\OrderItem; public function boot(): void { OrderItem::resolveRelationUsing('giftMessage', function (OrderItem $orderItem) { return $orderItem->hasOne(GiftMessage::class, 'order_item_id'); }); } ``` ## Resolving Models in Your Code [#resolving-models-in-your-code] In your application, use your own class directly. Code that must work whatever the configuration, such as a package, an add-on or a shared action, resolves the class from the contract or from the configuration instead of naming one. The Store API loads a product by its slug this way: ```php use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query() ->publish() ->where('slug', 'classic-t-shirt') ->firstOrFail(); ``` A relationship from one of your models to a swappable Shopper model reads the class from `config('shopper.models.*')`, as Shopper's own relationships do: ```php title="app/Models/WishlistItem.php" use Illuminate\Database\Eloquent\Relations\BelongsTo; public function product(): BelongsTo { return $this->belongsTo(config('shopper.models.product'), 'product_id'); } ``` ### Route Model Binding [#route-model-binding] Laravel binds a route parameter only when the controller type-hints an Eloquent model. The Shopper contracts are interfaces Laravel does not bind: type-hint one and the container injects an empty model instead of the one in the URL. Type-hint your class, or the Shopper class, which looks the record up through the configured class: ```php title="app/Http/Controllers/ProductController.php" use App\Models\Product; use Illuminate\View\View; public function show(Product $product): View { return view('products.show', ['product' => $product]); } ``` With a route such as `Route::get('/products/{product:slug}', [ProductController::class, 'show'])`, `/products/classic-t-shirt` loads the Classic T-Shirt. ## Morph Map [#morph-map] Polymorphic columns, such as `product_type` on order items or `priceable_type` on prices, store a short alias instead of a class name. Shopper registers these aliases with `Relation::morphMap()`. The aliases of the swappable models point to the configured class, so swapping a model changes the class Eloquent loads without changing a single stored row. | Alias | Model | |-------|-------| | `address`, `brand`, `category`, `collection`, `product`, `variant`, `attribute_product`, `channel`, `order`, `inventory`, `supplier`, `tax_zone`, `tax_rate` | The class configured for the `models.php` key of the same name | | `product_tag` | `Shopper\Core\Models\ProductTag` | | `country` | `Shopper\Core\Models\Country` | | `carrier` | `Shopper\Core\Models\Carrier` | | `carrier_option` | `Shopper\Core\Models\CarrierOption` | | `payment_method` | `Shopper\Core\Models\PaymentMethod` | An order item that sells a variant stores `variant` in `product_type`, and `$item->product` returns an instance of the class configured for the `variant` key. Compare morph types with the alias that `getMorphClass()` returns, never with a class name: ```php use Shopper\Core\Models\Contracts\ProductVariant; $variantItems = $order->items ->where('product_type', resolve(ProductVariant::class)->getMorphClass()); ``` Shopper does not enforce a morph map. Models without an alias, such as `OrderItem`, `OrderShipping`, the cart or your `User` model, are stored with their class name. If your application calls `Relation::enforceMorphMap()`, add an alias for each of them, or Laravel throws a `ClassMorphViolationException` when Shopper writes one to a polymorphic column. ## Public IDs [#public-ids] Most Shopper tables have a `public_id` column next to the auto-increment `id`. It holds a ULID, a 26-character identifier that sorts by creation time, filled by the `Shopper\Core\Models\Traits\HasPublicId` trait when the row is created. A copy made with `replicate()` gets a new one. Use the public ID wherever an identifier leaves your application, in a URL, an email or a payment provider's metadata: it cannot be guessed from another one, and it does not reveal how many orders the store has taken. The Store API returns `public_id` as the `id` of every resource that has one, and outgoing webhooks send it as `resource.id`. Foreign keys between Shopper tables keep using `id`. To find a record by its public ID, use `findByPublicId()` or the `wherePublicId` scope: ```php use Shopper\Core\Models\Order; $order = Order::findByPublicId('01JZ8Q4V6S3W9D2M7K5T1B8XNC'); $orders = Order::query() ->wherePublicId('01JZ8Q4V6S3W9D2M7K5T1B8XNC') ->with('items') ->get(); ``` Every model in the tables above has a public ID except the line and ledger rows, the tax setup and a few internal tables: `AttributeProduct`, `AttributeValue`, `CampaignBudgetMovement`, `CollectionRule`, `DiscountDetail`, `Geolocation`, `InventoryHistory`, `Legal`, `OrderPromotion`, `OrderTaxLine`, `Setting`, `StockLevel`, `TaxProvider`, `TaxRate`, `TaxRateRule`, `TaxZone`, `WebhookSubscription`, `CartLineAdjustment`, `CartLineTaxLine`, `CartPromotion`, `PaymentTransaction` and `PaymentWebhookEvent`. The `InteractsWithShopper` trait gives your `User` model one as well, stored in a `public_id` column Shopper adds to the `users` table. On a store upgraded from 2.x, the migration that adds the column fills it for the existing rows. ## Table Names [#table-names] Every Shopper model builds its table name with the `shopper_table()` helper, which prepends the `table_prefix` of `config/shopper/core.php`. With the default `sh_` prefix, `shopper_table('products')` returns `sh_products`, and the Shopper migrations create their tables the same way. Choosing another prefix is covered in [Configuration](/3.x/configuration#database-table-prefix). Use the helper whenever your own code names a Shopper table, in a migration, a raw query or a validation rule, so that it follows the configured prefix: ```php title="database/migrations/2026_11_16_000000_add_care_instructions_to_products_table.php" text('care_instructions')->nullable(); }); } public function down(): void { Schema::table(shopper_table('products'), function (Blueprint $table) { $table->dropColumn('care_instructions'); }); } }; ``` The pivot tables take the prefix too: `sh_product_has_relations` links products to their categories, collections, channels, tags and related products, and `sh_zone_has_relations` links zones to their countries, carriers, payment methods and collections. Three groups of tables are not prefixed, because they belong to your application or to another package: the `users` table, the role and permission tables named in `config/permission.php`, and the `media` table of Spatie Media Library. # Money (/3.x/money) Every amount Shopper stores, from a product price to an order total, is an integer in cents. This page explains that convention, the columns that hold amounts, how zero-decimal currencies differ, how to format an amount for display and convert a customer's input, and what the Store API returns. Prices per currency, the `HasPrices` trait and the `Price` model are on the [Pricing](/3.x/pricing) page, and the list of currencies a store sells in on [Currencies](/3.x/currencies). ## Amounts in Cents [#amounts-in-cents] Shopper stores an amount as a whole number of cents of its currency. A Classic T-Shirt sold at $29.99 is stored as `2999`, and an order of €1,250.00 as `125000`. Currencies without a minor unit in use, such as the CFA franc or the Japanese yen, are stored in whole units, as described in [Zero-Decimal Currencies](#zero-decimal-currencies). | Displayed price | Currency | Stored value | |-----------------|----------|--------------| | $29.99 | USD | `2999` | | €1,250.00 | EUR | `125000` | | 15,000 FCFA | XAF | `15000` | | ¥1,500 | JPY | `1500` | Integers keep the arithmetic exact. A float cannot hold most decimal prices: in PHP, `0.1 + 0.2` gives `0.30000000000000004` and `19.99 * 100` gives `1998.9999999999998`. With integers, a cart subtotal is the exact sum of its lines, and rounding only happens where a fraction of a cent appears: Shopper rounds each tax amount, each percentage discount and each share of a fixed discount spread over several lines to a whole cent with `round()` when it computes them. The same integers go to the payment provider without conversion. A payment driver receives the amount to charge as an `int` in cents, which is the unit Stripe expects. ## Amount Columns [#amount-columns] Every database column that holds money is an integer column, except the two string columns described after the table. The table names below leave out the `sh_` prefix set by `table_prefix` in `config/shopper/core.php`. | Table | Amount columns | |-------|----------------| | `orders` | `price_amount` (the amount charged), `tax_amount`, `shipping_amount`, `discount_value_at_apply` | | `order_items` | `unit_price_amount`, `discount_amount`, `tax_amount` | | `order_tax_lines` | `amount` | | `order_promotions` | `amount`, `value_at_apply` | | `order_refunds` | `amount` | | `payment_transactions` | `amount` | | `carts` | `shipping_amount` | | `cart_lines` | `unit_price_amount` | | `cart_line_adjustments` | `amount` | | `cart_line_tax_lines` | `amount` | | `cart_promotions` | `computed_amount`, `value` | | `prices` | `amount`, `compare_amount`, `cost_amount` | | `carrier_options` | `price` | | `carriers` | `shipping_amount` | | `discounts` | `value`, `min_required_value` | | `collection_rules` | `value` | | `campaigns` | `budget_amount`, `spent_amount` | | `campaign_budget_movements` | `amount`, `balance_after` | An amount is in the currency of its record: the `currency_code` of an order, a cart or a payment transaction, the `currency` of a refund, the currency of a price, the currency of the zone for a carrier option, and for a discount the currency of its zone, or the store default currency when it has no zone, and for a collection price rule the store default currency. A few columns depend on another value. A discount `value`, and the `value_at_apply` and `discount_value_at_apply` copied on the order, hold cents for a `fixed_amount` discount and a percentage for a `percentage` discount. `discounts.min_required_value` is a string column: it holds cents when the requirement is a minimum purchase amount, and a number of items when it is a minimum quantity. `collection_rules.value` is a string column too: it holds cents for a `product_price` or `compare_at_price` rule. Rates are decimal columns: `order_tax_lines.rate` holds a percentage such as `20.0000`. Totals are computed rather than stored. The `total` attribute of an order item is `unit_price_amount * quantity - discount_amount`, `Order::total()` adds up the item totals, and the totals of a cart come from the cart pipeline described on the [Cart](/3.x/cart) page. ## Formatting Amounts [#formatting-amounts] `shopper_money_format()` turns an amount in cents into a price for display. It divides the amount by 100, except for a zero-decimal currency, and formats it with Laravel's `Number::currency()` in the application locale returned by `app()->getLocale()`. Formatting relies on the `intl` PHP extension listed in the [requirements](/3.x/requirements). ```blade title="resources/views/orders/show.blade.php"

    Total: {{ shopper_money_format($order->price_amount, $order->currency_code) }}

    ``` The second argument is the currency of the amount. Without it, the helper uses the store default currency, which gives a wrong price for an order or a price in another currency: pass the currency code of the record whenever the store sells in more than one currency. The locale decides the symbol, the separators and the position of the currency, and the currency decides the number of decimals: | Call | `en` locale | `fr` locale | |------|-------------|-------------| | `shopper_money_format(2999, 'USD')` | $29.99 | 29,99 $US | | `shopper_money_format(2999, 'EUR')` | €29.99 | 29,99 € | | `shopper_money_format(15000, 'XAF')` | FCFA 15,000 | 15 000 FCFA | | `shopper_money_format(1500, 'JPY')` | ¥1,500 | 1 500 JPY | To hand a price to a view as one value, `Price::from()` returns an object with the `amount` in cents, the `currency` code and the `formatted` string. The currency defaults to the store default currency: ```php title="app/Http/Controllers/OrderController.php" use Shopper\Core\Helpers\Price; $total = Price::from($order->price_amount, $order->currency_code); return view('orders.show', [ 'order' => $order, 'total' => $total, ]); ``` For an order of €58.88, `$total->amount` is `5888`, `$total->currency` is `EUR` and `$total->formatted` is `€58.88` in the `en` locale. ## Default Currency [#default-currency] Merchants choose the store default currency in the setup wizard and change it on the **General** settings page. Shopper keeps the ID of that currency in the `default_currency_id` setting, and `shopper_currency()` returns its ISO code, such as `EUR`, or `USD` when no default currency is set. The code is cached for one hour, as described in [Settings](/3.x/settings#caching). The default currency is the fallback for every amount that comes without a currency: `shopper_money_format()`, `Price::from()`, the admin money fields, a cart created through the Store API without a currency and outside a zone that has one, and the product prices the Store API returns when neither the request nor its zone names a currency. Shopper never converts an amount from one currency to another: each price is set per currency, and an order keeps the currency it was placed in when the default currency changes. ## Zero-Decimal Currencies [#zero-decimal-currencies] Some currencies have no minor unit in everyday use: nobody pays 15,000.50 FCFA. Shopper stores these currencies in whole units, so 15,000 FCFA is stored as `15000`. The `zero_decimal_currencies()` helper returns the list, which is fixed in `shopper/core`: BIF, CLP, DJF, GNF, HTG, JPY, KMF, KRW, MGA, PYG, RWF, VND, VUV, XAF, XAG, XAU, XDR, XOF and XPF. `is_no_division_currency()` tells whether a code is in that list: `is_no_division_currency('XAF')` returns `true` and `is_no_division_currency('EUR')` returns `false`. The comparison is case-sensitive, so pass the code in uppercase, the way Shopper stores it. Every part of Shopper that turns stored amounts into decimals checks this list: `shopper_money_format()`, the admin money field and its validation rules. Your own conversions must check it too, as shown in [Converting Input](#converting-input). Every other currency is stored in cents, including the currencies with three decimals such as the Kuwaiti dinar: 12.34 KWD is stored as `1234` and displayed as KWD 12.340, and an amount like 12.345 KWD cannot be stored. ### Data From Shopper 2.x [#data-from-shopper-2x] Before 2.7, Shopper 2.x multiplied every amount by 100 when saving it, zero-decimal currencies included, so 15,000 FCFA reached the database as `1500000`. Version 2.7 stopped multiplying zero-decimal amounts and added a command that divides the old rows by 100. In 3.x, that command is `shopper:upgrade:fix-zero-decimal-currencies`, and `shopper:upgrade` runs it as step 4 of the [upgrade](/3.x/upgrade). The command divides by 100, with rounding, the amounts in a zero-decimal currency in these tables: `prices` (`amount`, `compare_amount`, `cost_amount`), `orders` (`price_amount`, `tax_amount`), `order_items` (`unit_price_amount`, `tax_amount`, `discount_amount`), `cart_lines`, `cart_line_tax_lines`, `cart_line_adjustments`, the `carrier_options` of zones in such a currency, and the fixed-amount `discounts` of those zones. Run it with `--dry-run` to see how many rows each table would change: ```bash php artisan shopper:upgrade:fix-zero-decimal-currencies --dry-run ``` Once it has run, the command records the `zero_decimal_fix_applied` setting and refuses to run again unless you pass `--force`. `shopper:upgrade` calls the command with `--force`, so it divides again on a store where `zero_decimal_fix_applied` is already set. The command also divides every row in a zero-decimal currency, including rows written by 2.7 or later, which already hold whole units. Back up the database before you upgrade a store that sells in one of these currencies, and compare a few prices and orders in that currency before and after the upgrade. ## Converting Input [#converting-input] A storefront form, an import or an integration receives prices as decimals. Convert a decimal to cents before you save it: multiply by 100 and round, unless the currency is a zero-decimal one. ```php title="app/Http/Controllers/GiftCardController.php" $currency = $request->input('currency_code'); $price = $request->input('price'); $amount = is_no_division_currency($currency) ? (int) $price : (int) round((float) $price * 100); ``` Round before the cast: `(int) (19.99 * 100)` truncates `1998.9999999999998` to `1998` and loses a cent. To fill a form with a stored amount, divide it by 100 unless the currency is a zero-decimal one. ### Admin Forms and Tables [#admin-forms-and-tables] Admin pages and slide-overs you add, as described in [Controllers](/3.x/extending/controllers) and [Slide-overs](/3.x/extending/slideover), get the same conversion from `MoneyInput`, the Filament field behind every price field of the admin panel. It shows the stored cents as a decimal, saves the decimal as cents, masks the input with the separators of the current locale and shows the currency code as a suffix. `currency()` sets the currency of the field, which uses the store default currency without it: ```php title="app/Livewire/Shopper/FreeShippingSettings.php" use Filament\Schemas\Schema; use Shopper\Components\Form\MoneyInput; public function form(Schema $schema): Schema { return $schema ->components([ MoneyInput::make('free_shipping_threshold') ->label('Free shipping from') ->currency(shopper_currency()) ->amountRules() ->required(), ]); } ``` `amountRules()` accepts up to six digits with up to two decimals, or up to nine digits without decimals for a zero-decimal currency. `money(false)` turns off the conversion and the currency suffix; the discount form uses it with a closure so that the same `value` field takes cents for a fixed amount and a percentage otherwise. In a Filament table, the `currency()` macro of `TextColumn` formats a column of cents with `shopper_money_format()`. Pass the currency of the record, or nothing for the store default currency: ```php title="app/Livewire/Shopper/OrdersReport.php" use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Shopper\Core\Models\Contracts\Order; public function table(Table $table): Table { return $table ->query(resolve(Order::class)::query()) ->columns([ TextColumn::make('number'), TextColumn::make('price_amount') ->label('Total') ->currency(fn (Order $record): string => $record->currency_code), ]); } ``` ## Amounts in the Store API [#amounts-in-the-store-api] The Store API returns amounts as they are stored: integers in cents, or whole units for a zero-decimal currency, next to the code of their currency. A cart from `GET /store/carts/{cartId}` carries its totals in the cart currency (attributes shortened): ```json { "data": { "id": "01JD3XQ5Z8K2M4N6P8R0T2V4W6", "type": "carts", "attributes": { "currency_code": "EUR", "subtotal": 5998, "discount_total": 600, "tax_total": 900, "shipping_total": 490, "total": 5888, "tax_inclusive": true } } } ``` A cart takes the `currency_code` sent when it is created, then the currency of the request zone, then the store default currency. These resources return amounts: | Type | Amount attributes | Currency attribute | |------|-------------------|--------------------| | `carts` | `subtotal`, `discount_total`, `tax_total`, `shipping_total`, `total`, `promotions[].amount` | `currency_code` | | `cart-lines` | `unit_price_amount`, `subtotal`, `discount_total`, `tax_total`, `adjustments[].amount`, `tax_lines[].amount` | The cart's | | `orders` | `price_amount`, `total`, `tax_amount`, `shipping_amount` | `currency_code` | | `order-items` | `unit_price_amount`, `total` | The order's | | `order-refunds` | `amount` | `currency` | | `products`, `variants` | `prices[].amount`, `prices[].compare_amount`, `calculated_price`, `price_range` (products only) | `currency_code` of each entry | | `shipping-options` | `amount` | `currency` | | `payment-sessions` | `amount` | `currency_code` | On an order, `price_amount` is the amount charged, with tax and shipping. `total` is the sum of the item totals: it leaves out shipping, and leaves out tax when prices exclude tax. Show `price_amount` as the order total. The `prices` of a product or a variant list its prices in every enabled currency. `calculated_price` and `price_range` use one currency: the `filter[currency]` parameter of the request, then the currency of the request zone, then the store default currency. The [Pricing](/3.x/pricing) page describes these fields, and the Store API [Catalog](/3.x/store-api/catalog#prices-currency-and-stock) guide how a storefront reads them. Webhook payloads carry the same integers. ### Formatting in JavaScript [#formatting-in-javascript] A JavaScript storefront formats amounts with `Intl.NumberFormat`, which follows the same ICU rules as the PHP formatter. The Store API does not say which currencies are zero-decimal ones: `isNoDivisionCurrency()` from `@shopperlabs/shopper-types` holds the same list as `zero_decimal_currencies()`. The SDK re-exports only the types of that package, so add `@shopperlabs/shopper-types` to the storefront to import the function. `GET /store/settings` returns the store `default_currency` and `default_locale`, as shown on the [Settings](/3.x/settings#store-api) page. ```ts title="lib/money.ts" import { isNoDivisionCurrency } from '@shopperlabs/shopper-types' export function formatMoney(amount: number, currency: string, locale: string): string { const value = isNoDivisionCurrency(currency) ? amount : amount / 100 return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value) } ``` `formatMoney(5888, 'EUR', 'fr')` returns `58,88 €`, and `formatMoney(15000, 'XAF', 'fr')` returns `15 000 FCFA`. # Notifications (/3.x/notifications) Shopper sends notifications on two channels. Database notifications appear under a bell in the top bar of the admin panel and tell administrators about new orders, payments, failed payments and finished product imports. Mail notifications go out when an administrator creates a team member or a customer, and when someone asks for a new password. Shopper sends no email to customers about their orders: no order confirmation, no payment receipt, no shipping update. Your application sends them by listening to the order events, as the [order notification example](/3.x/events#example-order-notification-system) shows. ## Database Notifications [#database-notifications] The admin panel builds these notifications with Filament's notifications package and stores them in Laravel's `notifications` table. Four events create one, each through a queued listener of `shopper/framework`: | Event | Fires when | Notification | Button | |-------|------------|--------------|--------| | `Shopper\Core\Events\Orders\OrderCreated` | An order is created | "New order received" | View order | | `Shopper\Core\Events\Orders\OrderPaid` | The payment status of an order becomes paid | "Order paid" | View order | | `Shopper\Payment\Events\PaymentFailed` | The provider declines an authorization, a capture or a refund | "Payment failed", or "Refund failed" for a refund | View order | | `Shopper\Core\Events\Products\ProductImportCompleted` | A product import finishes, with or without row errors | "Product import finished", with the number of imported and failed rows | View products | The body names the order number, for example "Order ORD-20260312-000042 has just been placed." A failed payment shows in red, and an import with row errors in orange. The button opens the order, or the product list for an import, and marks the notification as read. An import that stops before the end, with the `Failed` status, sends no notification. The four listeners live in the `Shopper\Listeners\Notifications` namespace: | Listener | Event | |----------|-------| | `SendNewOrderNotification` | `OrderCreated` | | `SendOrderPaidNotification` | `OrderPaid` | | `SendPaymentFailedNotification` | `PaymentFailed` | | `SendProductImportCompletedNotification` | `ProductImportCompleted` | They implement `ShouldQueue` and run on a queue named `notifications`. The [Events](/3.x/events) page describes the events and their payloads. ### Recipients [#recipients] Every user with the administrator or the manager role receives the notifications: the roles named in `config('shopper.admin.roles.admin')` and `config('shopper.admin.roles.manager')`, `administrator` and `manager` by default. Shopper finds them with the `administrators()` scope of the `InteractsWithShopper` trait on your user model. Customers and team members with any other role receive none, and nothing is stored when no user has one of the two roles. The [Roles](/3.x/acl#roles) section of the ACL page describes these roles. To avoid a role query on every notification, Shopper caches the IDs of these users for two hours under the `shopper.notifications.administrator_ids` cache key. A change of role takes effect when the cache expires. Clear the key to apply it at once: ```bash php artisan cache:forget shopper.notifications.administrator_ids ``` ## Enabling Database Notifications [#enabling-database-notifications] Database notifications are off by default. Turning them on registers the four listeners and adds the bell to the top bar: Set `enabled` to `true` under `notifications.database` in the admin configuration: ```php title="config/shopper/admin.php" 'notifications' => [ 'database' => [ 'enabled' => true, 'polling_interval' => '30s', ], ], ``` Shopper does not ship a migration for Laravel's `notifications` table. Create it if your application does not have it yet: ```bash php artisan make:notifications-table php artisan migrate ``` Your user model needs Laravel's `Illuminate\Notifications\Notifiable` trait. The `User` model of a new Laravel application already uses it. The listeners run on the `notifications` queue. Add it to the queues of your worker, next to the ones listed in [Installation](/3.x/installation#queue-worker): ```bash php artisan queue:work --queue=default,webhooks,notifications ``` ### Polling and Broadcasting [#polling-and-broadcasting] The bell reloads its list every 30 seconds. Change the interval with `polling_interval`, using a duration such as `'60s'` or `'2m'`. Set `polling_interval` to `null` to stop polling. The bell then refreshes through broadcasting only. For each recipient, Shopper's listeners dispatch Filament's `Filament\Notifications\Events\DatabaseNotificationsSent` event, which Laravel broadcasts on the user's private channel, `App.Models.User.{id}` for the `App\Models\User` model, under the name `database-notifications.sent`. The bell listens to it when Laravel Echo is loaded on the page as `window.Echo` and the user already has at least one notification. The admin panel does not load Echo itself. Once broadcasting is set up in your application, as the [Laravel broadcasting documentation](https://laravel.com/docs/broadcasting) explains, add your Echo script to the admin pages with the `BODY_END` render hook: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; public function boot(): void { Shopper::renderHook( LayoutRenderHook::BODY_END, fn (): string => Blade::render("@vite('resources/js/echo.js')"), ); } ``` `resources/js/echo.js` is the file `php artisan install:broadcasting` creates in an application that uses neither React nor Vue. List it in the `input` array of `vite.config.js` so Vite builds it as an entry point. ## Changing the Text [#changing-the-text] The titles, bodies and button labels come from the `notifications.php` translation file of `shopper/framework`, under the `database` key. Shopper ships it in English, French, Spanish and Swedish. To change a text, create the file for your locale in `lang/vendor/shopper` with the keys you want to replace. Laravel merges it with the package file, so the other keys keep their text: ```php title="lang/vendor/shopper/en/notifications.php" [ 'order_created' => [ 'title' => 'New order to pack', 'body' => 'Order :number is waiting in the warehouse queue.', ], ], ]; ``` | Key | Default text | |-----|--------------| | `database.order_created.title`, `.body` | "New order received", "Order :number has just been placed." | | `database.order_paid.title`, `.body` | "Order paid", "Payment for order :number has been received." | | `database.payment_failed.title`, `.body` | "Payment failed", "A payment attempt for order :number has failed." | | `database.refund_failed.title`, `.body` | "Refund failed", "A refund attempt for order :number has failed." | | `database.product_import.title`, `.body` | "Product import finished", ":imported products imported, :failed failed." | | `database.view_order` | "View order" | | `database.view_products` | "View products" | `php artisan shopper:publish` copies every translation file of the package to `lang/vendor/shopper`, if you prefer to start from the full file. ## Adding a Notification [#adding-a-notification] Any listener can notify the same users. `Shopper\Listeners\Notifications\SendsOrderNotification` is the base class of the order listeners: it is queued on the `notifications` queue, finds the administrators and managers, adds the "View order" button and stores the notification. Extend it and call `send()` with a Filament notification and the order. This listener warns the team when a package reaches the Delivery failed status: ```php title="app/Listeners/SendDeliveryFailedNotification.php" namespace App\Listeners; use Filament\Notifications\Notification; use Filament\Support\Icons\Heroicon; use Shopper\Core\Events\Orders\OrderShipmentDeliveryFailed; use Shopper\Listeners\Notifications\SendsOrderNotification; class SendDeliveryFailedNotification extends SendsOrderNotification { public function handle(OrderShipmentDeliveryFailed $event): void { if (! config('shopper.admin.notifications.database.enabled')) { return; } $this->send( Notification::make() ->title('Delivery failed') ->body("A package of order {$event->order->number} could not be delivered.") ->icon(Heroicon::OutlinedTruck) ->danger(), $event->order, ); } } ``` Laravel discovers the listener in `app/Listeners`. Unlike Shopper's listeners, which are only registered when the flag is on, yours always runs: the configuration check keeps it from filling the table while the bell is hidden. For a notification that is not about an order, call `sendToDatabase()` on the Filament notification with the recipients of your choice, such as `User::query()->administrators()->get()`. ## Replacing a Notification [#replacing-a-notification] Laravel resolves a listener from the service container when the event fires, so binding one of Shopper's listener classes to your own class replaces it. Your class receives the same event and runs on the same queue. This one adds the order total to the new order notification, formatted with `shopper_money_format()` as described on the [Money](/3.x/money) page: ```php title="app/Shopper/Listeners/SendNewOrderNotification.php" namespace App\Shopper\Listeners; use Filament\Notifications\Notification; use Filament\Support\Icons\Heroicon; use Shopper\Core\Events\Orders\OrderCreated; use Shopper\Listeners\Notifications\SendsOrderNotification; class SendNewOrderNotification extends SendsOrderNotification { public function handle(OrderCreated $event): void { $order = $event->order; $total = shopper_money_format($order->price_amount, $order->currency_code); $this->send( Notification::make() ->title(__('shopper::notifications.database.order_created.title')) ->body("Order {$order->number} of {$total} has just been placed.") ->icon(Heroicon::OutlinedShoppingBag) ->success(), $order, ); } } ``` Bind it in the `register` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Shopper\Listeners\SendNewOrderNotification; use Shopper\Listeners\Notifications\SendNewOrderNotification as ShopperNewOrderNotification; public function register(): void { $this->app->bind(ShopperNewOrderNotification::class, SendNewOrderNotification::class); } ``` Keep the replacement out of `app/Listeners`. Laravel would discover it there and register it as a second listener of `OrderCreated`, and administrators would receive the notification twice. ## Turning Notifications Off [#turning-notifications-off] `notifications.database.enabled` turns the four database notifications and the bell on or off together. There is no setting for a single notification: to drop one, [replace it](#replacing-a-notification) with a listener that sends something else, or nothing. The two welcome emails described below are only sent when the administrator asks for them in the creation form. The password reset email of the admin panel stops with the reset flow itself: set `password_reset` to `false` in `config/shopper/auth.php` and the login page hides the "Forgot your password?" link and no longer registers the reset routes. ## Mail Notifications [#mail-notifications] Shopper sends three emails from the admin panel, as Laravel notifications in the `Shopper\Notifications` namespace. They go through the `mail` channel with the mailer of `config/mail.php`, during the request: | Notification | Recipient | Sent when | |--------------|-----------|-----------| | `AdminSendCredentials` | The new team member | An administrator creates a team member with **Send Invite** turned on | | `CustomerSendCredentials` | The new customer | An administrator creates a customer with **Send customer credentials** checked | | `AdminResetPassword` | The user who asked for the reset | Someone submits the "Forgot your password?" form of the admin login page | The team member email is titled "Welcome to Shopper" and links to the admin login page. The customer email is titled "Welcome to" followed by `config('app.name')` and links to the home page of the application. The reset email links to the admin page where the user picks a new password. Both options of the creation forms are off by default. Creating team members is covered on the [Team](/3.x/team) page. Their subjects and lines come from the `mails.php` translation file (the two welcome emails) and the `pages/auth.php` file (the reset email) of `shopper/framework`, which you override in `lang/vendor/shopper` as shown in [Changing the Text](#changing-the-text). The layout is Laravel's mail notification template: `php artisan vendor:publish --tag=laravel-notifications` publishes it to `resources/views/vendor/notifications`. ## In the Admin [#in-the-admin] When database notifications are on, the bell in the top bar shows the number of unread notifications, up to "99+", and opens the list. Each notification has its button to the order or the products, and the list marks notifications as read or clears them. The [User Guide](/3.x/user-guide) walks through the admin screens. ## From a Storefront [#from-a-storefront] The Store API does not expose database notifications: they belong to the admin panel. It sends one email of its own. `POST /store/auth/forgot-password` sends Laravel's `Illuminate\Auth\Notifications\ResetPassword` notification to the customer and answers `202`, whether the email exists or not. The link in that email must open the reset page of your storefront. Set it before the storefront shows its "Forgot password" form, in the `boot` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Auth\Notifications\ResetPassword; public function boot(): void { ResetPassword::createUrlUsing(function ($customer, string $token): string { return 'https://shop.example.com/reset-password?' . http_build_query([ 'token' => $token, 'email' => $customer->email, ]); }); } ``` The page then sends the token, the email and the new password to `POST /store/auth/reset-password`. The Store API [Authentication](/3.x/store-api/authentication#resetting-a-password) guide covers the whole reset flow. # Orders (/3.x/orders) An order is the record of a purchase. When a customer checks out, Shopper copies everything the purchase needs into the order: the items with their price at that moment, the shipping and billing addresses, the discounts, the tax lines and the totals, all in [cents](/3.x/money). The order stays correct when the cart is gone, a product is renamed or a price changes. An order carries three statuses: `status` for the order itself (New, Processing, Completed, Cancelled, Archived), `payment_status` for the money and `shipping_status` for the packages. Each order item also has a fulfillment status. The payment and the shipments have their own pages: [Payments](/3.x/payments) and [Fulfillment](/3.x/fulfillment). ## Models [#models] The order is stored by five models of the `Shopper\Core\Models` namespace: | Model | Table | Holds | |-------|-------|-------| | `Order` | `orders` | The order, its statuses, its totals and the snapshot of its main discount | | `OrderItem` | `order_items` | One purchased product or variant, with its name, SKU, quantity and unit price at checkout | | `OrderAddress` | `order_addresses` | A copy of the shipping or billing address | | `OrderPromotion` | `order_promotions` | One discount applied at checkout, see [Discounts](/3.x/discounts) | | `OrderTaxLine` | `order_tax_lines` | One tax applied to an order item, see [Taxes](/3.x/taxes) | Shipments (`OrderShipping` and `OrderShippingEvent`) are described on the [Fulfillment](/3.x/fulfillment) page, refunds (`OrderRefund`) on the [Payments](/3.x/payments) page. The `Order` model implements the `Shopper\Core\Models\Contracts\Order` contract. Its traits change what you can do with an order: - `HasOrderStatusTransitions` adds `canTransitionTo()` and `transitionTo()`, covered in [Order Status](#order-status). - `HasPaymentStatusTransitions` adds `canTransitionPaymentTo()` and `transitionPaymentTo()`, covered in [Payment Status](#payment-status). - `HasPublicId` fills `public_id` with a ULID when the order is created, as described in [Public IDs](/3.x/models#public-ids). Use it in URLs and emails instead of the `id`. - `Searchable` indexes the order for the admin search, as described in [Orders and Customers](/3.x/search#orders-and-customers). - `SoftDeletes`: deleting an order sets `deleted_at` and keeps the row. ### Extending the Model [#extending-the-model] The class configured by default under the `order` key of `config/shopper/models.php` is `Shopper\Core\Models\Order`. To add your own methods, extend it: ```php title="app/Models/Order.php" namespace App\Models; use Shopper\Core\Models\Order as ShopperOrder; class Order extends ShopperOrder { public function hasFreeShipping(): bool { return $this->shipping_amount === 0; } } ``` Then point the configuration to your class: ```php title="config/shopper/models.php" 'order' => App\Models\Order::class, ``` Shopper binds the contract to the configured class, so `resolve(Shopper\Core\Models\Contracts\Order::class)`, `$item->order`, `$customer->orders` and the checkout all return your model. Keep the class name `Order`: the `items`, `shippings` and `refund` relations derive their `order_id` foreign key from it. If your class overrides `booted()`, call `parent::booted()`, which sets the [order number](#order-number-generation). The [Models](/3.x/models#swapping-a-model) page explains how swapping works. `OrderItem`, `OrderAddress`, `OrderPromotion` and `OrderTaxLine` have no configuration key: `$order->items` always returns `Shopper\Core\Models\OrderItem` instances. [Models You Cannot Swap](/3.x/models#models-you-cannot-swap) shows how to add a relation to them. ## Database Schema [#database-schema] The tables use the `sh_` prefix by default, as described in [Database Table Prefix](/3.x/configuration#database-table-prefix). Every amount is an integer in [cents](/3.x/money). ### Order Table [#order-table] The `sh_orders` table has soft deletes: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `number` | string(32) | yes | generated | Order number such as `ORD-20261117-000124`, unique | | `price_amount` | integer | yes | null | Amount charged to the customer, taxes and shipping included | | `tax_amount` | unsigned integer | yes | null | Total tax of the order | | `shipping_amount` | integer | yes | null | Shipping cost | | `status` | string(32) | no | `new` | A `Shopper\Core\Enum\OrderStatus` value, set by the model | | `payment_status` | string(32) | no | `pending` | A `Shopper\Core\Enum\PaymentStatus` value | | `shipping_status` | string(32) | no | `unfulfilled` | A `Shopper\Core\Enum\ShippingStatus` value | | `currency_code` | string | no | - | Currency of every amount of the order | | `email` | string | yes | null | Email the customer gave at checkout, the only contact of a guest order | | `notes` | text | yes | null | Private note written in the admin panel | | `metadata` | jsonb | yes | null | Your own data | | `parent_order_id` | bigint | yes | null | Parent order, see [Parent/Child Orders](#parentchild-orders) | | `payment_method_id` | bigint | yes | null | Payment method chosen at checkout | | `channel_id` | bigint | yes | null | Sales channel of the order | | `customer_id` | bigint | yes | null | Customer, null for a guest order | | `zone_id` | bigint | yes | null | Zone of the customer | | `billing_address_id` | bigint | yes | null | Billing `OrderAddress` | | `shipping_address_id` | bigint | yes | null | Shipping `OrderAddress` | | `shipping_option_id` | bigint | yes | null | Carrier option chosen at checkout | | `discount_id` | bigint | yes | null | Discount with the largest amount, see [Discount](#discount) | | `discount_code` | string | yes | null | Code of that discount | | `discount_type` | string(32) | yes | null | Type of that discount when it was applied | | `discount_value_at_apply` | unsigned integer | yes | null | Value of that discount when it was applied | | `discount_currency_code` | char(3) | yes | null | Currency of the discounts, set when one was applied | | `cancelled_at` | timestamp | yes | null | Set when the order moves to Cancelled | | `archived_at` | timestamp | yes | null | Set when the order moves to Archived | | `created_at` | timestamp | yes | null | Date the order was placed | | `updated_at` | timestamp | yes | null | Last update | | `deleted_at` | timestamp | yes | null | Soft delete date | Every foreign key is set to null when the referenced row is deleted, so deleting a customer or a payment method keeps their orders. The table is indexed on `(status, created_at)` and `(payment_status, currency_code, created_at)` for the admin lists and the reports. The model does not cast `metadata`. To read it as an array, extend the model and add `'metadata' => 'array'` to its casts. ### OrderItem Table [#orderitem-table] The `sh_order_items` table has no soft deletes. Its rows are deleted with their order when the order is force deleted: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | yes | null | Name at checkout, such as "Classic T-Shirt / Blue / L" for a variant | | `sku` | string | yes | null | SKU at checkout, indexed | | `product_type` | string | no | - | Morph type of the product or the variant | | `product_id` | bigint | no | - | ID of the product or the variant | | `quantity` | integer | no | - | Quantity ordered | | `unit_price_amount` | integer | no | - | Unit price at checkout | | `tax_amount` | unsigned integer | no | 0 | Tax of the line | | `discount_amount` | unsigned integer | no | 0 | Discount of the line | | `pricing` | json | yes | null | What a [custom price resolver](/3.x/pricing#custom-price-resolver) returned for the line | | `metadata` | jsonb | yes | null | Metadata copied from the cart line, such as an engraving text | | `order_id` | bigint | no | - | Order | | `fulfillment_status` | string | yes | `pending` | A `Shopper\Core\Enum\FulfillmentStatus` value, set by the model | | `order_shipping_id` | bigint | yes | null | Shipment that carries the item | | `created_at` | timestamp | yes | null | Creation date | | `updated_at` | timestamp | yes | null | Last update | The model casts `pricing` and `metadata` to arrays and `fulfillment_status` to the enum. ### OrderAddress Table [#orderaddress-table] An `OrderAddress` is a copy of the address used at checkout, so editing an address in the customer's book never changes a past order. The `sh_order_addresses` table has no soft deletes: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `customer_id` | bigint | yes | null | Customer, null for a guest order | | `first_name` | string | no | - | First name | | `last_name` | string | no | - | Last name | | `company` | string | yes | null | Company name | | `street_address` | string | no | - | Street and number | | `street_address_plus` | string | yes | null | Apartment, floor, building | | `postal_code` | string | no | - | Postal code | | `city` | string | no | - | City | | `state` | string | yes | null | State or region | | `phone` | string | yes | null | Phone number | | `country_name` | string | yes | null | Country name at checkout | | `created_at` | timestamp | yes | null | Creation date | | `updated_at` | timestamp | yes | null | Last update | The `full_name` attribute joins the first and last names. ### OrderPromotion Table [#orderpromotion-table] The `sh_order_promotions` table keeps one row per discount applied at checkout, with the amount it took off: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `order_id` | bigint | no | - | Order, deleted with it | | `discount_id` | bigint | yes | null | Discount, null once the discount is deleted | | `code` | string | yes | null | Code entered by the customer, null for an automatic discount | | `type` | string(32) | no | - | Type of the discount when it was applied | | `value_at_apply` | unsigned integer | no | - | Value of the discount when it was applied | | `amount` | unsigned integer | no | - | Amount the discount took off the order | | `currency_code` | char(3) | no | - | Currency of the amount | | `created_at` | timestamp | yes | null | Creation date | | `updated_at` | timestamp | yes | null | Last update | ## Relationships [#relationships] The examples on this page use `Shopper\Core\Models\Order`. If you swapped the model, use your own class. ### Customer [#customer] `customer` returns the user who placed the order, an instance of the class set in `auth.providers.users.model`. It is null for a guest order, which keeps the buyer's email in `email`. The `InteractsWithShopper` trait of your `User` model adds the inverse relation: ```php $order->customer?->email; $customer->orders()->latest()->get(); ``` ### Items [#items] `items` returns the order items. Each item points to the product or the variant it was bought from through the polymorphic `product` relation, and its `total` attribute is `unit_price_amount * quantity - discount_amount`: ```php foreach ($order->items as $item) { echo $item->name.' x '.$item->quantity.': '.$item->total; } $item->product; $item->order; ``` ### Addresses [#addresses] `shippingAddress` and `billingAddress` return the `OrderAddress` rows the order points to through `shipping_address_id` and `billing_address_id`. The checkout creates one row for each: ```php $order->shippingAddress?->full_name; $order->billingAddress?->city; ``` ### Shipping [#shipping] `shippings` returns the packages of the order, `shippingOption` the carrier option the customer chose at checkout, and `$item->shipment` the package that carries an item. An order can ship in several packages, as shown in [Partial Shipment (Split Across Packages)](/3.x/fulfillment#partial-shipment-split-across-packages). The [Fulfillment](/3.x/fulfillment) page covers shipments. ### Refund [#refund] `refund` returns the `OrderRefund` of the order, or null. Refunds are described in [Refunding a Payment](/3.x/payments#refunding-a-payment). ### Channel and Zone [#channel-and-zone] `channel` returns the [sales channel](/3.x/channels) the order was placed on, `zone` the zone of the customer, which decided the currency, the carriers and the payment methods, and `paymentMethod` the payment method chosen at checkout: ```php $order->channel?->name; $order->zone?->name; $order->paymentMethod?->title; ``` ### Discount [#discount] An order keeps every discount applied at checkout in `promotions`, one `OrderPromotion` row per discount with the amount it took off. The discount with the largest amount is also copied to the order columns `discount_id`, `discount_code`, `discount_type` and `discount_value_at_apply`, and `discount` returns it. To count the orders that used a discount, count its `OrderPromotion` rows, since `Discount::orders()` only returns the orders where it took the largest amount: ```php use Shopper\Core\Models\OrderPromotion; $order->discount?->code; $order->promotions->sum('amount'); OrderPromotion::query()->where('discount_id', $summerSale->id)->count(); ``` The checkout records each use against the discount's limits and charges the budget of its [campaign](/3.x/campaigns), as described in [Usage Limit Enforcement](/3.x/discounts#usage-limit-enforcement). ### Tax Lines [#tax-lines] Taxes are stored per item: `$item->taxLines` returns the `OrderTaxLine` rows of an item, one per tax rate with its code, name, rate and amount. `tax_amount` on the item and on the order hold the totals. The [Taxes](/3.x/taxes) page covers how they are computed, and [Tax Rates](/3.x/taxes#tax-rates) where the rates come from. ```php $order->load('items.taxLines'); foreach ($order->items as $item) { foreach ($item->taxLines as $taxLine) { echo $taxLine->name.' ('.$taxLine->rate.'%): '.$taxLine->amount; } } ``` ### Parent/Child Orders [#parentchild-orders] `parent` and `children` link orders through `parent_order_id`. Shopper never sets it; use it to split an order, for example one child order per supplier: ```php $order->children; $childOrder->parent; ``` ## Query Scopes [#query-scopes] The Order model has three scopes, and `HasPublicId` adds a fourth: ```php use Shopper\Core\Models\Order; Order::query()->notArchived()->latest()->get(); Order::query()->archived()->get(); Order::query()->awaitingPayment()->get(); Order::query()->wherePublicId('01JZ8Q4V6S3W9D2M7K5T1B8XNC')->first(); ``` `awaitingPayment` returns the New orders whose payment is still Pending, the ones [Reclaiming Pending Orders](#reclaiming-pending-orders) works on. ## Order Total [#order-total] `$order->total()` sums the `total` of the items: unit prices times quantities, minus the line discounts. It leaves out taxes and shipping. The amount the customer paid is `price_amount`, which the checkout sets to the cart total: the subtotal minus the discounts, plus the taxes when the prices exclude tax, plus shipping. ```php $order->total(); $order->price_amount; $order->tax_amount; $order->shipping_amount; ``` Format these amounts with the [Money](/3.x/money) helpers and the order's `currency_code`. ## Order Status [#order-status] A new order starts as New, with a Pending payment and an Unfulfilled shipping status. The model sets these three values when you create an order without a `status`. Each status is a backed enum of the `Shopper\Core\Enum` namespace, and the order and payment statuses refuse a move their enum does not allow. ### Order Status [#order-status-1] The `OrderStatus` enum follows the order from checkout to the end of its life: | Case | Value | Admin label | Can move to | |------|-------|-------------|-------------| | `New` | `new` | New | Processing, Completed, Cancelled, Archived | | `Processing` | `processing` | Processing | Completed, Cancelled, Archived | | `Completed` | `completed` | Completed | Cancelled, Archived | | `Cancelled` | `cancelled` | Cancelled | Archived | | `Archived` | `archived` | Archived | None | `$order->transitionTo()` moves the order and throws `Shopper\Core\Exceptions\InvalidOrderStatusTransitionException` for a move the table does not allow. Moving to Cancelled sets `cancelled_at`, moving to Archived sets `archived_at`. `transitionTo()` dispatches no event: the code that moves the order dispatches the matching one, so your listeners and the webhooks see the change. A customer can cancel an order from their account while it is still waiting for its payment. Release the payment at the provider first, so it can no longer be collected: ```php title="app/Http/Controllers/CancelOrderController.php" use Illuminate\Http\RedirectResponse; use Shopper\Core\Contracts\PaymentSessionGateway; use Shopper\Core\Enum\OrderStatus; use Shopper\Core\Events\Orders\OrderCancelled; use Shopper\Core\Models\Order; public function __invoke(Order $order, PaymentSessionGateway $payments): RedirectResponse { abort_unless($order->customer_id === auth()->id(), 404); if (! $order->isAwaitingPayment() || ! $order->canBeCancelled() || ! $payments->releaseOrder($order)) { return back()->with('error', __('This order can no longer be cancelled.')); } $order->transitionTo(OrderStatus::Cancelled); OrderCancelled::dispatch($order); return back(); } ``` `releaseOrder()` returns false when the payment was, or may have been, collected. Writing `status` with `update()` skips the transition check, the timestamps and the events: use `transitionTo()`. ### Payment Status [#payment-status] The `PaymentStatus` enum follows the money of the order: | Case | Value | Admin label | Can move to | Set by | |------|-------|-------------|-------------|--------| | `Pending` | `pending` | Payment pending | Authorized, Paid, Voided | Every new order | | `Authorized` | `authorized` | Authorized | Paid, Voided | An authorization at the provider | | `Paid` | `paid` | Paid | Partially refunded, Refunded | A capture, a payment webhook, or Mark as paid in the admin panel | | `PartiallyRefunded` | `partially_refunded` | Partially refunded | Partially refunded, Refunded | A refund smaller than the captured amount | | `Refunded` | `refunded` | Refunded | None | Refunds that reach the captured amount | | `Voided` | `voided` | Voided | None | A payment cancelled at the provider | `$order->transitionPaymentTo()` throws `Shopper\Core\Exceptions\InvalidPaymentStatusTransitionException` for a move the table does not allow, and dispatches `OrderPaid` when the new status is Paid. The payment package checks `canTransitionPaymentTo()` first and skips a move it does not allow, because provider webhooks can arrive out of order: a late "captured" never pulls a refunded order back to Paid. `PaymentStatus::revenueBearing()` returns Paid, Partially refunded and Refunded, the statuses that count as revenue. A refund the provider reports as failed is the one move outside the table: Shopper steps a Refunded or Partially refunded payment back to what the remaining refunds give, Paid when none is left, and dispatches `PaymentFailed` but not `OrderPaid`. [Pending Refunds](/3.x/payments#pending-refunds) describes when a provider reports it. Whether a payment is authorized first or captured at once depends on the payment method, as described in [Capture Methods](/3.x/payments#capture-methods). The [Webhooks](/3.x/payments#webhooks) section of the Payments page covers how the provider reports each change. ### Shipping Status [#shipping-status] The `ShippingStatus` enum answers whether the order has shipped. It has no transition table: `Shopper\Core\Actions\SyncOrderShippingStatusAction` computes it from the fulfillment statuses of the items each time a package is picked up, delivered or returned. The first rule that matches wins: | Items | Shipping status | |-------|-----------------| | Every item returned | `Returned` | | Some items returned, all the others shipped or delivered | `PartiallyReturned` | | No item shipped or delivered | `Unfulfilled` | | Every item delivered | `Delivered` | | At least one item delivered | `PartiallyDelivered` | | Every item shipped | `Shipped` | | Otherwise | `PartiallyShipped` | The action dispatches `OrderShipped` when the status becomes Shipped. When your code changes the fulfillment status of items, run the action so the order follows: ```php use Shopper\Core\Actions\SyncOrderShippingStatusAction; (new SyncOrderShippingStatusAction)->execute($order); ``` The carrier events that move the items are described in [Tracking Events](/3.x/fulfillment#tracking-events). ### Status Check Methods [#status-check-methods] The model has a method for each check the admin panel and the storefront need: | Method | True when | |--------|-----------| | `isNew()` | The status is New | | `isProcessing()` | The status is Processing | | `isCompleted()` | The status is Completed | | `isArchived()` | The status is Archived | | `isNotCancelled()` | The status is anything but Cancelled | | `canBeCancelled()` | The status is neither Cancelled nor Archived, and no item was delivered or returned | | `isPaid()` | The payment is Paid | | `allowsDownloads()` | The payment is Paid or Partially refunded | | `isPaymentPending()` | The payment is Pending | | `isPaymentAuthorized()` | The payment is Authorized | | `isAwaitingPayment()` | The status is New and the payment is Pending | | `isRefunded()` | The payment is Refunded | | `isShipped()` | The shipping status is Shipped | | `isShippingPending()` | The shipping status is Unfulfilled | `isPaid()` turns false once a refund is made, since the payment moves to Partially refunded or Refunded. `allowsDownloads()` stays true after a partial refund: the Store API checks it before it lists the files of an order or gives a [download link](/3.x/products#downloadable-files). `canBeCancelled()` does not look at the payment: check `isPaid()` or `isPaymentAuthorized()` as well before you let a customer cancel. ## Order Status Flow [#order-status-flow] Shopper moves the order status in these places. Every other move is up to your code: | Move | Triggered by | Event | |------|--------------|-------| | Created as New | The checkout, or your code | `OrderCreated` | | New to Processing | Start processing or Mark as paid in the admin panel, or the carrier picking up a package | None | | Processing to Completed | Mark complete in the admin panel, or automatically once the order is paid and every item is delivered | `OrderCompleted` | | New or Processing to Cancelled | Cancel Order in the admin panel, or [Reclaiming Pending Orders](#reclaiming-pending-orders) for a New order | `OrderCancelled` | | Any status that allows it to Cancelled | A payment cancellation reported by the payment provider, unless the payment is Paid or `canBeCancelled()` is false | `OrderCancelled` | | New, Processing or Cancelled to Archived | Archive in the admin panel, unless the payment is Paid | `OrderArchived` | The automatic completion runs when the last package of a paid order is delivered, and when an order whose items are all delivered gets paid, through the `OrderPaid` listener Shopper registers. A payment captured through the provider leaves a New order as New until its first package is picked up or someone starts processing it. The admin panel shows each action of the order page only when it applies: | Action | Shown when | Does | |--------|------------|------| | Start processing | The order is New | Moves it to Processing | | Mark as paid | The payment is Pending | Sets the payment to Paid, and moves a New order to Processing | | Capture payment | The payment is Authorized and the order is neither Cancelled nor Archived | Captures the authorization through the payment provider | | Mark complete | The order is Processing and Paid | Moves it to Completed | | Cancel Order | The order can be cancelled (see [Status Check Methods](#status-check-methods)) and is not Completed | Moves it to Cancelled | | Archive | The order is neither Completed, Paid nor Archived | Moves it to Archived and returns to the order list | Cancelling an order changes its status only. The listeners of `OrderCancelled` put the reserved stock back on sale and give the discount amount back to the campaign budget, but a payment that was authorized or collected stays as it is: void or refund it through the payment provider, as described in [Refunding a Payment](/3.x/payments#refunding-a-payment). Archiving an order runs no listener, so cancel an order before you archive it when its stock must return to sale. ## Fulfillment Status [#fulfillment-status] Each order item has a `fulfillment_status`, a `Shopper\Core\Enum\FulfillmentStatus` value. A new item starts as Pending (admin label "Awaiting fulfillment"). The pickup of its package moves it to Shipped, the delivery to Delivered, and a return to Cancelled, which is how a returned item is stored. Forwarded to Supplier and Preparing are there for your own workflow. Shopper checks no transition between item statuses. The [Fulfillment](/3.x/fulfillment) page lists the statuses and the dropshipping workflow. ```php use Shopper\Core\Enum\FulfillmentStatus; $order->items()->where('fulfillment_status', FulfillmentStatus::Pending)->get(); ``` ## Order Number Generation [#order-number-generation] Shopper numbers every order once its row is inserted: a `created` hook on the model calls the global `generate_number()` helper with the order ID and saves the result in `number`. Because the sequence comes from the auto-increment ID, two checkouts that finish at the same time never get the same number, and a unique index on `number` backs it up. With the default configuration, the order with ID 124 placed on November 17, 2026 gets `ORD-20261117-000124`. The prefix, the separator, the date format, the padding and the offset of the sequence are set under `generator` in `config/shopper/orders.php`, described in [Orders](/3.x/configuration#orders) on the Configuration page. To format a number yourself, for an invoice that follows the same scheme, pass the sequence: ```php $invoiceNumber = generate_number($invoice->id); ``` An order created with a `number` keeps it: the hook only fills an empty one. Use this to import the orders of another platform with their original numbers. ## Reclaiming Pending Orders [#reclaiming-pending-orders] The checkout reserves stock for every item when it creates the order, before the payment is confirmed. An order whose payment never lands would hold that stock forever, so the `shopper:orders:reclaim` command cancels unpaid orders after a delay. A failed payment attempt never cancels an order on its own: the customer may still retry with another card. Shopper schedules the command every hour, without overlapping runs, when `reclaim_pending_after_hours` in `config/shopper/orders.php` has a value. The default is 24 hours. Your server must run the Laravel scheduler, as described in [Run the Scheduler and a Queue Worker](/3.x/installation#run-the-scheduler-and-a-queue-worker). ```php title="config/shopper/orders.php" 'reclaim_pending_after_hours' => 24, ``` The command cancels an order when all of these hold: - The order is New and its payment is Pending (the `awaitingPayment` scope). - It was created more than `reclaim_pending_after_hours` hours ago. - Its payment method has a driver other than `manual`. Orders paid offline, by bank transfer or cash on delivery, and orders without a payment method are never reclaimed. - `canBeCancelled()` is true. - The payment provider confirms the payment can no longer be collected. An order whose payment was collected or is still processing is skipped, and so is an order whose provider cannot be reached; the next run tries it again. Each reclaimed order moves to Cancelled and dispatches `OrderCancelled`. Its listeners are queued: a queue worker puts the reserved stock back on sale and gives the discount amounts back to the campaign budgets. Run the command by hand with another delay through `--hours`: ```shell php artisan shopper:orders:reclaim --hours=48 ``` Set `reclaim_pending_after_hours` to `null` to turn the reclaim off. Shopper then leaves the command out of the schedule, and the command does nothing unless you pass `--hours`. ## Configuration [#configuration] Orders have no feature flag: the orders section of the admin panel is always on. The model is swapped through the `order` key of `config/shopper/models.php`, as shown in [Extending the Model](#extending-the-model). `config/shopper/orders.php` holds two settings: | Key | Default | Used for | |-----|---------|----------| | `generator` | prefix `ORD`, separator `-`, date `Ymd`, sequence from 0, padded to 6 digits with `0` | The [order number](#order-number-generation) format | | `reclaim_pending_after_hours` | `24` | The delay before [an unpaid order is reclaimed](#reclaiming-pending-orders), `null` to turn it off | The order pages of the admin panel are Livewire components you can replace. `php artisan shopper:component:publish order` creates `config/shopper/components/order.php`, which lists the pages (`order-index`, `order-detail`, `order-shipments`, `order-abandoned-carts`), the sections of the order page (`order-customer`, `order-fulfillment`, `order-items`, `order-notes`, `order-summary`) and the slide-overs, as described in [Components](/3.x/configuration#components). ## Creating Orders [#creating-orders] Most orders come from a cart at checkout. Creating one by hand is for imports, phone orders or orders coming from a marketplace. ### From a Cart [#from-a-cart] `Shopper\Cart\Actions\CreateOrderFromCartAction` turns a cart into an order in one database transaction: ```php title="app/Http/Controllers/CheckoutController.php" use Illuminate\Http\RedirectResponse; use Shopper\Cart\Actions\CreateOrderFromCartAction; use Shopper\Cart\Facades\Cart; public function store(): RedirectResponse { $cart = Cart::current(); abort_if($cart === null, 404); $order = resolve(CreateOrderFromCartAction::class)->execute($cart); Cart::forget(); return redirect()->route('orders.show', $order->public_id); } ``` The action prices every line again, copies the addresses, creates the items and their tax lines, reserves the stock, records the discounts and marks the cart as completed. Any exception, such as a price that went up or stock that ran out, rolls everything back. The [Order Conversion](/3.x/cart#order-conversion) section of the Cart page lists each step and exception, and [Stock Reservation](/3.x/cart#stock-reservation) explains how the stock is held. ### Complete Order with Items and Addresses [#complete-order-with-items-and-addresses] An order created by hand gets its number and its three statuses from the model. Wrap the inserts in a transaction: `OrderCreated` is dispatched after the transaction commits, so listeners and webhooks see the order with its items. ```php title="app/Actions/CreatePhoneOrder.php" use Illuminate\Support\Facades\DB; use Shopper\Core\Models\Order; use Shopper\Core\Models\OrderAddress; use Shopper\Models\Product; $tshirt = Product::query()->where('slug', 'classic-t-shirt')->firstOrFail(); $order = DB::transaction(function () use ($customer, $tshirt): Order { $address = OrderAddress::query()->create([ 'customer_id' => $customer->id, 'first_name' => 'Amina', 'last_name' => 'Ngono', 'street_address' => '24 Rue Joffre', 'postal_code' => '69002', 'city' => 'Lyon', 'country_name' => 'France', 'phone' => '+33 6 12 34 56 78', ]); $order = Order::query()->create([ 'customer_id' => $customer->id, 'email' => $customer->email, 'currency_code' => 'EUR', 'price_amount' => 5990, 'shipping_amount' => 990, 'shipping_address_id' => $address->id, 'billing_address_id' => $address->id, ]); $order->items()->create([ 'name' => $tshirt->name, 'sku' => $tshirt->sku, 'quantity' => 2, 'unit_price_amount' => 2500, 'product_type' => $tshirt->getMorphClass(), 'product_id' => $tshirt->id, ]); return $order; }); ``` An order created this way reserves no stock, writes no tax lines and records no discount use: the amounts are the ones you pass. To reserve stock, call the `Shopper\Core\Contracts\StockReserver` contract the checkout uses, described in [Stock Reservation](/3.x/cart#stock-reservation). ## Retrieving Orders [#retrieving-orders] A customer's order history reads the `orders` relation of the user, newest first: ```php title="app/Http/Controllers/AccountOrderController.php" use Illuminate\Http\Request; use Illuminate\View\View; public function index(Request $request): View { $orders = $request->user() ->orders() ->with('items') ->latest() ->paginate(10); return view('account.orders.index', ['orders' => $orders]); } ``` Load an order by its public ID in URLs, so a customer cannot guess the next one. Type-hint the Shopper class or yours, as described in [Route Model Binding](/3.x/models#route-model-binding), and check that the order belongs to the signed-in customer: ```php title="routes/web.php" Route::get('/orders/{order:public_id}', [OrderController::class, 'show'])->name('orders.show'); ``` This controller answers `404` when the order belongs to another customer, and loads the items, addresses and shipments the page shows: ```php title="app/Http/Controllers/OrderController.php" use Illuminate\Http\Request; use Illuminate\View\View; use Shopper\Core\Models\Order; public function show(Request $request, Order $order): View { abort_unless($order->customer_id === $request->user()?->id, 404); return view('orders.show', [ 'order' => $order->load(['items.product', 'shippingAddress', 'billingAddress', 'shippings']), ]); } ``` `Order::findByPublicId()` does the same lookup in your own code. Combine the [query scopes](#query-scopes) and the status columns for back-office queries: ```php use Shopper\Core\Enum\PaymentStatus; use Shopper\Core\Enum\ShippingStatus; use Shopper\Core\Models\Order; $toShip = Order::query() ->notArchived() ->where('payment_status', PaymentStatus::Paid) ->where('shipping_status', ShippingStatus::Unfulfilled) ->with(['items', 'shippingAddress']) ->oldest() ->get(); $order = Order::query()->where('number', 'ORD-20261117-000124')->firstOrFail(); ``` ## Events [#events] Order events live in the `Shopper\Core\Events\Orders` namespace. Each one is dispatched after the database transaction commits: | Event | Dispatched by | |-------|---------------| | `OrderCreated` | The model observer, whenever an order row is inserted | | `OrderItemCreated` | The model observer, whenever an order item row is inserted | | `OrderPaid` | `transitionPaymentTo()` when the payment becomes Paid | | `OrderShipped` | `SyncOrderShippingStatusAction` when the shipping status becomes Shipped | | `OrderCompleted` | Mark complete in the admin panel, or the automatic completion | | `OrderCancelled` | Cancel Order in the admin panel, a payment cancellation reported by the provider, or `shopper:orders:reclaim` | | `OrderArchived` | Archive in the admin panel | | `OrderNoteAdded` | Saving the private note of an order in the admin panel | | `OrderDeleted` | The model observer, when an order is deleted | `OrderCreated`, `OrderItemCreated` and `OrderDeleted` come from observers, so your own inserts dispatch them too. The others are dispatched by the code that makes the change: when your code moves an order with `transitionTo()`, dispatch the matching event yourself. Shopper listens to three of them: `OrderCreated` gives the order's customer the customer role, `OrderCancelled` restores the reserved stock and the campaign budget through queued listeners, and `OrderPaid` completes an order whose items are all delivered. The [Events](/3.x/events#order-events) page lists the payloads and the [order lifecycle](/3.x/events#order-lifecycle), the [payment events](/3.x/events#payment-events), the [shipment events](/3.x/events#shipment-events) and the [listeners Shopper registers](/3.x/events#listeners-shopper-registers). `OrderCreated`, `OrderPaid`, `OrderCancelled`, `OrderShipped` and `OrderCompleted` are also sent as the `order.created`, `order.paid`, `order.cancelled`, `order.shipped` and `order.completed` [webhooks](/3.x/webhooks). ## Permissions [#permissions] The admin panel checks these permissions on the order pages: | Permission | Checked for | |------------|-------------| | `orders.browse` | The Orders, Shipments and Abandoned Carts pages, their sidebar entries, and the order widgets of the dashboard | | `orders.read` | The order page and the shipment details | | `orders.edit` | Every action of the order page, the private note, shipping labels and shipment events | `orders.create` and `orders.delete` are seeded and not checked: the admin panel neither creates nor deletes orders. The [Access Control](/3.x/acl#access-by-section) page lists every permission by section. ## In the Admin [#in-the-admin] The **Orders** page lists the orders under the All, Open (New or Processing, not shipped yet), Paid, Fulfilled, Cancelled and Archived tabs, and filters them by number, customer, status, payment status, shipping status and date. The order page shows the items, the summary, the customer and the addresses, the private note and the fulfillment, with the actions of [Order Status Flow](#order-status-flow) and the forms to create shipping labels and record shipment events. The **Shipments** page lists every package, and the **Abandoned Carts** page lists the carts that never became orders. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API places orders and lets customers read them. Orders are returned by their public ID: | Endpoint | Returns | |----------|---------| | `POST /store/carts/{cartId}/complete` | The order placed from the cart: 201 when it is created, 200 with the same order when the cart was already completed | | `GET /store/orders/{orderId}` | One order, for the confirmation page. A customer's order is returned only to that signed-in customer, a guest order to whoever holds its ID. Accepts `include=items` only | | `GET /store/customers/me/orders` | The orders of the signed-in customer, paginated, newest first | | `GET /store/customers/me/orders/{orderId}` | One order of the signed-in customer, or a 404 | | `GET /store/customers/me/orders/{orderId}/items/{itemId}/files/{fileId}` | A temporary download link for a file of a virtual product in a paid order, described in [Downloadable Files](/3.x/products#downloadable-files) | An order resource has the `orders` type and its public ID as `id`. Its attributes are `number`, `status`, `payment_status`, `shipping_status`, `total` (the [order total](#order-total) of the items), `tax_amount`, `shipping_amount`, `price_amount`, `currency_code`, `email` (read it from the account endpoints) and `created_at`. When `GET /store/customers/me/orders/{orderId}` includes `items` and the payment status is Paid or Partially refunded, each item of a virtual product also carries `files`: the `id`, `name`, `extension` and `size` of each file, which the download endpoint above takes. The account endpoints accept the parameters that `OrderResource` declares in its `filters()`, `sorts()` and `includes()` methods. The list accepts all three, a single order accepts `include`: | Parameter | Values | |-----------|--------| | `filter[status]` | An `OrderStatus` value | | `sort` | `created_at` (prefix with `-` for descending) | | `include` | `items`, `shippingAddress`, `billingAddress`, `paymentMethod`, `shippings`, `shippings.events`, `refund` | This request lists the processing orders of the customer, with their items: ```bash curl "https://example.com/store/customers/me/orders?filter[status]=processing&include=items" \ -H "Authorization: Bearer 1|customer-token" ``` The Store API has no endpoint to cancel or change an order: build it in your application, as in [Order Status](#order-status). The Store API [Orders](/3.x/store-api/orders) guide covers the order endpoints. # Payment Methods (/3.x/payment-methods) A payment method is a way customers pay at checkout, as the merchant sets it up: "Credit Card" processed by Stripe, "Bank Transfer" with the store's IBAN in its instructions, "Cash on Delivery" collected by the courier. Each method holds the texts customers read, the zones where it is offered and the payment driver that processes it. The method is the configuration merchants manage. The driver is the code that talks to the payment provider: [Payments](/3.x/payments) describes drivers, payment sessions, captures and refunds. This page covers the model, its availability per zone and how it maps to a driver. ## Model [#model] The model is `Shopper\Core\Models\PaymentMethod`, which implements the `Shopper\Core\Models\Contracts\PaymentMethod` contract. It cannot be swapped through `config/shopper/models.php`; [Models You Cannot Swap](/3.x/models#models-you-cannot-swap) shows how to add a relation to it with `resolveRelationUsing()`. The model uses three traits. `HasPublicId` fills the `public_id` column with a ULID, the identifier the Store API exposes, as described in [Public IDs](/3.x/models#public-ids). `HasSlug` makes the slug you set unique, appending `-1`, `-2` and so on when it is taken, and adds a `findBySlug()` method. It does not build a slug from the title: the admin form copies the title into the slug, code has to set it. `HasZones` adds the `zones()` relation. ## Database Schema [#database-schema] Payment methods are stored in the `sh_payment_methods` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)). Their zones go through the pivot table of zones. ### PaymentMethod Table [#paymentmethod-table] The table has these columns: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `title` | string | no | - | Name customers see, such as "Credit Card" | | `slug` | string | yes | null | URL identifier, unique | | `logo` | string | yes | null | Not read by Shopper: the logo comes from the driver, see [Logo Handling](#logo-handling) | | `link_url` | string | yes | null | Website or documentation of the provider. The Store API does not return it | | `description` | text | yes | null | Shown to customers when they choose a payment method | | `instructions` | text | yes | null | Shown to customers after they place an order | | `is_enabled` | boolean | no | false | Whether carts can offer the method | | `driver` | string | yes | null | Code of the payment driver, such as `stripe`. `null` means `manual` | | `metadata` | jsonb | yes | null | Your own data. The model has no cast for it: write a JSON string and decode it when you read it | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The `driver` column is added by the `shopper/payment` migrations. Orders, carts and payment transactions reference a method through their own `payment_method_id` column, as described in [Orders](#orders). ## Contract [#contract] The contract declares one relation, the zones where the method is offered: ```php namespace Shopper\Core\Models\Contracts; use Illuminate\Database\Eloquent\Relations\MorphToMany; interface PaymentMethod { public function zones(): MorphToMany; } ``` ## Relationships [#relationships] A payment method relates to the zones where it is offered, and to the carts, orders and payment transactions that use it. ### Zones [#zones] A payment method is offered in the zones it is attached to, through the polymorphic pivot described in [Zones](/3.x/zones#pivot-table). When a cart asks for its payment methods, Shopper applies these rules: - A cart in a zone offers the enabled methods attached to that zone whose driver is configured. A method attached to no zone is not offered there. - A cart without a zone offers every enabled method whose driver is configured, attached to a zone or not. A cart gets a zone from the `X-Shopper-Zone` header or from the default zone of the Store API, as described in [Resolving a Zone](/3.x/zones#resolving-a-zone). The Cash on delivery method created by the Shopper seeders is attached to no zone, so carts in a zone do not offer it until you attach it. Moving a cart to another zone clears the payment method it had selected. ```php $creditCard->zones; $creditCard->zones()->syncWithoutDetaching([$europe->id, $northAmerica->id]); $creditCard->zones()->detach($northAmerica->id); ``` The pivot table has no unique index, so `attach()` stores a second row when the method is already in the zone: use `sync()` or `syncWithoutDetaching()`. In the admin panel, the payment methods of a zone are picked in the zone form. ### Orders [#orders] Orders, carts and payment transactions each define a `paymentMethod()` relation. The checkout copies the method of the cart to the order it creates: ```php $cart->paymentMethod; $order->paymentMethod; ``` The payment method defines no inverse relation. Query orders by their foreign key: ```php use Shopper\Core\Models\Order; $orders = Order::query() ->where('payment_method_id', $bankTransfer->id) ->latest() ->get(); ``` The three foreign keys are nullable and set to `null` when the method is deleted, as described in [Deleting Payment Methods](#deleting-payment-methods). ## Query Scopes [#query-scopes] The `enabled` scope keeps the methods whose `is_enabled` flag is set: ```php use Shopper\Core\Models\PaymentMethod; $methods = PaymentMethod::query()->enabled()->get(); ``` ## Logo Handling [#logo-handling] A payment method has no logo of its own: `logo()` returns the logo of its driver. The Stripe driver returns the Stripe logo and the `manual` driver a cash on delivery icon, so a bank transfer and a cash on delivery method show the same icon. Without `shopper/payment` installed, `logo()` returns `null`. ```php $creditCard->logo(); ``` `PaymentProcessingService::getLogoUrl()` returns the same URL. The admin table and the `logo` attribute of the Store API both read it. `logo()` calls the resolver bound to `shopper.payment.logo` in the service container. To give some methods their own logo, bind your resolver in the `boot()` method of a service provider and fall back to the driver logo for the others: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Core\Models\PaymentMethod; use Shopper\Payment\Facades\Payment; public function boot(): void { $this->app->bind('shopper.payment.logo', fn () => fn (PaymentMethod $method): ?string => match ($method->slug) { 'bank-transfer' => asset('images/payments/bank-transfer.svg'), 'mobile-money' => asset('images/payments/mobile-money.svg'), default => Payment::driver($method->driver ?? 'manual')->logo(), }); } ``` ## Payment Drivers [#payment-drivers] The `driver` column holds the code of the payment driver that processes the method. Drivers are registered on the payment manager, behind the `Shopper\Payment\Facades\Payment` facade. `shopper/payment` ships the `manual` driver, used when `driver` is `null`, for payments collected outside Shopper: cash on delivery, bank transfer or a check that the merchant marks as paid. The [Stripe driver](/3.x/payments/stripe) registers the `stripe` driver. ```php use Shopper\Payment\Facades\Payment; Payment::availableDrivers(); Payment::isConfigured('stripe'); Payment::driver($creditCard->driver ?? 'manual')->name(); ``` `availableDrivers()` returns the registered driver codes, such as `['manual', 'stripe']`. `isConfigured()` returns `false` for a driver that lacks its credentials, such as Stripe without its secret key and webhook secret, and for a code no driver is registered under. A cart offers a method only when its driver is configured, so an enabled method whose driver is not configured stays hidden from customers. The admin form lists the registered drivers and marks the ones that are not configured with a "Not configured" badge. For a provider Shopper has no driver for, such as a mobile money aggregator, register your own driver with `Payment::extend()` as described in [Custom Drivers](/3.x/payments#custom-drivers), then set its code in the `driver` column. Keep the driver registered while methods use it: the payment methods page of the admin panel fails to load when a method names a driver that is no longer registered. ## Configuration [#configuration] Payment methods have no feature flag and no key in `config/shopper/models.php`. The settings of the payment package live in `config/shopper/payment.php`, described in [Payments](/3.x/payments). To hide the payment methods page from the settings screen, set `Items\PaymentSetting::class` to `false` in `config/shopper/settings.php`, as shown in [Settings](/3.x/configuration#settings). ### Components [#components] The payment methods page of the admin panel is part of the settings components. To replace it with your own Livewire component, publish the settings component file: ```bash php artisan shopper:component:publish setting ``` The command creates `config/shopper/components/setting.php`. This entry belongs to payment methods: ```php title="config/shopper/components/setting.php" use Shopper\Livewire\Pages; return [ 'pages' => [ 'payment-methods' => Pages\Settings\PaymentMethods::class, ], ]; ``` The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below set up the payment methods of a store that sells in Europe and West Africa. ### Creating Payment Methods [#creating-payment-methods] Create payment methods with Eloquent and set `is_enabled`: the column defaults to `false`, and a disabled method is offered to no cart. #### Basic Payment Method [#basic-payment-method] A card payment processed by Stripe, offered in the European zone: ```php use Shopper\Core\Models\PaymentMethod; use Shopper\Core\Models\Zone; $creditCard = PaymentMethod::query()->create([ 'title' => 'Credit Card', 'slug' => 'credit-card', 'driver' => 'stripe', 'link_url' => 'https://stripe.com', 'description' => 'Pay securely with your credit or debit card.', 'instructions' => 'Your card is charged when your order is confirmed.', 'is_enabled' => true, ]); $creditCard->zones()->sync([Zone::findBySlug('europe')->id]); ``` #### Cash on Delivery [#cash-on-delivery] Offline methods use the `manual` driver. The merchant marks the order as paid once the courier has collected the money: ```php $cod = PaymentMethod::query()->create([ 'title' => 'Cash on Delivery', 'slug' => 'cash-on-delivery', 'driver' => 'manual', 'description' => 'Pay in cash when your order is delivered.', 'instructions' => 'Have the exact amount ready for the courier.', 'is_enabled' => true, ]); ``` #### Bank Transfer [#bank-transfer] The `instructions` text tells customers where to send the money after they place the order: ```php $bankTransfer = PaymentMethod::query()->create([ 'title' => 'Bank Transfer', 'slug' => 'bank-transfer', 'driver' => 'manual', 'description' => 'Pay by direct bank transfer.', 'instructions' => 'Transfer the order total to IBAN FR76 3000 6000 0112 3456 7890 189 and use your order number as the payment reference.', 'is_enabled' => true, ]); ``` #### Zone-Scoped Payment Method [#zone-scoped-payment-method] A method attached to one zone is offered to the carts of that zone only. Mobile money for the West African market, collected manually: ```php $mobileMoney = PaymentMethod::query()->create([ 'title' => 'Mobile Money', 'slug' => 'mobile-money', 'driver' => 'manual', 'description' => 'Pay with Orange Money or MTN Mobile Money.', 'instructions' => 'Send the order total to +225 07 00 00 00 00 with your order number as the reference.', 'is_enabled' => true, ]); $mobileMoney->zones()->sync([Zone::findBySlug('west-africa')->id]); ``` ### Retrieving Payment Methods [#retrieving-payment-methods] To list the enabled methods and to find one by slug: ```php use Shopper\Core\Models\PaymentMethod; $methods = PaymentMethod::query()->enabled()->get(); $creditCard = PaymentMethod::findBySlug('credit-card'); ``` `findBySlug()` throws a `ModelNotFoundException` when no method has the slug. To get the methods a cart in a zone offers, with the rules described in [Zones](#zones), use the payment processing service: ```php use Shopper\Payment\Services\PaymentProcessingService; $methods = resolve(PaymentProcessingService::class)->getMethodsForZone($europe); ``` The methods attached to no zone are offered only to carts without a zone: ```php $unzoned = PaymentMethod::query() ->enabled() ->whereDoesntHave('zones') ->get(); ``` ### Updating Payment Methods [#updating-payment-methods] Update a method like any Eloquent model: ```php $bankTransfer->update([ 'instructions' => 'Transfer the order total to IBAN FR76 3000 6000 0112 3456 7890 189 within 7 days.', ]); $cod->update(['is_enabled' => false]); ``` A disabled method is no longer offered and can no longer be selected for a cart. The orders already placed with it keep it. ### Deleting Payment Methods [#deleting-payment-methods] Deleting a method sets `payment_method_id` to `null` on its orders, carts and payment transactions. Shopper captures, refunds and records provider webhooks through the payment method of the order. Once the method is deleted, its orders can no longer be captured or refunded from Shopper. Disable a method that customers have used instead of deleting it. ### Working with Orders [#working-with-orders] The order keeps the method the customer selected on the cart. Show its title and instructions on the order confirmation page or email. The relation is `null` when the method was deleted: ```php $order->paymentMethod?->title; $order->paymentMethod?->instructions; ``` ### Storefront Example [#storefront-example] A storefront built with Blade, without the Store API, reads and sets the payment method of a cart with Shopper's PHP classes. #### Checkout Payment Selection [#checkout-payment-selection] A Blade storefront lists the methods of the session cart with the same rules as the Store API, then stores the choice with the cart manager. `CartManager::setPaymentMethod()` does not check the zone, so the controller checks that the chosen method is in the list: ```php title="app/Http/Controllers/CheckoutPaymentController.php" namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Collection; use Illuminate\Validation\ValidationException; use Illuminate\View\View; use Shopper\Cart\CartManager; use Shopper\Cart\Facades\Cart; use Shopper\Cart\Models\Cart as ShopperCart; use Shopper\Core\Models\PaymentMethod; use Shopper\Payment\Facades\Payment; use Shopper\Payment\Services\PaymentProcessingService; class CheckoutPaymentController extends Controller { public function __construct( private readonly PaymentProcessingService $payments, private readonly CartManager $carts, ) {} public function edit(): View { $cart = Cart::current() ?? abort(404); return view('checkout.payment', [ 'cart' => $cart, 'paymentMethods' => $this->availableMethods($cart), ]); } public function update(Request $request): RedirectResponse { $cart = Cart::current() ?? abort(404); $method = $this->availableMethods($cart)->firstWhere('public_id', $request->input('payment_method')); if (! $method) { throw ValidationException::withMessages([ 'payment_method' => 'This payment method is not available for your order.', ]); } $this->carts->setPaymentMethod($cart, $method->id); return to_route('checkout.review'); } private function availableMethods(ShopperCart $cart): Collection { if ($cart->zone) { return $this->payments->getMethodsForZone($cart->zone); } return PaymentMethod::query() ->enabled() ->get() ->filter(fn (PaymentMethod $method): bool => Payment::isConfigured($method->driver ?? 'manual')) ->values(); } } ``` ### Use Cases [#use-cases] Common setups and how to build them: | Scenario | Implementation | |----------|----------------| | Card payments | A method with the `stripe` driver from the [Stripe driver](/3.x/payments/stripe) | | Offline payments | A method with the `manual` driver and the payment steps in `instructions` | | Methods per market | Attach each method to the zones where it is sold | | A provider Shopper has no driver for | Register a [custom driver](/3.x/payments#custom-drivers) and set its code in `driver` | | One logo per method | Bind a resolver to `shopper.payment.logo`, see [Logo Handling](#logo-handling) | | Retiring a method | Disable it, keep it for the orders that use it | ## Events [#events] Shopper dispatches no payment method event and registers no observer on the model. Listen to the Eloquent events of `PaymentMethod`, such as `saved` and `deleted`, for your own code. The events of the payment lifecycle, such as `OrderPaid` and `PaymentFailed`, are listed in [Payment Events](/3.x/events#payment-events). ## Permissions [#permissions] The payment methods page checks one permission, `system.settings`, when it opens and on every action: creating, editing, enabling or disabling and deleting a method. The [Access Control](/3.x/acl#system-permissions) page lists the system permissions. ## In the Admin [#in-the-admin] Merchants manage payment methods under Settings, in the Selling group, as Payment methods (`/cpanel/setting/payment-methods`). The table shows the logo, title, driver (gray for `manual`, green for a configured driver, orange otherwise), the live or test mode of the driver, the zones, a status toggle and the date of the last change. The form asks for the title (labeled "Provider"), the driver, a provider documentation URL, the description and the instructions. A new method starts disabled: turn on its status toggle in the table. Zones are not set in this form: the zone form picks the payment methods of each zone. The setup guide of the dashboard marks its payment step as done once an enabled method exists. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API lists the methods a cart offers and sets the method of a cart: | Endpoint | Purpose | |----------|---------| | `GET /store/carts/{cartId}/payment-methods` | The methods the cart offers, with the rules described in [Zones](#zones) | | `POST /store/carts/{cartId}/payment-method` | Sets the method of the cart, by public ID | A payment method resource has the type `payment-methods`, its public ID as `id`, and carries `title`, `slug`, `description`, `instructions`, `driver` and `logo`. To select a method, send its ID as `payment_method_id`: ```bash curl -X POST "https://example.com/store/carts/01JD8Z3K4M5N6P7Q8R9S0T1V2W/payment-method" \ -H "Content-Type: application/json" \ -d '{"payment_method_id": "01JD9A2B3C4D5E6F7G8H9J0K1M"}' ``` The response is the cart. An enabled method the cart does not offer returns a 422 response with the `payment_method_unavailable` code. Switching methods releases the payment session opened for the previous one, and is refused once that session is paid. Carts and orders accept `include=paymentMethod`. The next step of the checkout opens a payment session for the selected method, as described in [Payments](/3.x/payments). The Store API [Checkout](/3.x/store-api/checkout#payment-methods) guide covers the payment method endpoints. # Payments (/3.x/payments) The `shopper/payment` package moves the money of an order through payment drivers. A driver talks to one payment provider: `manual` ships with the package for cash on delivery and bank transfers, the [Stripe driver](/3.x/payments/stripe) adds `stripe`, and your application can register its own. Your code and the Store API call the same methods to initiate, authorize, capture, refund and cancel a payment, whatever the provider. Every operation is recorded as a transaction and moves the payment status of the order. What the provider reports later, through its webhooks or when Shopper asks for the state of a payment, goes through the same code, so a late or repeated event never moves an order backwards. The `PaymentMethod` model that merchants configure, and the zones where each method is offered, are described on [Payment Methods](/3.x/payment-methods). ## How It Works [#how-it-works] The payment system has five pieces: 1. `PaymentManager`, behind the `Payment` facade, resolves a driver by its code (`manual`, `stripe` or your own). 2. `PaymentDriver` is the contract every driver implements. 3. `PaymentProcessingService` calls the driver for an order, records a transaction and moves the payment status. 4. `PaymentTransaction` stores every operation on an order, with its result and the provider reference. 5. `PaymentWebhookEvent` journals the events a provider reports, so that each one is applied once, even when it arrives before its order exists. A storefront built on the Store API opens a [payment session](#payment-sessions) on the cart, lets the customer confirm the payment with the provider, then completes the cart. The provider reports the outcome through its [webhooks](#webhooks). Code that manages orders directly calls the service, as shown in [Processing Payments](#processing-payments). ## Payment Drivers [#payment-drivers] A payment method stores the code of its driver in its `driver` column. A method whose driver is `null` uses `manual`. ### Available Drivers [#available-drivers] Shopper ships one driver and `shopper/stripe` adds a second: | Driver | Package | Code | Description | |--------|---------|------|-------------| | Manual | `shopper/payment` | `manual` | No provider API. For cash on delivery, bank transfers and other offline payments | | [Stripe](/3.x/payments/stripe) | `shopper/stripe` | `stripe` | Stripe PaymentIntents with 3D Secure | ### Using the Facade [#using-the-facade] The `Shopper\Payment\Facades\Payment` facade resolves drivers and tells which ones are registered and configured: ```php use Shopper\Payment\Facades\Payment; $driver = Payment::driver('stripe'); $driver->code(); $driver->name(); $driver->logo(); $driver->mode(); $driver->isConfigured(); Payment::driver(); Payment::availableDrivers(); Payment::isConfigured('stripe'); Payment::configuredDrivers(); ``` `Payment::driver()` without an argument returns the `manual` driver, and an unknown code throws an `InvalidArgumentException`. `availableDrivers()` returns the codes of `manual` and of every driver registered with `Payment::extend()`. `isConfigured()` returns `false` for an unknown code instead of throwing. `configuredDrivers()` returns a collection of driver instances keyed by code: `manual`, plus each driver whose `shopper.{code}.enabled` config value is true, such as `PAYMENT_STRIPE_ENABLED` for Stripe. Shopper itself never calls `configuredDrivers()`, so the `enabled` key neither shows nor hides a driver in the admin panel or at checkout: a cart offers the [payment methods](/3.x/payment-methods) the merchant enabled whose driver is configured. ### The PaymentDriver Contract [#the-paymentdriver-contract] Every driver implements `Shopper\Payment\Contracts\PaymentDriver`. Amounts are integers [in cents](/3.x/money), and every payment method returns a `PaymentResult`: | Method | Returns | Description | |--------|---------|-------------| | `code()` | `string` | Unique driver code, such as `stripe` | | `name()` | `string` | Name shown in the admin panel | | `logo()` | `?string` | Logo URL, or `null` | | `isConfigured()` | `bool` | Whether the credentials are set | | `mode()` | `?PaymentMode` | `PaymentMode::Live` or `PaymentMode::Test` (`Shopper\Payment\Enum\PaymentMode`), or `null` when the driver has no such notion | | `supportsWebhooks()` | `bool` | Whether the provider sends webhooks | | `supportsRefunds()` | `bool` | Whether the provider can refund | | `supportsRetrieval()` | `bool` | Whether Shopper can ask the provider for the current state of a payment | | `initiatePayment(int $amount, string $currency, array $context = [])` | `PaymentResult` | Create a payment with the provider | | `authorizePayment(string $reference, array $data = [])` | `PaymentResult` | Authorize an initiated payment | | `capturePayment(string $reference, ?int $amount = null)` | `PaymentResult` | Capture an authorized payment, in full or in part | | `refundPayment(string $reference, int $amount, ?string $reason = null, array $context = [])` | `PaymentResult` | Refund a captured payment, in full or in part | | `cancelPayment(string $reference)` | `PaymentResult` | Cancel a payment that is not captured | | `retrievePayment(string $reference)` | `PaymentResult` | Read the current state of a payment | | `handleWebhook(array $payload, array $headers = [])` | `WebhookResult` | Turn a provider webhook into a `WebhookResult` | The abstract class `Shopper\Payment\Drivers\Driver` implements the contract with defaults: no logo, no mode, webhooks and refunds supported, retrieval not supported, and every operation except `initiatePayment()` throwing a `PaymentException` that says the driver does not support it. A driver that extends it implements `code()`, `name()`, `isConfigured()` and `initiatePayment()`, then overrides what its provider offers. A driver whose provider can read a refund by its ID can also implement `Shopper\Payment\Contracts\RetrievesRefunds`. Its one method, `retrieveRefund(string $refundId)`, returns a `PaymentResult` that the reconcile command uses to settle [pending refunds](#pending-refunds). ### The Manual Driver [#the-manual-driver] The manual driver (`Shopper\Payment\Drivers\ManualDriver`) calls no API. It is always configured, and initiating a payment succeeds right away with the status `authorized` and a reference such as `manual_01JD8Z6Q4M3K2V7R9T5W1XNB0C`. Authorizing and capturing succeed, webhooks are ignored, and refunding, cancelling or retrieving a manual payment throws a `PaymentException`. The money of a manual order is collected outside Shopper, and the merchant records it with Mark as paid in the admin panel, as described in [In the Admin](#in-the-admin). ## Configuration [#configuration] The payment package merges its configuration under `shopper.payment`. Publish it to `config/shopper/payment.php` with the other Shopper config files: ```bash php artisan vendor:publish --tag=shopper-config ``` The file holds the reconciliation settings described in [Reconciling Payments](#reconciling-payments) and [Orphaned Payments](#orphaned-payments): | Key | Env | Default | Purpose | |-----|-----|---------|---------| | `reconciliation.pull_on_completion` | `PAYMENT_PULL_ON_COMPLETION` | `true` | Queue a provider check when a cart completes with a payment still pending | | `reconciliation.schedule` | `PAYMENT_RECONCILE_SCHEDULE` | `true` | Schedule `shopper:payments:reconcile --pull` every 15 minutes | | `reconciliation.queue` | `PAYMENT_RECONCILE_QUEUE` | `null` | Queue of the provider checks, the default queue when `null` | | `reconciliation.backoff` | | `[60, 300, 900]` | Seconds between the attempts of a provider check | | `reconciliation.prune_after_days` | `PAYMENT_WEBHOOK_EVENTS_PRUNE_AFTER_DAYS` | `90` | Age in days after which journaled provider events are pruned | | `reconciliation.orphan_after_minutes` | `PAYMENT_ORPHAN_AFTER_MINUTES` | `30` | Minutes before a collected payment without an order counts as orphaned | | `reconciliation.orphans` | `PAYMENT_ORPHANS` | `alert` | `alert` reports orphaned payments, `refund` also refunds them | Provider credentials live in each driver's own file: the Stripe driver reads `config/shopper/stripe.php`, published with the `shopper-stripe-config` tag. The scheduled command and the provider checks need the scheduler and a queue worker, as described in [Run the Scheduler and a Queue Worker](/3.x/installation#run-the-scheduler-and-a-queue-worker). ## Processing Payments [#processing-payments] `Shopper\Payment\Services\PaymentProcessingService` is the entry point for code that manages the payment of an order. Resolve it from the container: ```php use Shopper\Payment\Services\PaymentProcessingService; $payments = resolve(PaymentProcessingService::class); ``` Each method uses the driver of the order's payment method, so the order must have one. The service records a transaction for every call and returns the driver's `PaymentResult`. An exception thrown by the driver, such as a `PaymentException` for a provider error, reaches your code. A storefront built on the Store API does not call these methods during checkout: it uses [payment sessions](#payment-sessions) and the provider's [webhooks](#webhooks). ### Initiating a Payment [#initiating-a-payment] `initiate()` creates a payment with the provider for the order total. The driver receives `order_number` and `order_id` in its context, followed by the context you pass. The service records an `initiate` transaction and leaves the payment status unchanged: ```php use Shopper\Core\Models\Contracts\Order; use Shopper\Payment\Services\PaymentProcessingService; $order = resolve(Order::class)::query()->where('number', 'ORD-20261117-000124')->firstOrFail(); $result = resolve(PaymentProcessingService::class)->initiate($order, [ 'metadata' => ['order_number' => $order->number], ]); if ($result->redirectUrl !== null) { return redirect()->away($result->redirectUrl); } return view('checkout.payment', [ 'clientSecret' => $result->clientSecret, ]); ``` The context keys a driver reads depend on the driver. Stripe reads `payment_method`, `customer`, `metadata` and `idempotency_key`. ### Authorizing a Payment [#authorizing-a-payment] `authorize()` asks the driver to authorize an initiated payment. When the driver answers with success, the payment status moves to Authorized: ```php $result = $payments->authorize($order, 'pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T', [ 'payment_method' => 'pm_card_visa', 'return_url' => route('checkout.confirmation', $order->number), ]); if ($result->requiresAction()) { return redirect()->away($result->redirectUrl); } ``` A provider that needs the customer to confirm, for a 3D Secure check for example, answers with a `redirectUrl` or the status `requires_action`. Check `requiresAction()` and send the customer to `redirectUrl` before you treat the payment as authorized. The Stripe driver answers with success in that case too, so the payment status already reads Authorized. ### Capturing a Payment [#capturing-a-payment] `capture()` collects an authorized payment. Pass an amount in cents to capture part of it, or `null` to capture the full amount. A successful capture moves the payment status to Paid, which dispatches `OrderPaid`: ```php $reference = $payments->getLatestReference($order); $result = $payments->capture($order, $reference); $partial = $payments->capture($order, $reference, amount: 4500); ``` Capturing an order that is already paid returns a successful result without calling the provider. Capturing a cancelled or archived order throws a `PaymentException`. ### Refunding a Payment [#refunding-a-payment] `refund()` returns money to the customer, in full or in part. The amount is in cents and the order's payment status must be Paid or Partially refunded, otherwise the service throws a `PaymentException`. The amount cannot exceed what remains refundable: the sum of the successful captures, or the order total when no capture is recorded, minus the successful refunds and the refunds still pending at the provider. Pass an idempotency key with each refund the merchant asks for. Generate it once, such as a UUID stored with the refund request or the queued job, and send the same key on every retry: ```php use Shopper\Payment\Enum\TransactionType; $reference = $order->paymentTransactions() ->successful() ->ofType(TransactionType::Capture) ->latest('id') ->value('reference'); $result = $payments->refund( order: $order, reference: $reference, amount: 2999, reason: 'requested_by_customer', idempotencyKey: $refundKey, ); ``` The service stores the key in the `idempotency_key` column of the refund transaction, unique per order, and passes it to the driver in `$context['idempotency_key']`. A call that repeats a key already recorded on the order returns the state of that refund without calling the provider, so a double submit or a retried job refunds once. Repeating a key with another amount throws a `PaymentException`, and a refund that failed keeps its key: use a new key to try again. Without a key, the service generates a UUID, so every call is a new refund. Call `refund()` outside any open database transaction: the service locks the order and reads the refunds on file, and on MySQL a transaction opened earlier would read them from a stale snapshot. When the refunds reach the captured amount, the payment status moves to Refunded, otherwise to Partially refunded. A fully refunded order also gives its discounts back to their [campaign budgets](/3.x/campaigns#budgets). The reason goes to the provider: Stripe passes it as the reason of its refund, and accepts `duplicate`, `fraudulent` and `requested_by_customer`. The manual driver cannot refund. The service records a `refund` transaction and does not create an `OrderRefund` record. [Order Refunds](#order-refunds) shows how to keep one. #### Pending Refunds [#pending-refunds] Some providers accept a refund and settle it later. A driver reports such a refund by returning `PaymentResult::pendingRefund()` with the provider's refund ID. The service then records the `refund` transaction as `pending` and leaves the payment status as it is, and the pending amount counts against the refundable balance until the refund settles. `$result->isPending()` returns `true` for that answer, and for a refund answered with the status `requires_action`. The provider reports the outcome through its webhooks. A `Refunded` result that carries the same refund ID marks the transaction successful and moves the payment status to Partially refunded or Refunded. A `RefundFailed` result marks it failed, gives its amount back to the refundable balance and dispatches `PaymentFailed`. When the webhook does not come, `shopper:payments:reconcile --pull` asks the drivers that can read a refund for its state, as described in [Reconciling Payments](#reconciling-payments). ### Cancelling a Payment [#cancelling-a-payment] `cancel()` releases a payment that is not captured yet, such as an authorization the store will not capture. A successful cancellation moves the payment status to Voided: ```php $result = $payments->cancel($order, $reference); ``` ### Querying Transactions [#querying-transactions] The service returns the transactions of an order, newest first, and the reference of the latest successful one: ```php $transactions = $payments->getTransactions($order); $reference = $payments->getLatestReference($order); ``` The payment package adds a `paymentTransactions` relationship to the order, and the `PaymentTransaction` model has three scopes: ```php use Shopper\Payment\Enum\TransactionType; use Shopper\Payment\Models\PaymentTransaction; $order->paymentTransactions; PaymentTransaction::query()->successful()->get(); PaymentTransaction::query()->forDriver('stripe')->get(); PaymentTransaction::query()->ofType(TransactionType::Capture)->get(); ``` ### Getting Available Payment Methods for a Zone [#getting-available-payment-methods-for-a-zone] `getMethodsForZone()` returns the enabled payment methods of a zone whose driver is configured, and `getLogoUrl()` the logo of a method, taken from its driver: ```php use Shopper\Core\Models\Zone; $zone = Zone::findBySlug('europe'); $methods = $payments->getMethodsForZone($zone); foreach ($methods as $method) { $logo = $payments->getLogoUrl($method); } ``` [Payment Methods](/3.x/payment-methods#zones) describes how methods are attached to zones. ## Payment Sessions [#payment-sessions] A payment session is the payment a Store API checkout opens on a cart before the order exists. The storefront creates it, the customer confirms it with the provider (with Stripe.js and the client secret, or on the provider's page through the redirect URL), and the cart is completed once the payment is confirmed. The [Install the Store API](/3.x/installation#install-the-store-api) section sets up the endpoints. The checkout makes three calls: | Endpoint | Purpose | |----------|---------| | `POST /store/carts/{cartId}/payment-method` | Set the payment method of the cart | | `POST /store/carts/{cartId}/payment-session` | Open the payment session, or resume the open one | | `POST /store/carts/{cartId}/complete` | Turn the cart into an order | Opening a session prices the cart again, refreshes its shipping price and asks the driver of the payment method to initiate a payment for the cart total. The driver receives an `idempotency_key` in its context, such as `cart_01JD8Z6Q4M3K2V7R9T5W1XNB0C_01JD8Z7A2B3C4D5E6F7G8H9J0K`, new for every attempt, and `metadata.cart_id` with the cart's public ID. The cart stores the session: the driver code, the provider reference, the amount, the currency and whether prices included tax. The response answers `201` with a `payment-sessions` resource whose ID is the provider reference: ```json { "data": { "type": "payment-sessions", "id": "pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T", "attributes": { "driver": "stripe", "status": "pending", "amount": 5998, "currency_code": "USD", "client_secret": "pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T_secret_Wv4nZ8kD", "redirect_url": null, "data": { "stripe_status": "requires_payment_method", "publishable_key": "pk_test_51H8kYbLkdIwHu7ix", "idempotency_key": "cart_01JD8Z6Q4M3K2V7R9T5W1XNB0C_01JD8Z7A2B3C4D5E6F7G8H9J0K" } } } } ``` Calling the endpoint again resumes the open session when its driver can retrieve payments, the total and the currency have not changed, and no promotion of the cart has lapsed. A session the provider already collected is returned as it is. In any other case, Shopper releases the open session and opens a new one. Releasing cancels the payment at the provider before the session is cleared. A change to the cart that affects an open session, such as a new quantity or another shipping option, releases it the same way, and the storefront opens a new session for the new total. Shopper never releases a payment the provider has collected or might collect, so the change is refused instead. Calls on the same cart are serialized by a lock held in the cache. Besides the cart validation errors, a storefront handles these answers: | Status | Code | When | |--------|------|------| | `409` | `cart_completed` | The cart is already an order | | `422` | `payment_method_required` | The cart has no payment method | | `503` | `payment_method_not_configured` | The driver of the method is not configured | | `422` | `price_changed` | A unit price went up since the customer last saw the cart | | `422` | `cart_nothing_to_collect` | The cart total is zero | | `409` | `payment_session_collected` | The payment is collected, or the driver cannot release it, so the cart cannot change | | `409` | `payment_session_in_progress` | Another call holds the cart, retry after the `Retry-After` header (3 seconds) | | `503` | `payment_provider_unavailable` | The provider did not answer or cannot release the payment yet, retry after the `Retry-After` header (5 seconds) | Completing the cart checks the session against the cart. A method whose driver is not `manual` needs a session (`422 payment_session_required`), and the session must match the cart total and currency (`422 payment_session_mismatch`). The order is created with an `initiate` transaction that carries the session reference, then Shopper applies the provider events that arrived before the order, and queues a provider check when `pull_on_completion` is on. When a product runs out of stock after the payment was collected, Shopper refunds or cancels the payment and answers `422 payment_released`. Completing a completed cart again returns its order with `200` instead of `201`. [Order Conversion](/3.x/cart#order-conversion) describes how the cart becomes an order. ## Data Transfer Objects [#data-transfer-objects] Drivers answer with two read-only objects from `Shopper\Payment\DataTransferObjects`. ### PaymentResult [#paymentresult] Every payment operation returns a `PaymentResult`: ```php use Shopper\Payment\DataTransferObjects\PaymentResult; $result = new PaymentResult( success: true, status: 'authorized', reference: 'pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T', clientSecret: 'pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T_secret_Wv4nZ8kD', redirectUrl: null, amount: 5998, message: null, data: ['stripe_status' => 'requires_capture'], ); $result = PaymentResult::failed('Your card was declined.', 'pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T'); $result = PaymentResult::pendingRefund('re_3QJ8bTLkdIwHu7ix1Hc4Vd2P', 2999); $result->requiresAction(); $result->isCollected(); $result->isPending(); $result->toArray(); ``` `pendingRefund()` answers a refund the provider accepted but has not settled yet, with the provider's refund ID as reference and the status `pending`. `isPending()` returns `true` for a successful result with the status `pending` or `requires_action`. `requiresAction()` returns `true` when the result carries a redirect URL or the status `requires_action`. `isCollected()` returns `true` for the statuses `authorized`, `captured` and `processing`, the payments a cart can no longer release. `toArray()` uses snake_case keys (`client_secret`, `redirect_url`). The statuses Shopper reads are `pending`, `requires_action`, `processing`, `authorized`, `captured`, `canceled`, `failed` and `refunded`. ### WebhookResult [#webhookresult] `handleWebhook()` returns a `WebhookResult`, which tells Shopper what happened to which payment: ```php use Shopper\Payment\DataTransferObjects\WebhookResult; use Shopper\Payment\Enum\WebhookAction; $result = new WebhookResult( action: WebhookAction::Captured, reference: 'pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T', amount: 5998, data: ['cart_id' => '01JD8Z6Q4M3K2V7R9T5W1XNB0C'], eventId: 'evt_1QJ7yBLkdIwHu7ixq8Rn2xLp', ); $ignored = WebhookResult::ignored(); $ignored->isIgnored(); $result->refundId(); $result->idempotencyKey(); ``` The `Shopper\Payment\Enum\WebhookAction` cases are `Authorized`, `Captured`, `Refunded`, `Canceled`, `Failed`, `RefundFailed` and `Ignored`. `eventId` is the provider's event ID, which Shopper uses to apply each event once. In `data`, Shopper reads `refund_id` for a refund, `idempotency_key` for the key of the refund request, `cart_id` for a payment opened from a cart and `failure_message` for a failure. `refundId()` and `idempotencyKey()` return the first two, or `null`. ## Payment Status [#payment-status] The `payment_status` column of the order holds a `Shopper\Core\Enum\PaymentStatus` case. The service moves it as transactions succeed: | Case | Value | Meaning | |------|-------|---------| | `Pending` | `pending` | Awaiting payment | | `Authorized` | `authorized` | Funds held, not captured | | `Paid` | `paid` | Funds collected | | `PartiallyRefunded` | `partially_refunded` | Part of the amount refunded | | `Refunded` | `refunded` | The captured amount refunded | | `Voided` | `voided` | Cancelled before capture | ### Status Transitions [#status-transitions] The enum allows these moves, and the service skips a move the enum does not allow, so a capture reported late never brings a refunded order back to Paid: | From | To | When | |------|----|------| | Pending | Authorized | An authorization succeeds | | Pending | Paid | A capture succeeds (automatic capture), or Mark as paid in the admin panel | | Pending | Voided | A cancellation succeeds | | Authorized | Paid | A capture succeeds | | Authorized | Voided | A cancellation succeeds | | Paid | Partially refunded | A refund leaves part of the captured amount | | Paid | Refunded | A refund reaches the captured amount | | Partially refunded | Partially refunded or Refunded | Another refund succeeds | The enum allows no move out of Refunded and Voided, and a failed authorization, capture or refund dispatches `PaymentFailed`. A failure leaves the status as it is, with one exception: a `RefundFailed` webhook for a refund the provider had confirmed marks that refund failed, and the payment status steps back from Refunded or Partially refunded to what the remaining refunds give, Paid when none is left. That step is written outside the enum and dispatches no `OrderPaid`, and an order in processing whose items are all delivered then moves to Completed. The order status has its own state machine, described on [Orders](/3.x/orders). ## Transaction Model [#transaction-model] Every payment operation is recorded as a `Shopper\Payment\Models\PaymentTransaction`, including those reported by the provider. ### Database Schema [#database-schema] Transactions are stored in the `sh_payment_transactions` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Description | |--------|------|-------------| | `id` | bigint | Primary key | | `driver` | string | Driver code (`stripe`, `manual`, ...) | | `type` | string | `TransactionType` value | | `status` | string | `TransactionStatus` value | | `amount` | integer | Amount in cents | | `currency_code` | string(3) | ISO currency code | | `reference` | string, nullable | Provider reference: the payment, or the refund for a refund | | `idempotency_key` | string, nullable | Idempotency key of a refund request, unique per order | | `data` | jsonb, nullable | Data returned by the driver | | `notes` | text, nullable | Message returned by the driver | | `metadata` | jsonb, nullable | Custom data | | `order_id` | bigint, nullable | Foreign key to the order | | `payment_method_id` | bigint, nullable | Foreign key to the payment method | | `user_id` | bigint, nullable | The admin user or customer who made the call, `null` for provider events | | `created_at` | timestamp | Creation time | | `updated_at` | timestamp | Last update time | The model has `order()` and `paymentMethod()` relationships. ### Enums [#enums] `type` holds a `Shopper\Payment\Enum\TransactionType` case and `status` a `Shopper\Payment\Enum\TransactionStatus` case: | Enum | Case | Value | |------|------|-------| | `TransactionType` | `Initiate` | `initiate` | | `TransactionType` | `Authorize` | `authorize` | | `TransactionType` | `Capture` | `capture` | | `TransactionType` | `Refund` | `refund` | | `TransactionType` | `Cancel` | `cancel` | | `TransactionStatus` | `Pending` | `pending` | | `TransactionStatus` | `Success` | `success` | | `TransactionStatus` | `Failed` | `failed` | The `initiate` transaction a Store API checkout records when the order is created has the status `pending`, and so does a refund the provider has not settled yet, until its webhook or the reconcile command settles it. The service records the others as `success` or `failed` from the driver's answer. ## Order Refunds [#order-refunds] `Shopper\Core\Models\OrderRefund` is the refund record of an order, the one the dashboard and the Store API read. The payment service does not write it: your application creates it when it refunds an order. Refunds are stored in the `sh_order_refunds` table: | Column | Type | Description | |--------|------|-------------| | `id` | bigint | Primary key | | `public_id` | ulid, nullable | Public identifier | | `reason` | text, nullable | Why the order is refunded | | `amount` | integer | Amount in cents | | `currency` | string | ISO currency code | | `status` | string | `OrderRefundStatus` value, `pending` by default | | `notes` | text, nullable | Internal notes | | `metadata` | jsonb, nullable | Custom data | | `order_id` | bigint | Foreign key to the order | | `user_id` | bigint, nullable | Foreign key to the customer | | `created_at` | timestamp | Creation time | | `updated_at` | timestamp | Last update time | `status` holds a `Shopper\Core\Enum\OrderRefundStatus` case: | Case | Value | Label | |------|-------|-------| | `Awaiting` | `awaiting` | Awaiting | | `Pending` | `pending` | Pending | | `Treatment` | `treatment` | Treatment | | `Partial_Refund` | `partial_refund` | Partially refunded | | `Refunded` | `refunded` | Refunded | | `Rejected` | `rejected` | Rejected | | `Cancelled` | `cancelled` | Cancelled | `OrderRefundStatus::settled()` returns `Partial_Refund` and `Refunded`, the refunds where money went back to the customer. The dashboard subtracts the settled refunds from the revenue of their period and currency. Create the record after a successful refund. A [pending refund](#pending-refunds) gets the `Pending` status, and a settled one the status that matches the order's new payment status: ```php use Shopper\Core\Enum\OrderRefundStatus; use Shopper\Core\Enum\PaymentStatus; use Shopper\Core\Models\OrderRefund; $result = $payments->refund( order: $order, reference: $reference, amount: 2999, reason: 'requested_by_customer', idempotencyKey: $refundKey, ); if ($result->success) { OrderRefund::query()->create([ 'order_id' => $order->id, 'user_id' => $order->customer_id, 'amount' => 2999, 'currency' => $order->currency_code, 'reason' => 'requested_by_customer', 'status' => match (true) { $result->isPending() => OrderRefundStatus::Pending, $order->refresh()->payment_status === PaymentStatus::Refunded => OrderRefundStatus::Refunded, default => OrderRefundStatus::Partial_Refund, }, ]); } ``` A pending refund that fails later dispatches `PaymentFailed` with the `refund` transaction type. One that succeeds dispatches no event: the status of its `refund` transaction, whose `reference` is the provider's refund ID, tells you when to move the record to its settled status. The model has `order()` and `customer()` relationships, and the order a `refund()` relationship that returns one refund. Query every refund of an order with `OrderRefund::query()->where('order_id', $order->id)`. The model cannot be swapped, as listed in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). ## Capture Methods [#capture-methods] Shopper supports two capture strategies. The strategy decides when the customer's funds are collected. ### Manual Capture (Authorize-then-Capture) [#manual-capture-authorize-then-capture] Recommended for physical goods. Funds are held on the customer's card at checkout but only collected when you decide to capture. This gives you the flexibility to: - Verify stock availability before collecting payment - Cancel an order without processing a refund (and without refund fees) - Capture only when the order is ready to ship When the order is ready to ship, the merchant captures the payment from the admin panel, or your code calls [`capture()`](#capturing-a-payment): ![Capture flow: merchant clicks Capture on order detail, Shopper calls capturePayment on the provider, funds are transferred, transaction recorded as captured and order marked as Paid](/images/shared/capture.png) ### Automatic Capture [#automatic-capture] Funds are collected immediately when the customer confirms payment. Use this for digital products, subscriptions, or when fulfillment is instant. The provider reports the capture and the order moves from Pending to Paid. Manual capture is the default for the Stripe driver (`STRIPE_CAPTURE_METHOD=manual`). Authorization holds typically last 7 days (varies by card network), so capture within that window or the hold is released. When Stripe cancels an expired authorization, its webhook voids the payment and cancels the order. ## Webhooks [#webhooks] A provider reports the outcome of a payment through webhooks: an authorization, a capture, a refund made from its dashboard, a cancellation or a failure. With the Store API installed, Shopper receives them on one route per driver, under the `store` prefix set by `SHOPPER_API_PREFIX`: ```text POST /store/webhooks/{driver} ``` Register this URL in the provider's dashboard, such as `https://example.com/store/webhooks/stripe`. The route answers `404` for a driver that is not registered or not configured. It passes the request body to the driver's `handleWebhook()` with the raw body added as `_raw_body`, for signature checks, and the headers with lowercase names and their first value. A webhook the driver rejects, for a wrong signature for example, answers `400` with `{"error": "Invalid webhook payload."}`, and an accepted one `200` with `{"received": true}`. The route is rate limited to 120 requests per minute per IP address, set by `rate_limiters.shopper-api-webhook` in `config/shopper/http.php`, and `middleware.webhook` in the same file adds middleware to it. Shopper applies each action to the order that holds the reference in its transactions: | Action | Effect | |--------|--------| | `Authorized` | Records an `authorize` transaction and moves the payment status to Authorized | | `Captured` | Records a `capture` transaction and moves the payment status to Paid | | `Refunded` | Settles the pending refund with the same refund ID, or records a successful `refund` transaction, moves the payment status to Partially refunded or Refunded, and gives a fully refunded order's discounts back to their campaign budgets | | `RefundFailed` | Marks the refund failed, or records a failed `refund` transaction, gives its amount back to the refundable balance, steps the payment status back when the refund had been confirmed, and dispatches `PaymentFailed` | | `Canceled` | Records a `cancel` transaction, moves the payment status to Voided and cancels the order when it is not paid and can be cancelled, which dispatches `OrderCancelled` | | `Failed` | On an order still pending payment, records a failed transaction and dispatches `PaymentFailed` | | `Ignored` | Nothing | The order row is locked while an event is applied, and an outcome already recorded for the same reference is skipped, so redelivered events change nothing. ### The Event Journal [#the-event-journal] A webhook that carries an event ID is journaled in `sh_payment_webhook_events` before it is applied. The table has a unique index on `driver` and `event_id`, so a redelivered event is stored once. An event whose order does not exist yet, because the customer confirmed the payment before the storefront completed the cart, stays unprocessed. When the cart is completed, or when the reconcile command runs, Shopper applies the waiting events of each reference in a fixed order (authorized, captured, failed, canceled, refunded, refund failed), whatever order they arrived in. A webhook without an event ID is applied right away, and dropped when no order holds its reference yet. The scheduler prunes the journal daily with `model:prune`: events older than `prune_after_days` are deleted once they are processed, marked as orphaned, or of a type other than authorized and captured. To receive webhooks without the Store API, register a route that does what Shopper's route does, and exclude it from CSRF protection: ```php title="routes/web.php" use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Shopper\Payment\Actions\IngestPaymentEvent; use Shopper\Payment\Exceptions\PaymentException; use Shopper\Payment\Facades\Payment; Route::post('/payments/webhooks/{driver}', function (Request $request, string $driver, IngestPaymentEvent $ingest) { abort_unless(Payment::isConfigured($driver), 404); try { $result = Payment::driver($driver)->handleWebhook( [...$request->all(), '_raw_body' => $request->getContent()], array_map(fn (array $values): string => (string) ($values[0] ?? ''), $request->headers->all()), ); } catch (PaymentException) { abort(400); } $ingest->execute($driver, $result); return response()->json(['received' => true]); })->whereIn('driver', ['stripe', 'mollie'])->withoutMiddleware(ValidateCsrfToken::class); ``` ## Reconciling Payments [#reconciling-payments] A webhook can be lost or arrive late, so Shopper also asks the provider. When a cart is completed with its payment still pending, Shopper queues a `Shopper\Payment\Jobs\SyncPendingPaymentJob` (when `pull_on_completion` is on). The job retrieves the payment from the provider and applies an authorization, a capture or a cancellation to the order. It only acts on an order that is new and pending payment, with a driver that supports retrieval. The job is unique per order and reference for an hour, and retries after the delays of `backoff`. The `shopper:payments:reconcile` command catches up on the rest: ```bash php artisan shopper:payments:reconcile --pull --minutes=30 ``` It applies the journaled events whose order now exists, reports the orphaned payments described below, and with `--pull` queues a provider check for every order still pending payment after `--minutes` (15 by default) whose method uses a driver other than `manual`. When `schedule` is on, Shopper schedules it with `--pull` every 15 minutes, without overlapping runs. With `--pull`, the command also settles the [pending refunds](#pending-refunds) recorded more than `--minutes` ago, for the drivers that implement `Shopper\Payment\Contracts\RetrievesRefunds`. It calls the driver's `retrieveRefund()` with the provider's refund ID and applies the answer as the webhook would: a successful result settles the refund, a failed one marks it failed with the result's message, and a result that is still pending is left for the next run. A refund that throws is reported to your exception handler and the command moves on. The pending refunds of other drivers wait for their webhook. An order whose payment never lands is cancelled by the hourly `shopper:orders:reclaim` command, which releases the payment at the provider first, as described in [Reclaiming Pending Orders](/3.x/orders#reclaiming-pending-orders). ## Orphaned Payments [#orphaned-payments] A customer can pay and lose the connection before the storefront completes the cart. The reconcile command looks for authorizations and captures journaled more than `orphan_after_minutes` ago that still have no order, and dispatches `PaymentOrphaned` for each one the provider has not since reported as refunded or canceled. A refund the provider has reported as failed does not count, so a payment whose only refund failed is dispatched as an orphan. With the Store API installed, a listener completes the cart the payment belongs to. When a listener recognizes the payment but cannot complete its cart, the payment is reported to your exception handler, and refunded when `orphans` is `refund`. [Orphaned Payments](/3.x/events#orphaned-payments) on the Events page describes the event and its listeners. A payment the command has refunded is marked in the journal, and later runs neither refund it nor report it again. When the provider then reports that its refund failed, the `RefundFailed` webhook finds no order, and Shopper reports the failed refund to your exception handler, as it does for any refund of a payment without an order that fails. ## Custom Drivers [#custom-drivers] You can create drivers for any payment provider: PayPal, Mollie, Razorpay, NotchPay. The steps below build a Mollie driver that redirects the customer to Mollie's hosted checkout. ### Step 1: Create the Driver Class [#step-1-create-the-driver-class] Extend the abstract `Driver` and implement the operations Mollie offers: ```php title="app/Payment/Drivers/MollieDriver.php" apiKey) && filled($this->redirectUrl); } public function mode(): ?PaymentMode { if (! $this->isConfigured()) { return null; } return str_starts_with((string) $this->apiKey, 'live_') ? PaymentMode::Live : PaymentMode::Test; } public function supportsRetrieval(): bool { return true; } public function initiatePayment(int $amount, string $currency, array $context = []): PaymentResult { if (! $this->isConfigured()) { throw PaymentException::notConfigured($this->code()); } $payment = $this->send( $this->client() ->withHeaders(array_filter(['Idempotency-Key' => $context['idempotency_key'] ?? null])) ->post('payments', array_filter([ 'amount' => $this->toMollie($amount, $currency), 'description' => isset($context['order_number']) ? 'Order '.$context['order_number'] : (string) config('app.name'), 'redirectUrl' => $this->redirectUrl, 'webhookUrl' => $this->webhookUrl, 'metadata' => $context['metadata'] ?? null, ])), ); return new PaymentResult( success: true, status: $this->status($payment['status']), reference: $payment['id'], redirectUrl: $payment['_links']['checkout']['href'] ?? null, amount: $amount, ); } public function capturePayment(string $reference, ?int $amount = null): PaymentResult { $body = []; if ($amount !== null) { $body['amount'] = $this->toMollie($amount, $this->payment($reference)['amount']['currency']); } $capture = $this->send($this->client()->post("payments/{$reference}/captures", $body)); return new PaymentResult( success: $capture['status'] !== 'failed', status: 'captured', reference: $reference, amount: $amount, ); } public function refundPayment(string $reference, int $amount, ?string $reason = null, array $context = []): PaymentResult { $currency = $this->payment($reference)['amount']['currency']; $refund = $this->send( $this->client() ->withHeaders(array_filter(['Idempotency-Key' => $context['idempotency_key'] ?? null])) ->post("payments/{$reference}/refunds", array_filter([ 'amount' => $this->toMollie($amount, $currency), 'description' => $reason, ])), ); return new PaymentResult( success: ! in_array($refund['status'], ['failed', 'canceled'], true), status: 'refunded', reference: $refund['id'], amount: $amount, ); } public function cancelPayment(string $reference): PaymentResult { $payment = $this->send($this->client()->delete("payments/{$reference}")); return new PaymentResult( success: true, status: 'canceled', reference: $payment['id'], ); } public function retrievePayment(string $reference): PaymentResult { $payment = $this->payment($reference); $status = $this->status($payment['status']); return new PaymentResult( success: ! in_array($status, ['canceled', 'failed'], true), status: $status, reference: $payment['id'], redirectUrl: $payment['_links']['checkout']['href'] ?? null, amount: $this->fromMollie($payment['amount']), ); } public function handleWebhook(array $payload, array $headers = []): WebhookResult { $id = $payload['id'] ?? null; if (! is_string($id) || ! str_starts_with($id, 'tr_')) { return WebhookResult::ignored(); } $payment = $this->payment($id); $action = WebhookAction::tryFrom($this->status($payment['status'])); if ($action === null) { return WebhookResult::ignored(); } return new WebhookResult( action: $action, reference: $payment['id'], amount: $this->fromMollie($payment['amount']), data: ['cart_id' => $payment['metadata']['cart_id'] ?? null], eventId: "{$payment['id']}:{$payment['status']}", ); } private function status(string $status): string { return match ($status) { 'open' => 'pending', 'pending' => 'processing', 'authorized' => 'authorized', 'paid' => 'captured', 'canceled', 'expired' => 'canceled', default => 'failed', }; } private function toMollie(int $amount, string $currency): array { $decimals = is_no_division_currency($currency) ? 0 : 2; return [ 'currency' => $currency, 'value' => number_format($amount / (10 ** $decimals), $currency === 'ISK' ? 0 : $decimals, '.', ''), ]; } private function fromMollie(array $amount): int { $decimals = is_no_division_currency($amount['currency']) ? 0 : 2; return (int) round((float) $amount['value'] * (10 ** $decimals)); } private function payment(string $reference): array { return $this->send($this->client()->get("payments/{$reference}")); } private function send(Response $response): array { if ($response->failed()) { throw PaymentException::apiError($this->code(), (string) $response->json('detail', $response->body())); } return $response->json(); } private function client(): PendingRequest { return Http::baseUrl('https://api.mollie.com/v2/') ->withToken((string) $this->apiKey) ->acceptJson(); } } ``` Mollie's payment webhook posts only the payment ID. The driver reads the payment from Mollie's API with its key, so a forged request cannot report a status Mollie does not hold. Amounts go to Mollie as decimal strings, using the [zero-decimal currency](/3.x/money#zero-decimal-currencies) list to place the decimal point. Mollie takes ISK without decimals, which Shopper stores in cents, so the driver rounds it to whole units. ### Step 2: Register the Driver [#step-2-register-the-driver] Register the driver in a service provider: ```php title="app/Providers/AppServiceProvider.php" new MollieDriver( apiKey: config('shopper.mollie.api_key'), redirectUrl: config('shopper.mollie.redirect_url'), webhookUrl: config('shopper.mollie.webhook_url'), )); } } ``` The driver now appears in the driver list of the payment method form, and its webhook route is `/store/webhooks/mollie`. ### Step 3: Add Configuration [#step-3-add-configuration] Create the config file the driver reads. The `enabled` key follows the convention of the Stripe driver and is read by `Payment::configuredDrivers()`: ```php title="config/shopper/mollie.php" env('PAYMENT_MOLLIE_ENABLED', false), 'api_key' => env('MOLLIE_API_KEY'), 'redirect_url' => env('MOLLIE_REDIRECT_URL'), 'webhook_url' => env('MOLLIE_WEBHOOK_URL'), ]; ``` Then set the values in `.env`: ```dotenv PAYMENT_MOLLIE_ENABLED=true MOLLIE_API_KEY=test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx MOLLIE_REDIRECT_URL=https://example.com/checkout/complete MOLLIE_WEBHOOK_URL=https://example.com/store/webhooks/mollie ``` ### Step 4: Create the Payment Method [#step-4-create-the-payment-method] Create a payment method that uses the driver, from Settings, Payment methods in the admin panel or in code, and attach it to the zones where it is offered: ```php use Shopper\Core\Models\PaymentMethod; PaymentMethod::query()->create([ 'title' => 'iDEAL and Bancontact', 'slug' => 'mollie', 'driver' => 'mollie', 'is_enabled' => true, ]); ``` [Payment Methods](/3.x/payment-methods#zones) shows how to attach a method to zones. A driver works with every part of Shopper when it follows these rules: - Map the provider's states to the statuses Shopper reads: `pending`, `requires_action`, `processing`, `authorized`, `captured`, `canceled`, `failed` and `refunded`. - Give every webhook result an `eventId` that is unique per event, so the journal stores it once and the reconcile command can find orphaned payments. - Put the provider's refund ID in `data.refund_id` for a refund, `data.cart_id` from the payment metadata for a payment opened from a cart, and the provider's message in `data.failure_message` for a failure. - Answer a refund the provider accepts without settling it with `PaymentResult::pendingRefund()` and the provider's refund ID, never the payment reference, then report its outcome with a `Refunded` or `RefundFailed` webhook result that carries the same ID in `data.refund_id`. A refund answered with `success: true` and any status other than `pending` or `requires_action` is recorded as settled. - Send `$context['idempotency_key']` to the provider with the refund, as the request's idempotency key and in the refund's metadata when the provider stores it, and return it in `data.idempotency_key` of the `Refunded` and `RefundFailed` results. A refund recorded by its webhook after the answer to `refundPayment()` was lost then carries the key, and a retry with that key finds it. - Implement `Shopper\Payment\Contracts\RetrievesRefunds` when the provider can read a refund by its ID, so `shopper:payments:reconcile --pull` settles the pending refunds whose webhook never came. `retrieveRefund(string $refundId)` returns `PaymentResult::pendingRefund($refundId)` while the refund is not settled, `new PaymentResult(success: true, status: 'refunded', reference: $refundId)` once it is, and `PaymentResult::failed($reason, $refundId)` when it failed. Any other state, or a lookup that did not answer, returns `pendingRefund()` or throws. - Return `true` from `supportsRetrieval()` and implement `retrievePayment()` for Store API checkouts: without retrieval, a session cannot be resumed or released, and a cart that holds one cannot change. - Make `cancelPayment()` work on a payment the customer has not confirmed yet. When the provider cannot cancel an open payment, a change to the cart answers `503 payment_provider_unavailable` until the payment fails or expires. - Throw a `PaymentException` when the provider answers with an error, as `send()` does above. Mollie also calls the payment webhook for refunds and chargebacks, which leave the payment status at `paid`. The driver above does not report them: a refund made from Mollie's dashboard is not recorded on the order. For the same reason, its `refundPayment()` answers every refund Mollie accepts as settled, and the driver does not implement `RetrievesRefunds`. A driver that reports refund webhooks returns `pendingRefund()` for a refund the provider has not settled yet. ## Events [#events] The payment package and the core dispatch these events: | Event | Namespace | When | |-------|-----------|------| | `OrderPaid` | `Shopper\Core\Events\Orders` | The payment status becomes Paid | | `PaymentFailed` | `Shopper\Payment\Events` | An authorization, a capture or a refund fails | | `OrderCancelled` | `Shopper\Core\Events\Orders` | The provider cancels the payment of an order that is not paid | | `PaymentOrphaned` | `Shopper\Core\Events\Payments` | A collected payment still has no order | | `OrphanedPaymentRefunded` | `Shopper\Core\Events\Payments` | An orphaned payment is refunded | `PaymentFailed` carries the order, the `TransactionType` that failed and the provider's message as `$reason`. When database notifications are enabled, the admin panel notifies its administrators of a failed payment, as described on [Notifications](/3.x/notifications). [Payment Events](/3.x/events#payment-events) lists the arguments of each event and how to listen to them. ## Permissions [#permissions] The admin panel checks these permissions on the payment screens: | Permission | Checked for | |------------|-------------| | `orders.read` | Opening an order and its payment details | | `orders.edit` | Mark as paid and Capture payment on an order | | `system.settings` | The Payment methods settings page, where methods and their drivers are managed | [Access by Section](/3.x/acl#access-by-section) lists the permissions of every section. ## In the Admin [#in-the-admin] Merchants manage payment methods under Settings, Payment methods: the list shows each method with its driver, green when the driver is configured, and its Live or Test mode, and the form offers every registered driver, marked "Not configured" when its credentials are missing. On an order pending payment, Mark as paid sets the payment status to Paid for a payment collected outside Shopper, such as cash on delivery, and moves a new order to processing. On an authorized order, Capture payment captures the payment with the order's latest successful reference. Refunds are made in code, as shown in [Refunding a Payment](#refunding-a-payment). The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the checkout payment flow and the provider webhooks under the `store` prefix: | Endpoint | Purpose | |----------|---------| | `GET /store/carts/{cartId}/payment-methods` | The enabled methods of the cart's zone whose driver is configured | | `POST /store/carts/{cartId}/payment-method` | Set the cart's payment method by its public ID | | `POST /store/carts/{cartId}/payment-session` | Open or resume the payment session, as described in [Payment Sessions](#payment-sessions) | | `POST /store/carts/{cartId}/complete` | Place the order | | `POST /store/webhooks/{driver}` | Receive the provider's webhooks | | `GET /store/customers/me/orders/{orderId}?include=refund` | An order of the signed-in customer with its refund (`status`, `amount`, `currency`, `reason`, `created_at`) | The Store API does not expose payment transactions or refunding. The Store API [Checkout](/3.x/store-api/checkout) guide covers the payment session and the completion of a cart. # Stripe (/3.x/payments/stripe) The `shopper/stripe` package connects a Shopper store to Stripe. It registers a payment driver named `stripe` on the payment manager of [`shopper/payment`](/3.x/payments): the driver creates a Stripe PaymentIntent for each payment, Stripe.js confirms it in the customer's browser with a 3D Secure check when the card asks for one, and Stripe's webhooks move the payment of the order to Authorized, Paid, Refunded or Voided. Capture can be manual or automatic, and refunds full or partial. This page covers what is specific to Stripe. The payment manager, the processing service, payment sessions and the way Shopper applies provider events are described on [Payments](/3.x/payments). ## Installation [#installation] Install the package with Composer: ```bash composer require shopper/stripe ``` The package requires `shopper/payment` and Stripe's PHP library, `stripe/stripe-php`. Laravel discovers `Shopper\Stripe\StripeServiceProvider`, which merges the package configuration under `shopper.stripe` and registers the `stripe` driver with `Payment::extend()`, built from that configuration. Publish the configuration file to `config/shopper/stripe.php`: ```bash php artisan vendor:publish --tag=shopper-stripe-config ``` ## Configuration [#configuration] Every value of `config/shopper/stripe.php` comes from an environment variable: | Key | Env | Default | Purpose | |-----|-----|---------|---------| | `enabled` | `PAYMENT_STRIPE_ENABLED` | `false` | Lists `stripe` in `Payment::configuredDrivers()` | | `secret_key` | `STRIPE_SECRET_KEY` | `null` | Secret API key, used for every call to Stripe. Its prefix sets the [test mode](#test-mode) | | `publishable_key` | `STRIPE_PUBLISHABLE_KEY` | `null` | Publishable key returned to the storefront with each payment, for Stripe.js | | `webhook_secret` | `STRIPE_WEBHOOK_SECRET` | `null` | Signing secret of the webhook endpoint, used to verify each event | | `capture_method` | `STRIPE_CAPTURE_METHOD` | `manual` | `manual` or `automatic`, as described in [Capture Method](#capture-method) | Copy the secret and publishable keys from the API keys page of your Stripe Dashboard. The webhook signing secret is shown on the webhook endpoint once you create it, as described in [Setting Up](#setting-up): ```bash title=".env" STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_CAPTURE_METHOD=manual ``` The driver is configured when both the secret key and the webhook secret are set. Shopper reads that check everywhere else: until both are set, the admin panel marks Stripe "Not configured", carts do not offer the payment methods that use it, opening a payment session answers `503 payment_method_not_configured`, and the webhook route answers `404`. `PAYMENT_STRIPE_ENABLED` only affects the list returned by `Payment::configuredDrivers()`, which neither the admin panel nor the Store API reads: the flag does not show or hide Stripe. The publishable key is not part of the check, but the storefront cannot load the Payment Element without it. Keep the Stripe keys in your environment and out of version control. ## Capture Method [#capture-method] The `capture_method` setting decides when Stripe collects the customer's funds. The driver passes it to every PaymentIntent it creates: | Value | Behavior | Use case | |-------|----------|----------| | `manual` | The card is authorized at checkout and captured later, from the admin panel or in code | Physical goods, checking stock before charging | | `automatic` | The card is charged when the customer confirms | Digital products, instant fulfillment | Manual capture is the default. The payment status of the order moves from Pending to Authorized when the customer confirms, then to Paid when the store captures. With automatic capture, it moves from Pending to Paid. [Capture Methods](/3.x/payments#capture-methods) describes both strategies. A capture can collect less than the authorized amount: the driver passes the amount to Stripe as `amount_to_capture`, and Stripe releases the rest of the hold. A PaymentIntent is captured once, so capture the amount the order needs in one call. Stripe keeps an authorization for a limited time, generally 7 days for online card payments, depending on the card network. When the authorization expires, Stripe cancels the PaymentIntent, and its `payment_intent.canceled` webhook voids the payment and cancels the order when it is unpaid and still cancellable. ## Payment Method Setup [#payment-method-setup] Customers pay with Stripe through a payment method whose `driver` is `stripe`. Create it in the admin panel under Settings, Payment methods, where the Driver field lists every driver registered with `Payment::extend()`: Stripe shows there once the package is installed, marked "Not configured" until the secret key and the webhook secret are set. You can also create it with Eloquent, then attach it to the zones where it is offered: ```php use Shopper\Core\Models\PaymentMethod; use Shopper\Core\Models\Zone; $creditCard = PaymentMethod::query()->create([ 'title' => 'Credit Card', 'slug' => 'credit-card', 'driver' => 'stripe', 'description' => 'Pay securely with your credit or debit card.', 'is_enabled' => true, ]); $creditCard->zones()->sync([Zone::findBySlug('europe')->id]); ``` A cart offers the method only while the driver is configured. The settings list shows the method with a green Stripe badge once the secret key and the webhook secret are set, and its Live or Test mode. [Payment Methods](/3.x/payment-methods) describes the model and its zones, and the [User Guide](/3.x/user-guide) the settings screen. ## Payment Flow [#payment-flow] A Stripe payment follows the PaymentIntent flow: Shopper creates the PaymentIntent on the server, the customer confirms it in the browser with Stripe.js, and Stripe reports the outcome through its webhooks. The steps below follow a checkout with manual capture. ### 1. Initiate at Checkout [#1-initiate-at-checkout] With the Store API, the storefront opens a [payment session](/3.x/payments#payment-sessions) once the customer has chosen the Stripe payment method: ```text POST /store/carts/{cartId}/payment-session ``` The driver creates a PaymentIntent for the cart total [in cents](/3.x/money), with the currency code in lowercase, the configured capture method, the cart's public ID in `metadata.cart_id` and the idempotency key of the session. The response of a new session carries the two values Stripe.js needs: `client_secret`, and the publishable key in `data.publishable_key`. The session ID is the PaymentIntent ID, such as `pi_3QJ7xYLkdIwHu7ix0Zb5Rk1T`. A call that resumes the open session answers with the same `client_secret` but without `data.publishable_key`, so give the storefront the publishable key in its own configuration as well. Code that manages orders without the Store API initiates the payment of an existing order with the processing service: ```php use Shopper\Payment\Services\PaymentProcessingService; $result = resolve(PaymentProcessingService::class)->initiate($order, [ 'metadata' => ['order_number' => $order->number], ]); return view('checkout.payment', [ 'clientSecret' => $result->clientSecret, 'publishableKey' => $result->data['publishable_key'], ]); ``` The driver reads four keys from the context: `payment_method`, `customer` (a Stripe customer ID), `metadata` and `idempotency_key`. Without an idempotency key, it generates one. A Stripe API error is thrown as a `Shopper\Stripe\Exceptions\StripeException`, which extends `PaymentException`. ### 2. Confirm on the Frontend [#2-confirm-on-the-frontend] The payment page mounts Stripe's Payment Element with the client secret and confirms the payment with `stripe.confirmPayment()`: ```blade title="resources/views/checkout/payment.blade.php"
    ``` Stripe runs the 3D Secure check when the card requires it, then redirects the customer to `return_url` with the `payment_intent` and `payment_intent_client_secret` query parameters. `confirmPayment()` returns only when the confirmation fails before the redirect, with the error to show. ### 3. Handle the Callback [#3-handle-the-callback] With the Store API, the page behind `return_url` completes the cart: ```text POST /store/carts/{cartId}/complete ``` Shopper creates the order with an `initiate` transaction that holds the PaymentIntent ID, applies the Stripe events that arrived before the order existed, and queues a provider check when `reconciliation.pull_on_completion` is on. The webhook then moves the payment status: `payment_intent.amount_capturable_updated` to Authorized with manual capture, `payment_intent.succeeded` to Paid with automatic capture. The confirmation page can show the order as pending payment for the few seconds before the webhook lands. [Payment Sessions](/3.x/payments#payment-sessions) lists the answers of the complete call. An order initiated in code already holds the PaymentIntent ID in its transactions, so the same webhooks update it. Stripe.js has confirmed the PaymentIntent, so the callback does not call `authorize()`, which would confirm it a second time. To show the outcome before the webhook arrives, read the PaymentIntent from Stripe: ```php use Shopper\Payment\Facades\Payment; use Shopper\Payment\Services\PaymentProcessingService; $reference = resolve(PaymentProcessingService::class)->getLatestReference($order); $payment = Payment::driver('stripe')->retrievePayment($reference); $payment->status; ``` The driver maps the status of the PaymentIntent to these values: | Stripe status | `status` | |---------------|----------| | `requires_payment_method`, `requires_confirmation` | `pending` | | `requires_action` | `requires_action` | | `processing` | `processing` | | `requires_capture` | `authorized` | | `succeeded` | `captured` | | `canceled` | `canceled` | `authorize()` is for a server-side confirmation, where your code passes a `payment_method` and a `return_url`, as described in [Authorizing a Payment](/3.x/payments#authorizing-a-payment). ### 4. Capture from the Admin Panel [#4-capture-from-the-admin-panel] When the order is ready to ship, the merchant clicks Capture payment on the order page. The action shows on an authorized order that is neither cancelled nor archived, needs the `orders.edit` permission, and captures the full amount with the order's latest successful reference. The payment status moves from Authorized to Paid, which dispatches `OrderPaid`. Code captures the same way, in full or in part, with [`capture()`](/3.x/payments#capturing-a-payment). ## Webhooks [#webhooks] Stripe reports the outcome of each PaymentIntent and each refund through webhooks. The driver verifies the event, turns it into a `WebhookResult`, and Shopper applies it to the order that holds the PaymentIntent, once per event, as described in [Webhooks](/3.x/payments#webhooks). ### Setting Up [#setting-up] The Store API receives Stripe's webhooks on the driver's route, under the prefix set by `SHOPPER_API_PREFIX` (`store` by default). The [Install the Store API](/3.x/installation#install-the-store-api) section sets it up. In the Stripe Dashboard, add a webhook endpoint with the URL `https://example.com/store/webhooks/stripe` and select the seven events listed in [Handled Events](#handled-events). Copy the endpoint's signing secret, which starts with `whsec_`, into `STRIPE_WEBHOOK_SECRET`. The route needs no CSRF exclusion and answers `200` with `{"received": true}` once the event is accepted. A store without the Store API registers its own route, as shown at the end of [The Event Journal](/3.x/payments#the-event-journal). ### Handled Events [#handled-events] The driver handles seven Stripe events: | Stripe Event | Action | Effect on the order | |--------------|--------|---------------------| | `payment_intent.amount_capturable_updated` | `Authorized` | The payment status moves to Authorized, for the amount Stripe can capture | | `payment_intent.succeeded` | `Captured` | The payment status moves to Paid, for the amount received | | `payment_intent.payment_failed` | `Failed` | On an order still pending payment, a failed transaction and `PaymentFailed` with Stripe's error message | | `payment_intent.canceled` | `Canceled` | The payment status moves to Voided, and an unpaid order that can still be cancelled moves to Cancelled | | `refund.created`, `refund.updated`, `refund.failed` with the refund status `succeeded` | `Refunded` | The pending refund is settled, or the refund is recorded, and the payment status moves to Partially refunded or Refunded | | `refund.created`, `refund.updated`, `refund.failed` with the refund status `failed` or `canceled` | `RefundFailed` | The refund is marked failed, its amount goes back to the refundable balance, and `PaymentFailed` is dispatched with Stripe's failure reason | Every other event, and a refund event with another status, such as `pending`, is ignored and still answered with `200`. Refund events let Shopper record a refund made from the Stripe Dashboard and settle the refunds Stripe has not finished, as described in [Refunds](#refunds). A refund made through Shopper is not counted twice: the event carries the Stripe refund ID and the idempotency key stored in the refund's metadata, and Shopper applies it to the refund it already recorded. Authorization and capture events also carry the `cart_id` stored in the PaymentIntent metadata, which lets Shopper find the cart of a customer who paid and left before the storefront completed it, as described in [Orphaned Payments](/3.x/payments#orphaned-payments). ### Signature Verification [#signature-verification] The driver verifies every webhook before it reads it. It needs the raw request body, passed as `_raw_body`, and the `Stripe-Signature` header, and checks the signature with the webhook secret through Stripe's PHP library. A missing body or header, or a signature that does not match, throws a `StripeException`, and the route answers `400` with `{"error": "Invalid webhook payload."}`. Without a webhook secret the driver also throws, but the Store API route answers `404` before it reaches the driver, as described in [Configuration](#configuration). A route of your own must pass the body exactly as Stripe sent it. ## Refunds [#refunds] Refund a captured payment with the processing service. The amount is in cents and can be less than the captured amount: ```php use Shopper\Payment\Services\PaymentProcessingService; $payments = resolve(PaymentProcessingService::class); $result = $payments->refund( order: $order, reference: $reference, amount: 2000, reason: 'requested_by_customer', idempotencyKey: $refundKey, ); ``` The reference is the PaymentIntent ID, which [Refunding a Payment](/3.x/payments#refunding-a-payment) shows how to read from the capture transaction, along with how to generate `$refundKey`. The `reason` goes to Stripe, which accepts `duplicate`, `fraudulent` and `requested_by_customer`: any other value makes Stripe reject the refund and the call throw a `StripeException`. Leave it `null` to send no reason. The driver creates a Stripe refund for the PaymentIntent. It sends the idempotency key of the refund, yours or the UUID the service generates without one, as the key of the Stripe request, and stores it in the refund's metadata under `idempotency_key`, so the refund events carry it back to the store. Stripe forgets a request key after 24 hours: past that delay, retrying a refund whose answer was lost and whose events have not reached the store yet creates a second refund. Shopper records both and reports the duplicate to your exception handler. Shopper reads the status of the Stripe refund from its answer: | Stripe refund status | Recorded as | Payment status | |----------------------|-------------|----------------| | `succeeded` | A successful refund | Moves to Partially refunded or Refunded | | `pending`, `requires_action` | A [pending refund](/3.x/payments#pending-refunds) | Unchanged until the refund settles | | `failed`, `canceled` | A failed refund, with Stripe's failure reason | Unchanged, and `PaymentFailed` is dispatched | A pending refund settles when the `refund.updated` event confirms it, and `refund.failed` marks it failed and gives its amount back to the refundable balance. Without the refund events, it settles only when `php artisan shopper:payments:reconcile --pull` asks Stripe for its state with the driver's `retrieveRefund()`, once it has been pending for the `--minutes` delay (15 by default), as described in [Reconciling Payments](/3.x/payments#reconciling-payments). A refund that fails after Stripe confirmed it steps the payment status back, as described in [Status Transitions](/3.x/payments#status-transitions). The service creates no `OrderRefund` record: [Order Refunds](/3.x/payments#order-refunds) shows how to keep one. When `reconciliation.orphans` is `refund`, Shopper refunds an [orphaned payment](/3.x/payments#orphaned-payments) whose cart it could not complete. That refund has no transaction for the reconcile command to check, so its failure is only known from the `refund.failed` event, which Shopper reports to your exception handler. ## Cancellation [#cancellation] Cancel an authorized payment before capture to release the hold on the customer's card. The driver cancels the PaymentIntent, no funds are collected and no refund is needed: ```php $result = $payments->cancel($order, $reference); ``` A successful cancellation moves the payment status to Voided. Cancel Order in the admin panel changes the order status only and leaves the authorization in place: cancel the payment in code, or from the Stripe Dashboard, whose `payment_intent.canceled` webhook voids it. An order whose payment never lands is cancelled by `shopper:orders:reclaim`, which releases the payment at Stripe first, as described in [Reclaiming Pending Orders](/3.x/orders#reclaiming-pending-orders). ## Testing [#testing] Stripe keeps test data apart from live data. With test keys, every call goes to your test account and no card is charged. ### Stripe Test Cards [#stripe-test-cards] Pay with Stripe's [test cards](https://docs.stripe.com/testing), with any future expiry date and any three-digit CVC: | Card Number | Scenario | |-------------|----------| | `4242 4242 4242 4242` | Successful payment | | `4000 0025 0000 3155` | Requires 3D Secure authentication | | `4000 0000 0000 9995` | Declined (insufficient funds) | | `4000 0000 0000 0002` | Declined (generic) | ### Webhook Testing [#webhook-testing] Use the Stripe CLI to forward the events of your test account to your local application: ```bash stripe listen --forward-to localhost:8000/store/webhooks/stripe ``` The CLI prints a signing secret that starts with `whsec_`. Set it as `STRIPE_WEBHOOK_SECRET` while you develop, then run a checkout with a test card: the CLI shows each event and the answer of the route. ### Test Mode [#test-mode] The driver reads its mode from the prefix of the secret key: `sk_test_` is test mode and `sk_live_` live mode. The payment methods list in the admin panel shows the mode of each method, so a store still on test keys is visible at a glance. A key with any other prefix shows no mode. Test and live webhook endpoints have their own signing secrets: change `STRIPE_WEBHOOK_SECRET` with the keys. ## Events [#events] The driver dispatches no event of its own. As Shopper applies Stripe's results, it dispatches the payment events: `OrderPaid` when a capture succeeds, `PaymentFailed` when a payment or a refund fails, with Stripe's error message or failure reason as its reason, `OrderCancelled` when Stripe cancels the payment of an unpaid order, `PaymentOrphaned` for a collected payment that still has no order, and `OrphanedPaymentRefunded` when Stripe reports a refund of a payment that has no order. [Payment Events](/3.x/events#payment-events) lists their arguments and how to listen to them. # Pricing (/3.x/pricing) Shopper sets prices per currency on [products](/3.x/products) and [product variants](/3.x/product-variants). Each price is a row of the `prices` table, attached to its product or variant through a polymorphic relationship, with at most one row per currency. Shopper never converts a price from one currency to another: a store that sells in US dollars and euros sets a USD price and an EUR price on each Classic T-Shirt. Amounts are integers in cents. The [Money](/3.x/money) page covers that convention, zero-decimal currencies and formatting; this page covers where prices live, how to read and write them, and how Shopper decides the price a customer pays. The price stored on a product is the catalog price. The cart, the checkout and the Store API never read it directly: they ask a price resolver, which returns the catalog price by default. Replacing the resolver gives you customer group prices, B2B price lists or quantity tiers without changing the cart. ## Price Model [#price-model] The model is `Shopper\Core\Models\Price`. It implements the `Shopper\Core\Models\Contracts\Price` contract and has no key in `config/shopper/models.php`, so it cannot be swapped: [Models You Cannot Swap](/3.x/models#models-you-cannot-swap) shows how to add a relationship to it. It uses `HasPublicId`, which fills the `public_id` column described in [Public IDs](/3.x/models#public-ids). ### Database Schema [#database-schema] Prices live in the `prices` table, `sh_prices` with the default [table prefix](/3.x/configuration#database-table-prefix): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | auto | Public identifier, unique | | `priceable_type` | string | no | | Morph alias of the owner: `product` or `variant` | | `priceable_id` | bigint | no | | ID of the product or variant | | `amount` | integer, unsigned | yes | null | Selling price in cents, indexed | | `compare_amount` | integer, unsigned | yes | null | Compare-at price in cents | | `cost_amount` | integer, unsigned | yes | null | Cost price in cents | | `currency_id` | bigint | no | | Foreign key to `currencies`, deleted with the currency | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | A unique index on `priceable_type`, `priceable_id` and `currency_id` allows one price per currency for each product or variant. Write prices with `updateOrCreate()` keyed on the currency, as shown in [Creating Prices](#creating-prices): a second `create()` for the same currency fails on that index. When you upgrade from 2.x, the migration that adds the index first deletes duplicate rows and keeps the one with the highest `id`. ### Price Fields [#price-fields] Each price holds three amounts, all in the currency of the price: | Field | What it represents | Shown to customers | Example | |-------|--------------------|--------------------|---------| | `amount` | The selling price | Yes | `1999` for $19.99 | | `compare_amount` | The price before a sale, shown struck through next to the selling price | Yes, as a strikethrough | `2999` for $29.99 | | `cost_amount` | What the store paid its supplier, for margin reports | No | `850` for $8.50 | A Classic T-Shirt on sale for the Summer Sale has all three: a cost of `850`, a selling price of `1999` and a compare-at price of `2999`. The storefront shows $19.99 next to a struck-through $29.99, and the margin is $11.49. The Store API never returns `cost_amount`. ### Relationships [#relationships] `priceable()` returns the product or variant that owns the price, and `currency()` returns its `Shopper\Core\Models\Currency`. The currency relationship ignores the global scope that hides disabled currencies, so a price in a disabled currency still loads its currency. The `currency_code` attribute reads the code from that relationship: ```php $price->priceable; $price->currency; $price->currency_code; ``` The [Currencies](/3.x/currencies) page covers the Currency model, enabled and disabled currencies, and the currencies a store sells in. ### Price Helper [#price-helper] `amountPrice()`, `compareAmountPrice()` and `costAmountPrice()` wrap one of the three amounts in a `Shopper\Core\Helpers\Price` object, which carries the `amount`, the `currency` and the `formatted` string. They return `null` when the amount is `null` or `0`. These methods do not pass the currency of the price to the helper, so the object is formatted in the store default currency. For a price in another currency, build the helper with the currency code of the price, as described in [Formatting Amounts](/3.x/money#formatting-amounts): ```php use Shopper\Core\Helpers\Price as PriceHelper; $selling = PriceHelper::from($price->amount, $price->currency_code); $selling->formatted; ``` ## HasPrices Trait [#hasprices-trait] `Shopper\Core\Models\Product` and `Shopper\Core\Models\ProductVariant` implement the `Shopper\Core\Contracts\Priceable` contract with the `Shopper\Core\Models\Traits\HasPrices` trait. The trait gives a model three methods: | Method | Returns | Description | |--------|---------|-------------| | `prices()` | `MorphMany` | Every price of the model, one per currency | | `getPrice(?string $currencyCode = null)` | `?Price` | The catalog price in a currency, the store default currency when no code is given | | `resolvePrice(?PricingContext $context = null)` | `?ResolvedPrice` | The price a customer pays, from the price resolver described in [Resolving Prices](#resolving-prices) | `getPrice()` reads the loaded `prices` relationship when there is one and filters it in memory, so eager-loading `prices.currency` on a listing avoids one query per product. Without a loaded relationship, it runs a query. It matches a price in a disabled currency too. Any model of yours can be priced the same way: implement `Priceable`, use `HasPrices`, and register a morph alias for it, as described in [Morph Map](/3.x/models#morph-map). ## Products and Variants [#products-and-variants] Which model holds the prices depends on the product type. A product of the `variant` type is sold through its variants: each variant has its own prices, and the prices of the product itself are not used. Every other type (`standard`, `virtual`, `external`) holds its prices on the product. The admin panel follows the same rule. It hides the Pricing tab of a variant product and shows a pricing table on each variant page instead. The Store API returns an empty `prices` array for a variant product and prices each variant, and sorting, price filters and price ranges on a variant product read the prices of its variants. The variant generator sets the price of each new variant in the store default currency; [Product Variants](/3.x/product-variants) covers variants. ## Resolving Prices [#resolving-prices] `resolvePrice()` returns the price a customer pays as a `Shopper\Core\Pricing\ResolvedPrice`, or `null` when the model has no price for the request. It asks the `Shopper\Core\Contracts\PriceResolver` bound in the container, and passes it a `Shopper\Core\Pricing\PricingContext` that describes the purchase: | Property | Type | Default | Description | |----------|------|---------|-------------| | `currencyCode` | `?string` | null | Currency to price in. `currency()` returns it, or the store default currency when it is null. | | `customerId` | `?int` | null | The customer buying, when known | | `quantity` | `int` | 1 | Quantity of the cart line | | `channelId` | `?int` | null | The sales channel of the request, as described in [Channels](/3.x/channels) | | `zoneId` | `?int` | null | The zone of the request | | `productQuantity` | `?int` | null | Quantity of the same product across every line of the cart. `productQuantity()` returns it, or `quantity` when it is null. | ```php title="app/Http/Controllers/ProductController.php" use Shopper\Core\Models\Contracts\Product; use Shopper\Core\Pricing\PricingContext; $product = resolve(Product::class)::query() ->publish() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $price = $product->resolvePrice(new PricingContext( currencyCode: 'EUR', customerId: auth()->id(), )); ``` The `ResolvedPrice` carries the result: | Property | Type | Description | |----------|------|-------------| | `amount` | `int` | Unit price to charge, in cents | | `currencyCode` | `string` | Currency of the amount | | `compareAmount` | `?int` | Compare-at price to show struck through | | `originalAmount` | `?int` | Price before the resolver changed it, for a resolver that applies its own reduction | | `meta` | `array` | Data the resolver attaches to the price | The default resolver, `Shopper\Core\Pricing\CatalogPriceResolver`, calls `getPrice()` with the currency of the context and returns its `amount` and `compare_amount`. It ignores the customer, the quantity, the channel and the zone. The cart resolves the price of a line each time the line or the cart changes, with a context built from the cart: its currency, customer, channel and zone, the line quantity and the quantity of the product across the cart. It stores the result on the line and checks it again when the order is placed, as described on the [Cart](/3.x/cart) page. ### Custom Price Resolver [#custom-price-resolver] A custom resolver implements `PriceResolver`. This one gives 10% off from 10 units of the same product in the cart, on top of the catalog price: ```php title="app/Pricing/VolumePriceResolver.php" namespace App\Pricing; use Illuminate\Database\Eloquent\Model; use Shopper\Core\Contracts\Priceable; use Shopper\Core\Contracts\PriceResolver; use Shopper\Core\Pricing\CatalogPriceResolver; use Shopper\Core\Pricing\PricingContext; use Shopper\Core\Pricing\ResolvedPrice; final class VolumePriceResolver implements PriceResolver { public function __construct( private CatalogPriceResolver $catalog, ) {} public function resolve(Priceable&Model $priceable, PricingContext $context): ?ResolvedPrice { $price = $this->catalog->resolve($priceable, $context); if ($price === null || $context->productQuantity() < 10) { return $price; } return new ResolvedPrice( amount: (int) round($price->amount * 0.9), currencyCode: $price->currencyCode, compareAmount: $price->compareAmount, originalAmount: $price->amount, meta: ['public' => ['tier' => '10+']], ); } } ``` Bind it in the `register()` method of a service provider. Shopper binds its own resolver as a singleton, and your binding replaces it: ```php title="app/Providers/AppServiceProvider.php" use App\Pricing\VolumePriceResolver; use Shopper\Core\Contracts\PriceResolver; public function register(): void { $this->app->singleton(PriceResolver::class, VolumePriceResolver::class); } ``` The cart stores the `meta` array on the cart line, in its `pricing` column. The Store API returns only the `public` key of `meta`, so keep anything a customer should not see outside that key. A resolver that queries the database for each product can implement `Shopper\Core\Contracts\PreloadsPrices` as well. Its `preload(iterable $priceables, PricingContext $context)` method receives every priceable of a cart or a Store API listing before the first `resolve()` call, so the resolver can load their prices in one query. ### Quantity Rules [#quantity-rules] A `Shopper\Core\Contracts\QuantityRuleResolver` returns the quantities a customer may buy, as a `Shopper\Core\Pricing\QuantityRule` with a `minimum`, an optional `maximum` and an `increment`. A rule of `new QuantityRule(minimum: 6, increment: 6)` sells wine by the case of 6. The constructor throws an `InvalidArgumentException` when the minimum or the increment is below 1, the minimum is not a multiple of the increment, or the maximum is below the minimum. The default `Shopper\Core\Pricing\DefaultQuantityRuleResolver` returns no rule. The cart refuses a quantity the rule does not allow with a `Shopper\Cart\Exceptions\QuantityRuleViolationException`, and the Store API returns the rule of each product. Bind your resolver the same way as a price resolver. ### Price Index [#price-index] Sorting by price, price filters and price ranges run in SQL, so they cannot call the resolver for each product. They use a `Shopper\Core\Contracts\ProductPriceIndex` instead: `minPriceExpression()` returns the SQL expression of the lowest price of a product in a currency, and `ranges()` returns the lowest and highest price of each product of a list. The default `Shopper\Core\Pricing\CatalogProductPriceIndex` reads the catalog prices and skips prices without an amount. A custom resolver that changes prices does not change the index: when listings must sort and filter on the resolved prices, bind your own `ProductPriceIndex` as well. ## Configuration [#configuration] Pricing has no feature flag and no config key. Shopper binds its three pricing services as singletons in `Shopper\Core\CoreServiceProvider`: | Contract | Default implementation | |----------|------------------------| | `Shopper\Core\Contracts\PriceResolver` | `Shopper\Core\Pricing\CatalogPriceResolver` | | `Shopper\Core\Contracts\QuantityRuleResolver` | `Shopper\Core\Pricing\DefaultQuantityRuleResolver` | | `Shopper\Core\Contracts\ProductPriceIndex` | `Shopper\Core\Pricing\CatalogProductPriceIndex` | Two store settings decide which currencies a merchant prices in: `currencies` lists the currencies of the store, and the admin price form shows one row for each; `default_currency_id` is the store default currency that `getPrice()` and `PricingContext` fall back to. The [Settings](/3.x/settings) page lists both keys. ## Creating Prices [#creating-prices] Create or update a price through the `prices()` relationship of a product or a variant, keyed on the currency so a second call updates the row instead of failing on the unique index: ```php title="database/seeders/CatalogSeeder.php" use Shopper\Core\Models\Contracts\Product; use Shopper\Core\Models\Currency; $product = resolve(Product::class)::query() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $product->prices()->updateOrCreate( ['currency_id' => Currency::query()->where('code', 'USD')->value('id')], [ 'amount' => 1999, 'compare_amount' => 2999, 'cost_amount' => 850, ], ); ``` ### Multi-Currency Pricing [#multi-currency-pricing] To set prices in several currencies at once, call `Shopper\Actions\Store\Product\SavePricingAction`, the action the admin price form uses. It takes an array keyed by currency ID and runs `updateOrCreate()` for each entry: ```php use Shopper\Actions\Store\Product\SavePricingAction; app()->call(SavePricingAction::class, [ 'model' => $product, 'pricing' => [ $usdCurrencyId => [ 'amount' => 2999, 'compare_amount' => 3999, 'cost_amount' => 850, ], $eurCurrencyId => [ 'amount' => 2799, 'compare_amount' => 3799, 'cost_amount' => 800, ], ], ]); ``` The action skips an entry whose `amount` is empty or `0`, and never deletes a price: to remove the EUR price of a product, delete its row with `$product->prices()->where('currency_id', $eurCurrencyId)->delete()`. The action ships with the admin panel package, `shopper/framework`. A [CSV import](/3.x/import) sets prices too, from the `price`, `compare_at_price`, `cost_per_item` and `currency` columns of each row. ## Retrieving Prices [#retrieving-prices] `getPrice()` returns the catalog price of a product in the store default currency, or in the currency you pass. Format its amounts with the currency of the price: ```blade title="resources/views/products/show.blade.php" @php($price = $product->getPrice('EUR')) @if ($price)

    {{ shopper_money_format($price->amount, $price->currency_code) }} @if ($price->compare_amount) {{ shopper_money_format($price->compare_amount, $price->currency_code) }} @endif

    @endif ``` On a listing, eager-load the prices with their currency, so `getPrice()` filters the loaded rows without a query per product: ```php title="app/Http/Controllers/ProductController.php" use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::query() ->publish() ->with('prices.currency') ->paginate(12); ``` `getPrice()` returns the price the merchant entered. To show the price the cart will charge, call `resolvePrice()` with the context of the customer, as described in [Resolving Prices](#resolving-prices). ## Events [#events] Prices dispatch no event. Saving prices from the admin panel or generating variants writes the `prices` table without an event. A CSV import dispatches `ProductCreated` for each product it creates, once the transaction that also writes its prices is committed, as listed in [Product Events](/3.x/events#product-events). ## Permissions [#permissions] The Pricing tab of a product and its actions check `products.edit`. Adding, editing or deleting the prices of a variant checks `products.edit` and `products.variants.edit`. The [Permissions](/3.x/acl#access-by-section) page lists the permissions of each section. ## In the Admin [#in-the-admin] The Pricing tab of a product, and the pricing table of each variant page, list one price per currency with its amount, compare-at price and cost. The form shows one row per store currency when you add prices, only the row's currency when you edit one, and saves through `SavePricingAction`. The tab is the `product-pricing` page, the table the `products.pricing` component and the form the `slide-overs.manage-pricing` component of `config/shopper/components/product.php`, which `php artisan shopper:component:publish product` copies to your application. The [User Guide](/3.x/user-guide) shows how merchants set prices, and [Admin Forms and Tables](/3.x/money#admin-forms-and-tables) the money fields and columns. ## From a Storefront [#from-a-storefront] The Store API returns the prices of a product on `GET /store/products` and `GET /store/products/{slug}`, and the prices of each variant when the request includes `variants`. Every price-aware value of a response uses one currency: the `filter[currency]` parameter of the request, then the currency of the zone of the request, then the store default currency. The response repeats that code in `meta.currency`. An unknown or disabled currency in `filter[currency]` answers `422` with the `currency_unknown` code. ```json { "data": { "id": "01JD3XQ5Z8K2M4N6P8R0T2V4W6", "type": "products", "attributes": { "name": "Classic T-Shirt", "price_range": { "currency_code": "EUR", "min": 2499, "max": 2499 }, "prices": [ { "public_id": "01JD3XR2A4C6E8G0J2L4N6Q8S0", "amount": 2999, "compare_amount": 3999, "currency_code": "USD" }, { "public_id": "01JD3XR2A4C6E8G0J2L4N6Q8S1", "amount": 2499, "compare_amount": null, "currency_code": "EUR" } ], "calculated_price": { "amount": 2499, "compare_amount": null, "original_amount": null, "currency_code": "EUR", "meta": null }, "quantity_rule": null } }, "meta": { "currency": "EUR" } } ``` | Attribute | Content | |-----------|---------| | `prices` | Every catalog price in an enabled currency, without `cost_amount`. Empty on a variant product. | | `calculated_price` | The `ResolvedPrice` from the price resolver in the request currency, with the `public` key of its `meta`. Null when the product has no price in that currency. Absent on a variant product, whose variants carry it on `GET /store/products/{slug}?include=variants`. | | `quantity_rule` | The `minimum`, `maximum` and `increment` from the quantity rule resolver, or null | | `price_range` | The lowest and highest price of the product in the request currency, from its variants for a variant product | Listings sort with `sort=price` or `sort=-price` and filter with `filter[price_min]` and `filter[price_max]`, in cents of the request currency. Both leave out products without a price in that currency. `include=price_range` adds `meta.price_range`, the lowest and highest price of the whole listing. When no currency resolves, a price sort or filter answers `422` with the `currency_required` code. The resolver receives the customer of the bearer token, so a response with calculated prices carries `Vary: Authorization`. [Amounts in the Store API](/3.x/money#amounts-in-the-store-api) covers the amounts of the other resources, and the Store API [Catalog](/3.x/store-api/catalog#prices-currency-and-stock) guide the product prices. # Product Tags (/3.x/product-tags) Tags are flat labels you attach to products: a season such as "Summer 2026", a campaign such as "Flash Sale", or a storefront badge such as "New Arrival" or "Best Seller". [Categories](/3.x/categories) form a tree and [collections](/3.x/collections) group products by hand or by rules. A tag has no parent and no rule, and a merchant can create one from the product form without leaving the product. A storefront uses tags to filter a listing, to show a badge on a product card, or to build a landing page for a campaign. A product can carry any number of tags. ## Model [#model] The model is `Shopper\Core\Models\ProductTag`. It has no contract and no key in `config/shopper/models.php`, so it cannot be swapped: [Models You Cannot Swap](/3.x/models#models-you-cannot-swap) shows how to add a relationship to it. Its morph alias is `product_tag`. Two traits change how you create and find tags: - `HasSlug` turns the `slug` you assign into a URL-safe, unique value, as described in [Slug Generation](#slug-generation). - `HasPublicId` fills the `public_id` column, the identifier the Store API returns, as described in [Public IDs](/3.x/models#public-ids). ## Database Schema [#database-schema] Tags live in their own table and reach products through the pivot table that products share with categories, collections, channels and related products. The table names below leave out the `sh_` [table prefix](/3.x/configuration#database-table-prefix). ### Tags Table [#tags-table] The `product_tags` table holds one row per tag: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | auto | Public identifier, unique | | `name` | string | no | | Tag name shown to customers | | `slug` | string | yes | null | URL-safe identifier, unique | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Pivot Table [#pivot-table] Tags use the polymorphic `product_has_relations` table. A row links a product to a tag, a category, a collection, a channel or a related product, told apart by `productable_type`: | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `product_id` | bigint | no | Foreign key to `products`, deleted with the product | | `productable_type` | string | no | Morph alias of the related model, `product_tag` for a tag | | `productable_id` | bigint | no | ID of the tag | The table has no unique constraint: `attach()` called twice with the same tag adds a second row. Use `sync()` or `syncWithoutDetaching()` to attach tags. Deleting a tag removes its row from `product_tags` but leaves its rows in `product_has_relations`; detach the products first if you delete tags from code. ## Slug Generation [#slug-generation] `HasSlug` runs the value you assign to `slug` through `Str::slug()`, then appends `-1`, `-2` and so on while another tag already uses it. The tag being updated is left out of that check, so saving a tag with its own slug keeps it. The slug is not derived from the name: pass one when you create a tag, or the column stays `null`: `findBySlug()` cannot find the tag and the `tag` scope finds it only by its public ID. ```php use Shopper\Core\Models\ProductTag; $first = ProductTag::query()->create(['name' => 'New Arrival', 'slug' => 'New Arrival']); $second = ProductTag::query()->create(['name' => 'New Arrivals', 'slug' => 'new-arrival']); $first->slug; $second->slug; ``` The first tag gets `new-arrival` and the second `new-arrival-1`. `ProductTag::findBySlug()` returns the tag with a given slug and throws a `ModelNotFoundException` when there is none, which Laravel turns into a 404: ```php $tag = ProductTag::findBySlug('summer-2026'); ``` ## Relationships [#relationships] A tag and a product are linked in both directions through `product_has_relations`. ### Products [#products] `products()` on a tag is a `morphToMany` relationship to the product model set in `config('shopper.models.product')`, so a swapped product model is returned. `tags()` on a product is the inverse `morphedByMany` relationship: ```php $tag->products; $tag->products()->count(); $tag->products()->syncWithoutDetaching([$classicTee->id, $runningShorts->id]); $tag->products()->detach($classicTee->id); $product->tags; $product->tags()->sync([$summerTag->id, $newArrivalTag->id]); ``` `sync()` replaces every tag of the product with the given IDs, and `syncWithoutDetaching()` adds the given tags and keeps the others. ## Configuration [#configuration] Tags have no config key and no model to swap. The `tag` feature flag turns their admin screens on and off. ### Disabling Tags [#disabling-tags] Tags are enabled by default. To remove them from the admin panel, set the `tag` flag to disabled in `config/shopper/features.php`: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'tag' => FeatureState::Disabled, ]; ``` When the flag is disabled, the Tags item leaves the sidebar, the `shopper.tags.index` route is not registered, and the Tags field leaves the product form. The flag only affects the admin panel: the `ProductTag` model, the `tag` scope and the Store API keep working, so a storefront still lists tags and filters products by tag. ## Creating Tags [#creating-tags] Create a tag with a name and a slug, then attach it to products: ```php title="database/seeders/CatalogSeeder.php" use Shopper\Core\Models\ProductTag; $tag = ProductTag::query()->create([ 'name' => 'Summer 2026', 'slug' => 'summer-2026', ]); $tag->products()->syncWithoutDetaching([$classicTee->id, $linenShirt->id]); ``` Merchants can also create a tag from the Tags field of the product form, without leaving the product. A [CSV import](/3.x/import) reads a `tags` column with comma-separated tag names: it attaches the tag with the same name when one exists, creates the others with a slug made from the name, and keeps the tags the product already has. ## Retrieving Tags [#retrieving-tags] List tags in alphabetical order with the number of published products in each: ```php use Shopper\Core\Models\ProductTag; $tags = ProductTag::query() ->withCount(['products' => fn ($query) => $query->publish()]) ->orderBy('name') ->get(); ``` Find a tag by its slug and page through its published products: ```php $tag = ProductTag::findBySlug('summer-2026'); $products = $tag->products() ->publish() ->with('prices.currency') ->paginate(12); ``` On a product listing, eager-load `tags` so each product card can show its badges without a query per product: ```php use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::query() ->publish() ->with('tags') ->paginate(12); ``` ## Storefront Example [#storefront-example] This controller serves a page that lists the tags of the store and a page per tag with its published products: ```php title="app/Http/Controllers/TagController.php" namespace App\Http\Controllers; use Illuminate\Contracts\View\View; use Shopper\Core\Models\ProductTag; final class TagController extends Controller { public function index(): View { $tags = ProductTag::query() ->withCount(['products' => fn ($query) => $query->publish()]) ->orderBy('name') ->get(); return view('tags.index', ['tags' => $tags]); } public function show(string $slug): View { $tag = ProductTag::findBySlug($slug); $products = $tag->products() ->publish() ->with('prices.currency') ->paginate(12); return view('tags.show', ['tag' => $tag, 'products' => $products]); } } ``` ### Filtering Products by Tags [#filtering-products-by-tags] The `tag` scope of the product model keeps the products that carry at least one of the given tags. It accepts slugs or public IDs, as one value, several arguments or an array: ```php use Shopper\Core\Models\Contracts\Product; $summer = resolve(Product::class)::query() ->publish() ->tag('summer-2026') ->get(); $highlights = resolve(Product::class)::query() ->publish() ->tag(['new-arrival', 'best-seller']) ->paginate(12); ``` Each call to the scope adds its own condition, so chaining two calls keeps the products that carry both tags: ```php $products = resolve(Product::class)::query() ->publish() ->tag('summer-2026') ->tag('best-seller') ->get(); ``` ## Events [#events] Creating, renaming or deleting a tag dispatches no event. Saving the main product form, where the tags of a product change, dispatches `ProductUpdated`, as listed in [Product Events](/3.x/events#product-events). The event is dispatched before the form saves the tags, so a listener that runs during the request reads the previous tags. ## Permissions [#permissions] The seeder creates `tags.browse`, `tags.read`, `tags.create`, `tags.edit` and `tags.delete` in the Products group. The tag list checks `tags.browse`, and its actions check `tags.create`, `tags.edit` and `tags.delete`. The admin panel never checks `tags.read`. The Tags item of the sidebar shows to users with `products.browse` or `tags.browse`, while the page itself requires `tags.browse`. Creating a tag from the product form needs only `products.edit`, the permission of the product form. The [Permissions](/3.x/acl#access-by-section) page lists the permissions of each section. ## In the Admin [#in-the-admin] The Tags page sits under Products in the sidebar. It lists tags with their name, slug and creation date, searches by name and slug, and creates or edits a tag in a modal with a slug generated from the name. The product form has a Tags field that selects existing tags and creates new ones. The page is the `tag-index` key of `config/shopper/components/product.php`, which `php artisan shopper:component:publish product` copies to your application. The [User Guide](/3.x/user-guide) shows how merchants manage tags. ## From a Storefront [#from-a-storefront] `GET /store/tags` returns a paginated list of the tags of the store with their `name`, `slug`, `created_at` and `updated_at`, and their public ID as `id`. It filters by name with `filter[name]` (a partial match), sorts with `sort=name`, and with `include=products` returns the published products of each tag, restricted to the channel of the request when one is resolved. The JavaScript SDK calls it with `tag.list()`. There is no endpoint for a single tag. ```json { "data": [ { "id": "01JD3XS4B6D8F0H2K4M6P8R0T2", "type": "tags", "attributes": { "name": "Summer 2026", "slug": "summer-2026", "created_at": "2026-05-02T09:14:00+00:00", "updated_at": "2026-05-02T09:14:00+00:00" } } ] } ``` To list the products of a tag, call `GET /store/products?filter[tag]=summer-2026`. The filter uses the `tag` scope, so it takes a slug or a public ID, and a comma-separated list keeps the products that carry any of them. `include=tags` on `GET /store/products` and `GET /store/products/{slug}` returns the tags of each product. The Store API [Catalog](/3.x/store-api/catalog#tags) guide covers the tag endpoints, and the [JSON:API](/3.x/store-api/json-api) page the pagination and the includes. # Product Variants (/3.x/product-variants) A product variant is one version of a product that a customer can buy. A Classic T-Shirt sold in Blue and Red, in sizes S, M and L, has six variants: Blue / S, Blue / M, Blue / L, Red / S, Red / M and Red / L. The product holds what they share (name, description, images, brand, categories, channels), and each variant holds its own SKU, barcode, prices, stock, images and shipping dimensions. Customers buy variants. A cart line, an order item and a stock movement point to the variant, and the product groups the variants on the storefront. ## How Variants Work [#how-variants-work] A product has variants when its type is `variant` (`Shopper\Core\Enum\ProductType::Variant`). `$product->canUseVariants()` returns `true` for that type only, and the admin panel shows the Variants section of the product editor for it. Each level holds its own data: | Level | Example | What it holds | |-------|---------|---------------| | Product | Classic T-Shirt | Name, description, images, brand, categories, channels, SEO fields | | Option | Color, Size | The attributes attached to the product | | Option value | Blue, Red, S, M, L | The attribute values selected on the product | | Variant | Blue / M | SKU, barcode, prices, stock, images, dimensions, and one value per option | Options are attributes. The values selected on a product for its Checkbox, ColorPicker and Select attributes, stored in `sh_attribute_product`, are the options of its variants. Text, Number, RichText and DatePicker attributes never take part in the combinations. The [Attributes](/3.x/attributes) page covers field types and attaching attributes to a product. A variant knows its combination through `sh_attribute_value_product_variant`, a pivot that links it to one attribute value per option: Blue / M is the variant linked to Color = Blue and Size = M. A storefront reads that pivot to find the variant matching what a customer selects, as shown in [Retrieving Variants](#retrieving-variants). Prices and stock live on each variant. The Store API refuses to add a variant product itself to a cart and answers with the `variant_required` error code. ## Model [#model] The model configured for variants is `Shopper\Models\ProductVariant`. It extends `Shopper\Core\Models\ProductVariant`, which implements the `Shopper\Core\Models\Contracts\ProductVariant` contract. The contract extends `Shopper\Core\Models\Contracts\Stockable`, and the core class also implements `Shopper\Core\Contracts\Priceable`, which is what lets a cart hold a variant. The core class holds the columns, the relationships, stock, prices and dimensions; the admin class adds the Spatie Media Library methods and the image conversions, as described in [Core Models and Admin Models](/3.x/models#core-models-and-admin-models). Five traits of the core class change what you can do with a variant: - `HasStock` gives each variant its own stock at each inventory location, described in [Stock Management](#stock-management). - `HasPrices` attaches one price per currency, described in [Pricing](#pricing). - `HasMediaCollections` declares the image and thumbnail collections described in [Media](#media). - `HasDimensions` formats the weight and the sizes used for shipping, described in [Dimensions](#dimensions). - `HasPublicId` fills `public_id` with a ULID when the variant is created. The Store API returns it as the variant `id`, and a cart line takes it as `purchasable_id`. The morph alias of the model is `variant`. Cart lines, order items, prices and stock movements store `variant` in their type column, as described in [Morph Map](/3.x/models#morph-map). ### Extending the Model [#extending-the-model] To add your own methods, extend the admin class: ```php title="app/Models/ProductVariant.php" product->name.' / '.$this->name; } } ``` Then point the `variant` key of the configuration to your class: ```php title="config/shopper/models.php" 'variant' => App\Models\ProductVariant::class, ``` Extend the admin class `Shopper\Models\ProductVariant`: the admin panel reads the variant images through its media methods, and `ProductVariantObserver` calls `media()` when a variant is deleted. The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ## Database Schema [#database-schema] Variants use two tables: `sh_product_variants` for the variants and `sh_attribute_value_product_variant` for their option values (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)). ### Product Variants Table [#product-variants-table] The `sh_product_variants` table holds one row per variant: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Variant name, such as `Blue / M`, indexed | | `sku` | string | yes | null | Stock keeping unit, unique within the product | | `barcode` | string | yes | null | Barcode, unique | | `ean` | string | yes | null | European Article Number, unique | | `upc` | string | yes | null | Universal Product Code, unique | | `allow_backorder` | boolean | no | `false` | Accept orders when the stock does not cover the quantity | | `position` | unsigned integer | no | `1` | Order among the variants of the product | | `product_id` | bigint | yes | null | Parent product, set to null when the product row is deleted | | `weight_unit` | string | no | `kg` | Weight unit | | `weight_value` | decimal(10,2) | yes | `0.00` | Weight | | `height_unit` | string | no | `cm` | Height unit | | `height_value` | decimal(10,2) | yes | `0.00` | Height | | `width_unit` | string | no | `cm` | Width unit | | `width_value` | decimal(10,2) | yes | `0.00` | Width | | `depth_unit` | string | no | `cm` | Depth unit | | `depth_value` | decimal(10,2) | yes | `0.00` | Depth | | `volume_unit` | string | no | `l` | Volume unit | | `volume_value` | decimal(10,2) | yes | `0.00` | Volume | | `metadata` | json | yes | null | Custom key-value data | | `created_at` | timestamp | yes | null | Creation date | | `updated_at` | timestamp | yes | null | Last update | The SKU is unique per product, through a unique index on the `product_id` and `sku` pair, so two products can each have a `BLUE-M` variant. `barcode`, `ean` and `upc` are unique across the whole table. Products are soft deleted, so deleting a product keeps its variants. A force delete removes the product row and the foreign key sets `product_id` to null on its variants, which stay in the table with their prices and stock. Delete the variants first when you force delete a product. ### Attribute Value Pivot Table [#attribute-value-pivot-table] The `sh_attribute_value_product_variant` table links a variant to its option values: | Column | Type | Nullable | Description | |--------|------|----------|-------------| | `id` | bigint | no | Primary key | | `value_id` | bigint | no | The attribute value (`sh_attribute_values`) | | `variant_id` | bigint | no | The variant | Both foreign keys cascade: deleting a variant or an attribute value deletes its pivot rows. The table has no unique index on the pair, so write it with `sync()`: `attach()` adds a second row for a value that is already linked. ## Relationships [#relationships] A variant belongs to one product and to one attribute value per option. ### Product [#product] `product()` returns the parent product, from the class configured under `shopper.models.product`: ```php $variant->product->name; ``` The inverse, `$product->variants`, returns the variants of a product ordered by `position`. ### Attribute Values [#attribute-values] `values()` returns the `Shopper\Core\Models\AttributeValue` records of the variant. Load their attribute to show the option names: ```php use Shopper\Core\Models\AttributeValue; $variant->load('values.attribute'); $options = $variant->values->mapWithKeys( fn (AttributeValue $value): array => [$value->attribute->name => $value->value], ); ``` For the Blue / M variant, `$options` holds `['Color' => 'Blue', 'Size' => 'M']`. To change the combination of a variant, sync its values: ```php $variant->values()->sync([$blue->id, $medium->id]); ``` ## Stock Management [#stock-management] Each variant has its own stock through the `HasStock` trait, and `tracksInventory()` always returns `true` for a variant. Stock works as on a product: each movement is a row of the `sh_inventory_histories` ledger, and `sh_stock_levels` keeps the current quantity at each location. The [Products](/3.x/products) page describes every stock method, and the [Locations](/3.x/locations) page covers stock spread over several locations. ### Querying Stock [#querying-stock] The `stock` attribute returns the quantity across every location. `inStock()` takes the quantity a customer wants, `1` by default: ```php $variant->stock; $variant->inStock(3); $variant->stockInventory($warehouse->id); $variant->getStock('2026-01-15'); ``` `stockInventory()` returns the stock at one location, and `getStock()` with a date replays the ledger up to that date. On the product, `$product->variants_stock` adds up the stock of every variant. ### Modifying Stock [#modifying-stock] Every write takes the location it applies to. `mutateStock()` adds stock and `decreaseStock()` removes it: ```php use Shopper\Core\Models\Contracts\Inventory; use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $variant = $product->variants()->where('sku', 'TS-BLUE-M')->firstOrFail(); $warehouse = resolve(Inventory::class)::query()->default()->firstOrFail(); $variant->mutateStock( inventoryId: $warehouse->id, quantity: 40, event: 'Shipment received', ); $variant->decreaseStock( inventoryId: $warehouse->id, quantity: 2, event: 'Damaged in storage', ); ``` `setStock()` compares the quantity you pass with the total stock of the variant across every location, and writes the difference to the location you pass. On a store with one location, that sets the stock; on a store with several, use `mutateStock()` with a difference computed from `stockInventory()`. `clearStock()` deletes every ledger row and every stock level of the variant, at every location. ### Backorder [#backorder] `allow_backorder` lets customers order a variant whose stock does not cover the quantity. `inStock()` ignores the flag, while the cart skips its stock check for a variant that allows backorders and the Store API reports `in_stock: true` for it. Check both in your own code: ```php $canBuy = $variant->allow_backorder || $variant->inStock($quantity); ``` When the order is placed, a backordered quantity is taken from a single location, the first one returned by the inventory resolver, and the stock there can go below zero. ### Avoiding N+1 Queries [#avoiding-n1-queries] Reading `$variant->stock` runs one query, so a product page that shows the stock of each variant runs one query per variant, and so does `variants_stock`. `loadCurrentStock()` loads the stock of a whole collection in one query: ```php use Shopper\Core\Models\Contracts\ProductVariant; resolve(ProductVariant::class)::loadCurrentStock($product->variants); $product->variants_stock; ``` `loadStockForInventory($variants, $warehouse->id)` does the same for one location. The `preventLazyStockLoading()` switch that the Products page describes is set per model: `Product::preventLazyStockLoading()` does not cover variants. Turn it on for variants only while you profile a page, because the cart reads the stock of the variant it adds without loading it in bulk, and `CartManager::add()` then throws `Shopper\Core\Exceptions\LazyStockLoadingException`. ## Pricing [#pricing] Each variant has its own prices through the `HasPrices` trait, one row of `sh_prices` per currency, with amounts in cents as described in [Amounts in Cents](/3.x/money#amounts-in-cents): ```php use Shopper\Core\Models\Currency; $variant->prices()->updateOrCreate( ['currency_id' => Currency::query()->where('code', 'USD')->value('id')], ['amount' => 2999, 'compare_amount' => 3499], ); $variant->getPrice()?->amount; $variant->getPrice('EUR')?->amount; ``` `getPrice()` without a code reads the store currency, and `resolvePrice()` returns the price the cart charges, as computed by the price resolver. The [Pricing](/3.x/pricing) page covers the price columns, multi-currency pricing and the price resolver. ## Media [#media] Each variant has its own images, in two collections declared by the core class. The collection names come from the media configuration: | Collection | Config key | Default name | Files | Use | |------------|------------|--------------|-------|-----| | Images | `shopper.media.storage.collection_name` | `uploads` | Several | The gallery of the variant | | Thumbnail | `shopper.media.storage.thumbnail_collection` | `thumbnail` | One | The main image of the variant | Both collections use the disk set by `shopper.media.storage.disk_name` (`public` by default) and accept the MIME types of `shopper.media.accepts_mime_types`. Each image gets the conversions of `shopper.media.conversions`: `large` (800 by 800) and `medium` (500 by 500). ```php $variant->addMedia($request->file('image')) ->toMediaCollection(config('shopper.media.storage.collection_name')); $variant->addMedia(storage_path('app/imports/classic-t-shirt-blue.jpg')) ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); $variant->getThumbnailUrl('medium'); $variant->getMedia(config('shopper.media.storage.collection_name')); ``` `getThumbnailUrl()` returns the thumbnail, or else the first image of the gallery, or else the placeholder image of the admin panel. It never falls back to the images of the product: when a variant has no image of its own, read `$variant->product->getThumbnailUrl('medium')` instead. The [Media](/3.x/media) page covers storage and conversions. ## Dimensions [#dimensions] Each variant has its own weight, height, width, depth and volume, stored as a value and a unit, so a carrier can rate a Red / L heavier than a Blue / S. The `weight`, `height`, `width`, `depth` and `volume` attributes return the value and the unit as one string: ```php $variant->weight; ``` A variant with a `weight_value` of 250 and a `weight_unit` of `g` returns `250.00 g`. The attributes return null only when the value column is null; a variant created without dimensions holds the `0.00` defaults and returns `0.00 kg`. Compare `weight_value` with zero to know whether a weight was entered. ### Dimension Enums [#dimension-enums] The unit columns are cast to enums: | Enum | Columns | Cases | |------|---------|-------| | `Shopper\Core\Enum\Dimension\Weight` | `weight_unit` | `KG` (`kg`), `G` (`g`), `LBS` (`lbs`) | | `Shopper\Core\Enum\Dimension\Length` | `height_unit`, `width_unit`, `depth_unit` | `M` (`m`), `CM` (`cm`), `MM` (`mm`), `FT` (`ft`), `IN` (`in`) | | `Shopper\Core\Enum\Dimension\Volume` | `volume_unit` | `L` (`l`), `ML` (`ml`), `GAL` (`gal`), `FLOZ` (`floz`) | ```php use Shopper\Core\Enum\Dimension\Weight; $variant->update([ 'weight_unit' => Weight::LBS, 'weight_value' => 0.55, ]); ``` ## SKU and Barcode [#sku-and-barcode] A variant carries four identifiers. The `sku` is your own reference, unique within its product. The `barcode`, `ean` and `upc` are unique across every variant of the store. The admin panel edits the SKU and the barcode, from the Add variant slide-over and from the variant page: it refuses a SKU used by another variant of the same product, and accepts letters, digits and hyphens in a barcode. It has no field for `ean` and `upc`; set them in code or through a CSV [import](/3.x/import). The variant generator proposes a SKU for each new combination: the product SKU followed by the option values in upper case, joined by hyphens. A Classic T-Shirt with the SKU `TS` gets `TS-BLUE-M` for its Blue / M variant, and a product without a SKU gets `BLUE-M`. The variant page draws the barcode with the `milon/barcode` package, in the symbology set by `shopper.core.barcode_type`: `C128` (Code 128) by default. Set it to `EAN13` or `UPCA` when your barcodes follow those standards: ```php title="config/shopper/core.php" 'barcode_type' => 'EAN13', ``` The search index stores the SKUs of the variants with their product, in the `skus` field, so a search for `TS-BLUE-M` finds the Classic T-Shirt. Shopper reindexes the product when a variant is created or deleted, or when its SKU changes. The [Search](/3.x/search) page covers indexing. ## Generating Variant Combinations [#generating-variant-combinations] A product with three colors and three sizes needs nine variants. The Generate variants slide-over of the admin panel builds every combination of the option values selected on the product. It reads the options with `MapProductOptions`, builds the combinations with `Arr::permutate()`, matches each combination with the existing variant that holds its values, and lists them with an editable name, SKU, price and stock. Merchants remove the combinations they do not sell, then save the list with `SaveProductVariantsAction`. - A combination held by an existing variant keeps that variant, with its SKU, price and stock. - A new combination gets a name made of its values, such as `Blue / M`, and the SKU described in [SKU and Barcode](#sku-and-barcode). - A variant whose combination is removed from the list is deleted on save. - When you add an option to a product that already has variants, each variant keeps its ID and takes the first new combination that contains its values. The other combinations become new variants. The price field takes an amount in cents and saves it in the store default currency. The Generate button appears once the product has at least one attribute, of any type. ### Permutation Helpers [#permutation-helpers] `Shopper\Core\Macros\Arr` builds the combinations of option values. Each option is a list of values, keyed by the option name: ```php use Shopper\Core\Macros\Arr; $options = [ 'Color' => [ ['id' => 1, 'value' => 'Blue'], ['id' => 2, 'value' => 'Red'], ], 'Size' => [ ['id' => 4, 'value' => 'M'], ['id' => 5, 'value' => 'L'], ], ]; $combinations = Arr::permutate($options); $name = Arr::performPermutationIntoWord($combinations[0], 'value'); $valueIds = Arr::getPermutationIds($combinations[0]); ``` `permutate()` returns the four combinations Blue / M, Blue / L, Red / M and Red / L, each keyed by option name: the first one is `['Color' => ['id' => 1, 'value' => 'Blue'], 'Size' => ['id' => 4, 'value' => 'M']]`. `performPermutationIntoWord()` joins one field of a combination into `Blue / M`, and takes the separator as a third argument (`'-'` gives `Blue-M`). `getPermutationIds()` returns `[1, 4]`, the attribute value IDs to sync on the variant. `permutate()` returns an empty array when there is no option, and throws an `InvalidArgumentException` when an option has no values. ### Bulk Save with SaveProductVariantsAction [#bulk-save-with-saveproductvariantsaction] `Shopper\Actions\Store\Product\SaveProductVariantsAction` saves the whole list of variants of a product in one transaction, then reindexes the product. Each entry takes the keys `variant_id`, `name`, `sku`, `price` (in cents, in the store default currency), `stock` and `values` (the attribute value IDs): ```php use Shopper\Actions\Store\Product\SaveProductVariantsAction; $variants = app()->call(SaveProductVariantsAction::class, [ 'product' => $product, 'variants' => [ [ 'variant_id' => null, 'name' => 'Blue / M', 'sku' => 'TS-BLUE-M', 'price' => 2999, 'stock' => 50, 'values' => [1, 4], ], [ 'variant_id' => null, 'name' => 'Blue / L', 'sku' => 'TS-BLUE-L', 'price' => 2999, 'stock' => 30, 'values' => [1, 5], ], ], ]); ``` The action returns the list with `variant_id` filled in. It deletes every variant of the product whose ID is not in the list, so a list without any `variant_id` replaces all the variants. An entry with a `variant_id` keeps the name and the SKU of that variant; the action only writes its price, stock and values. A price of 0 leaves the prices untouched, and a price above 0 keeps the existing compare price only when it is higher than the new price. For each entry with a `stock` above 0, the action calls `clearStock()` on the variant, which deletes its stock history and its stock at every location, then records the quantity at the default location. Pass a `stock` of 0 for the existing variants whose stock must not change. ### MapProductOptions [#mapproductoptions] `Shopper\Helpers\MapProductOptions::generate()` returns the options of a product with the values selected on it, and skips the attributes with a free-value type. Each option has the shape `['id' => 3, 'key' => 'attribute_3', 'name' => 'Color', 'values' => [...]]`, and each value `['id' => 1, 'key' => 'value_1', 'value' => 'Blue']`. Key the options by name to feed them to `Arr::permutate()`: ```php use Shopper\Core\Macros\Arr; use Shopper\Helpers\MapProductOptions; $options = collect(MapProductOptions::generate($product)) ->mapWithKeys(fn (array $option): array => [$option['name'] => $option['values']]) ->all(); $combinations = Arr::permutate($options); ``` ## Variants in Carts and Orders [#variants-in-carts-and-orders] A cart line holds a variant through its `purchasable_type` (`variant`) and `purchasable_id` columns. Add a variant with `CartManager`: ```php use Shopper\Cart\CartManager; use Shopper\Cart\Facades\Cart; $cart = Cart::current() ?? Cart::create(); $line = resolve(CartManager::class)->add($cart, $variant, quantity: 2); ``` Adding the same variant again raises the quantity of its line. The cart checks the stock of the variant unless it allows backorders, and throws `Shopper\Cart\Exceptions\InsufficientStockException` when the stock is short. The pricing context that the cart passes to the price resolver counts the lines of every variant of a product together: with two Blue / M and three Red / L in the cart, `productQuantity()` returns 5 on both lines. The default resolver ignores it; a custom resolver uses it for quantity tiers on the whole product, as the [Pricing](/3.x/pricing) page shows. `CartManager` does not check that the parent product is published, and it accepts a variant product itself; the Store API checks both before it calls the cart. The [Cart](/3.x/cart) page covers carts. When the cart becomes an order, each line becomes an order item that keeps a copy of the variant at that moment: - `name` joins the product name and the variant name: `Classic T-Shirt / Blue / M`. - `sku` copies the variant SKU. - `product_type` holds `variant` and `product_id` the variant ID, so `$item->product` returns the variant. The order then reserves the stock of each variant, across the locations that hold it, with ledger rows labeled "Reserved for order" that reference the order. When a variant without backorders no longer has the stock, the order is not created and `InsufficientStockException` is thrown. The [Orders](/3.x/orders) page covers order items. ## Configuration [#configuration] Variants have no feature flag in `features.php`: the Variants section appears on every product of the `variant` type. Options come from attributes, so the `attribute` feature must stay enabled for merchants to choose options in the admin panel. The model is swapped with the `variant` key of `config/shopper/models.php`, as shown in [Extending the Model](#extending-the-model), and the images follow the media keys listed in [Media](#media). The barcode symbology is set by `shopper.core.barcode_type`. ### Components [#components] The variant screens of the admin panel belong to the product section. To replace one with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish product ``` The command creates `config/shopper/components/product.php`. These are its variant entries: ```php title="config/shopper/components/product.php" use Shopper\Livewire; use Shopper\Livewire\Components; use Shopper\Navigation\Product\Sections; return [ 'sections' => [ Sections\VariantsSection::class => true, ], 'pages' => [ 'product-variants' => Livewire\Pages\Product\Variants::class, 'variant-edit' => Livewire\Pages\Product\Variant::class, ], 'components' => [ 'products.variant-stock' => Components\Products\VariantStock::class, 'slide-overs.add-variant' => Livewire\SlideOvers\AddVariant::class, 'slide-overs.update-variant' => Livewire\SlideOvers\UpdateVariant::class, 'slide-overs.generate-variants' => Livewire\SlideOvers\GenerateVariants::class, ], ]; ``` Set `Sections\VariantsSection::class` to `false` to hide the Variants section from the product editor. The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below resolve the variant class from its contract, so they keep working after you swap the model. ### Creating Variants [#creating-variants] Create a single variant with the `CreateNewVariant` action, or step by step on the model. The [Generating Variant Combinations](#generating-variant-combinations) section covers creating every combination at once. #### Single Variant [#single-variant] `Shopper\Actions\Store\Product\CreateNewVariant` creates the variant, its prices, its option values and its initial stock in one transaction: ```php use Shopper\Actions\Store\Product\CreateNewVariant; use Shopper\Core\Models\Currency; $usd = Currency::query()->where('code', 'USD')->value('id'); $variant = app()->call(CreateNewVariant::class, ['data' => [ 'product_id' => $product->id, 'name' => 'Blue / L', 'sku' => 'TS-BLUE-L', 'values' => [$blue->id, $large->id], 'prices' => [ $usd => ['amount' => 2999, 'compare_amount' => 3499], ], 'quantity' => 50, ]]); ``` `prices` is keyed by currency ID, with amounts in cents, and a currency without an `amount` is skipped. The action sets `position` after the last variant of the product, and records `quantity` at the default location; when no location is the default one, the quantity is not recorded. #### Manual Creation [#manual-creation] For full control, create the variant through the contract and write its values, prices and stock yourself: ```php use Shopper\Core\Enum\Dimension\Length; use Shopper\Core\Enum\Dimension\Weight; use Shopper\Core\Models\Contracts\Inventory; use Shopper\Core\Models\Contracts\ProductVariant; use Shopper\Core\Models\Currency; $variant = resolve(ProductVariant::class)::query()->create([ 'product_id' => $product->id, 'name' => 'Red / L', 'sku' => 'TS-RED-L', 'position' => $product->variants()->max('position') + 1, 'weight_unit' => Weight::G, 'weight_value' => 250, 'height_unit' => Length::CM, 'height_value' => 74, 'width_unit' => Length::CM, 'width_value' => 56, ]); $variant->values()->sync([$red->id, $large->id]); $variant->prices()->updateOrCreate( ['currency_id' => Currency::query()->where('code', 'USD')->value('id')], ['amount' => 2999], ); $variant->mutateStock( inventoryId: resolve(Inventory::class)::query()->default()->value('id'), quantity: 50, event: 'Initial stock', ); ``` ### Retrieving Variants [#retrieving-variants] `$product->variants` returns the variants ordered by `position`. To find a variant by its SKU, query the variants of its product, since a SKU is unique per product only: ```php $variant = $product->variants()->where('sku', 'TS-BLUE-L')->first(); ``` To build an option picker, load the variants with their values and the attribute of each value: ```php $variants = $product->variants()->with('values.attribute')->get(); ``` To find the variant matching a selection, such as Color = Blue and Size = L, count the matching values: ```php use Illuminate\Database\Eloquent\Builder; $valueIds = [$blue->id, $large->id]; $variant = $product->variants() ->whereHas('values', fn (Builder $query) => $query->whereKey($valueIds), '=', count($valueIds)) ->first(); ``` `whereKey()` qualifies the `id` column with the table name, which the query needs because the pivot table has an `id` column too. ### Storefront Example [#storefront-example] This controller shows a product page with its option picker, and answers the request the page sends when a customer changes the selection: ```php title="app/Http/Controllers/ProductController.php" publish() ->where('slug', $slug) ->with(['variants.values.attribute', 'variants.prices.currency', 'variants.media']) ->firstOrFail(); resolve(ProductVariant::class)::loadCurrentStock($product->variants); $options = $product->variants ->flatMap->values ->unique('id') ->groupBy(fn (AttributeValue $value): string => $value->attribute->name); return view('products.show', [ 'product' => $product, 'options' => $options, ]); } public function variant(Request $request, string $slug): JsonResponse { $valueIds = $request->validate([ 'values' => ['required', 'array'], 'values.*' => ['integer'], ])['values']; $variant = resolve(Product::class)::query() ->publish() ->where('slug', $slug) ->firstOrFail() ->variants() ->whereHas('values', fn (Builder $query) => $query->whereKey($valueIds), '=', count($valueIds)) ->firstOrFail(); return response()->json([ 'id' => $variant->public_id, 'name' => $variant->name, 'sku' => $variant->sku, 'price' => $variant->getPrice()?->amount, 'stock' => $variant->stock, 'in_stock' => $variant->allow_backorder || $variant->inStock(), 'image' => $variant->getThumbnailUrl('medium'), ]); } } ``` `$options` groups the values by option name, `['Color' => [Blue, Red], 'Size' => [S, M, L]]`, for the picker. The price is in cents: format it as described on the [Money](/3.x/money) page. ## Events [#events] Shopper dispatches no variant event of its own. Saving the variants of a product from the admin panel dispatches no product event either, as described in [Product Events](/3.x/events#product-events). Listen to the Eloquent model events instead. They are dispatched under the core class name as well, so a listener registered on `Shopper\Core\Models\ProductVariant` keeps firing after you swap the model: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\ProductVariant; public function boot(): void { ProductVariant::saved(fn (ProductVariant $variant) => Cache::forget("storefront.product.{$variant->product_id}")); } ``` The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ### Observer Behavior [#observer-behavior] Shopper registers `Shopper\Core\Observers\ProductVariantObserver` on the variant model. Before a variant is deleted, it deletes its media, its prices and its stock history and stock levels, and the database deletes its pivot rows, so `$variant->delete()` needs no cleanup beforehand. When a variant is created or deleted, or when its SKU changes, it reindexes the parent product once the transaction is committed. ## Permissions [#permissions] The admin panel checks three permissions of the `products.variants` resource, in the Products group: | Permission | Allows | |------------|--------| | `products.variants.create` | Saving a variant from the Add variant slide-over, and saving new combinations from the generator | | `products.variants.edit` | Opening the generator, editing a variant, its SKU and barcode, its media, its prices and its stock, and reordering the variants | | `products.variants.delete` | Deleting a variant, one at a time or in bulk, and saving a generator list that drops existing variants | The variants list and the variant page sit behind `products.edit`, like every section of the product editor. `products.variants.browse` and `products.variants.read` are seeded with the others, but the admin panel never checks them. The [Access Control](/3.x/acl#access-by-section) page lists the permissions of each section. ## In the Admin [#in-the-admin] Merchants manage variants in the Variants section of a variant product. The table lists each variant with its thumbnail, name, SKU, position and stock, lets merchants drag rows to reorder them, and deletes variants one at a time or in bulk. Add variant opens a four-step slide-over: General (name, SKU, option values), Media (thumbnail and images), Pricing (one price per currency) and Inventories (barcode and initial quantity). Generate variants opens the generator described in [Generating Variant Combinations](#generating-variant-combinations). The variant page edits the name, option values, backorder setting and dimensions, the SKU and barcode, the images, the prices and the stock at each location. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes variants inside their product, under the `store` prefix set by `SHOPPER_API_PREFIX`. It has no variant endpoint of its own: | Endpoint | Returns | |----------|---------| | `GET /store/products/{slug}?include=variants` | The product with its variants, their prices and their option values | | `GET /store/products?filter[option]=blue,large` | The products with a variant, or a product attribute, whose value or value key matches one of the given values | | `POST /store/carts/{cartId}/lines` | Adds a variant to a cart | A variant resource has the type `variants`, its `public_id` as `id`, and carries `name`, `sku`, `barcode`, `ean`, `upc`, `position`, `allow_backorder`, `stock`, `in_stock`, `metadata`, `prices`, the calculated price, `values` (each with `value`, `key`, `attribute` and `attribute_slug`), `images`, `thumbnail`, `created_at` and `updated_at`, and a `product` relationship. `in_stock` is `true` when the stock is above 0 or the variant allows backorders. To add a variant to a cart, send its public ID with the `variant` type: ```bash curl -X POST "https://example.com/store/carts/01JD8Z3K4M5N6P7Q8R9S0T1V2W/lines" \ -H "Content-Type: application/json" \ -d '{"purchasable_type": "variant", "purchasable_id": "01JD8Z9X7Y6W5V4T3S2R1Q0P9N", "quantity": 2}' ``` The API answers with the `variant_required` error code when the request names a variant product instead of one of its variants, `purchasable_unavailable` when the variant does not exist or its product is not published, `price_missing` when the variant has no price in the cart currency, and `stock_insufficient` when the stock is short. The Store API [Cart](/3.x/store-api/cart#adding-a-line) guide shows how a storefront adds a variant to a cart, and the [Pricing](/3.x/pricing) page describes the price fields. # Products (/3.x/products) A product is an item of the catalog: a T-shirt, an ebook, a pair of sneakers sourced from a partner. Each product has a type that decides what it can do. A standard product carries its own price and stock, a variant product is sold through variants such as "Blue / Large", a virtual product needs no shipping, and an external product comes from a supplier and cannot be added to a cart. The product holds what its variants share: the name, the description, the images, the brand, the categories, the SEO fields and the channels it is sold on. Prices have their own table, described on the [Pricing](/3.x/pricing) page, and variants have their own model, described on the [Product Variants](/3.x/product-variants) page. ## Model [#model] The model is `Shopper\Core\Models\Product`. It implements the `Shopper\Core\Models\Contracts\Product` contract, which extends `Shopper\Core\Models\Contracts\Stockable`. The class configured by default under the `product` key of `config/shopper/models.php` is `Shopper\Models\Product`, from the admin package: it extends the core model and registers the media collections with Spatie Media Library. The examples on this page use that class. The traits of the core model change what you can do with a product: - `HasSlug` turns the `slug` you assign into a URL-safe value and appends `-1`, `-2` and so on when it is already taken. The slug is not derived from the name: pass one when you create a product. - `HasPublicId` fills `public_id` with a ULID when the product is created, as described in [Public IDs](/3.x/models#public-ids). - `HasPrices` adds the `prices` relation and `getPrice()`, covered in [Pricing](#pricing). - `HasStock` adds the stock ledger, covered in [Stock Management](#stock-management). - `HasDimensions` adds the formatted `weight`, `height`, `width`, `depth` and `volume` attributes. - `HasDiscounts` adds the `discounts` relation, and `InteractsWithReviews` adds the `ratings` relation. - `Searchable` (`Shopper\Core\Models\Traits\Searchable`, built on Laravel Scout) sends the product to the search index once it is visible and its publication date has passed. The [Search](/3.x/search) page covers the index. - `SoftDeletes` keeps a deleted product in the table with a `deleted_at` date and leaves it out of every query. ### Extending the Model [#extending-the-model] To add your own methods, extend the admin model: ```php title="app/Models/Product.php" namespace App\Models; use Shopper\Models\Product as ShopperProduct; class Product extends ShopperProduct { public function isNewArrival(): bool { return $this->published_at->isAfter(now()->subDays(30)); } } ``` Then point the configuration to your class: ```php title="config/shopper/models.php" 'product' => App\Models\Product::class, ``` Shopper binds the contract to the configured class, so `resolve(Shopper\Core\Models\Contracts\Product::class)`, `$variant->product`, `$brand->products` and `$category->products` all return your model. The [Models](/3.x/models#swapping-a-model) page explains how swapping works. ## Database Schema [#database-schema] Products are stored in the `sh_products` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Product name | | `slug` | string | yes | null | URL identifier, unique | | `sku` | string | yes | null | Stock keeping unit, unique | | `barcode` | string | yes | null | Barcode such as an ISBN or a UPC, unique | | `summary` | text | yes | null | Short description for listings | | `description` | longtext | yes | null | Full description, HTML from the admin editor | | `type` | string | yes | null | A `Shopper\Core\Enum\ProductType` value | | `is_visible` | boolean | no | false | Whether the product can be shown on a storefront | | `featured` | boolean | no | false | Flag for your home page or a "featured" block | | `allow_backorder` | boolean | no | false | Whether the product can be sold when it is out of stock | | `security_stock` | integer | yes | 0 | Safety stock threshold, see [Querying Stock](#querying-stock) | | `published_at` | datetimeTz | no | time the migration ran | Publication date; a future date schedules the product | | `seo_title` | string(60) | yes | null | Title for search engines | | `seo_description` | string(160) | yes | null | Description for search engines | | `weight_unit` | string | no | kg | Weight unit: `kg`, `g`, `lbs` | | `weight_value` | decimal(10,2) | yes | 0.00 | Weight | | `height_unit` | string | no | cm | Height unit: `m`, `cm`, `mm`, `ft`, `in` | | `height_value` | decimal(10,2) | yes | 0.00 | Height | | `width_unit` | string | no | cm | Width unit | | `width_value` | decimal(10,2) | yes | 0.00 | Width | | `depth_unit` | string | no | cm | Depth unit | | `depth_value` | decimal(10,2) | yes | 0.00 | Depth | | `volume_unit` | string | no | l | Volume unit: `l`, `ml`, `gal`, `floz` | | `volume_value` | decimal(10,2) | yes | 0.00 | Volume | | `external_id` | string | yes | null | Identifier of an external product at its supplier | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `brand_id` | bigint | yes | null | Brand, set to `null` when the brand is deleted | | `supplier_id` | bigint | yes | null | Supplier, set to `null` when the supplier is deleted | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | | `deleted_at` | timestamp | yes | null | Soft delete timestamp | The table has a composite index on `is_visible` and `published_at`, the two columns the `publish` scope filters on. The stock is not a column of this table: it lives in the stock ledger described in [Stock Management](#stock-management). ## Relationships [#relationships] A product belongs to a brand and a supplier, has many variants, prices and reviews, and is linked to its categories, collections, channels, tags and related products through one polymorphic pivot table, `sh_product_has_relations`. ### Brand [#brand] Each product can belong to one brand through `brand_id`: ```php $product->brand; ``` To list the products of a brand, use the `byBrand` scope, which takes brand slugs or public IDs and skips disabled brands: ```php use Shopper\Models\Product; $products = Product::query()->publish()->byBrand('nike')->get(); ``` The [Brands](/3.x/brands) page covers the brand model. ### Categories [#categories] Products and categories are linked through `sh_product_has_relations`. A product can be in several categories: ```php $product->categories; $product->categories()->attach([$menswear->id, $tShirts->id]); $product->categories()->sync([$tShirts->id]); ``` The `category` and `categoryTree` scopes described in [Filtering the Catalog](#filtering-the-catalog) query products by category. The [Categories](/3.x/categories) page covers the category tree. ### Collections [#collections] Products are added to manual collections by hand and to automatic collections by their rules: ```php $product->collections; $product->collections()->attach($summerSale->id); ``` Every time a product is saved, the `Shopper\Core\Observers\ProductObserver` queues a `SyncProductWithCollectionsJob` once the transaction commits. The job checks the product against the rules of every automatic collection, attaches it where it matches and detaches it where it no longer does. The [Collections](/3.x/collections) page covers the rules. ### Channels [#channels] A product is sold on the channels it is attached to: ```php $product->channels; $product->channels()->attach($webStore->id); ``` A product attached to no channel is hidden from the Store API as soon as a request resolves a channel. The [Channels](/3.x/channels#assigning-products-to-channels) page covers the assignment and its effect on the catalog. ### Variants [#variants] For a product of the `Variant` type, `variants()` returns its variants, ordered by their `position` column. Each variant has its own SKU, prices, stock and media: ```php $product->variants; $product->variants_stock; ``` The `variants_stock` attribute adds up the stock of every variant. The [Product Variants](/3.x/product-variants) page covers variants, their options and their generation. ### Tags [#tags] Tags are flat labels, stored in the `Shopper\Core\Models\ProductTag` model and linked through `sh_product_has_relations`: ```php $product->tags; $product->tags()->attach([$organicCotton->id, $bestSeller->id]); ``` The [Product Tags](/3.x/product-tags) page covers tags. ### Supplier [#supplier] A product can be linked to one supplier through `supplier_id`. External products use it to record where they come from: ```php $product->supplier; ``` Suppliers are disabled on a fresh install. The [Suppliers](/3.x/suppliers) page covers the model and its feature flag. ### Attributes (Options) [#attributes-options] The attributes of a product, such as the material of a T-shirt, are read through `options()`. The name `options` avoids a collision with the `$attributes` property of Eloquent models. The `sh_attribute_product` pivot table stores the selected attribute value, or a custom value for a free-text attribute: ```php $product->options; $product->options()->attach($material->id, [ 'attribute_value_id' => $cotton->id, ]); $product->options()->attach($careInstructions->id, [ 'attribute_custom_value' => 'Machine wash at 30 degrees', ]); ``` The same rows are available as `Shopper\Models\AttributeProduct` models through `attributeProducts()`. Standard, variant and virtual products can have attributes; external products cannot. The [Attributes](/3.x/attributes) page covers attribute types and values. ### Related Products [#related-products] Related products are other products you suggest next to this one, for cross-selling: ```php $product->relatedProducts; $product->relatedProducts()->attach([$hoodie->id, $cap->id]); ``` The relation goes one way: attaching the hoodie to the T-shirt does not attach the T-shirt to the hoodie. ### Discounts [#discounts] A discount can target specific products through the `sh_discountables` table: ```php $product->discounts; ``` The [Discounts](/3.x/discounts) page covers discount rules and conditions. ### Reviews [#reviews] Customer reviews are attached to the product through the polymorphic `reviewrateable` columns of the reviews table, and read through `ratings()`: ```php $approved = $product->ratings() ->where('approved', true) ->latest() ->get(); ``` The [Reviews](/3.x/reviews) page covers ratings, approval and the rating helpers. ## Query Scopes [#query-scopes] The model has scopes for the storefront: one for the publication state, one for channels, and a set of catalog filters that the Store API also uses. ### Published Products [#published-products] The `publish` scope keeps the products whose `is_visible` flag is on and whose `published_at` date is in the past. This is the starting point of every storefront query: ```php use Shopper\Models\Product; $products = Product::query()->publish()->get(); ``` To schedule a product, set `published_at` to a future date: it stays out of the `publish` scope until that date. To hide a product without changing its date, turn `is_visible` off. ### Filter by Channel [#filter-by-channel] The `channel` scope keeps the products attached to one channel, or to any of several channels. It takes channel IDs: ```php use Shopper\Models\Product; $products = Product::query() ->publish() ->channel([$webStore->id, $mobileApp->id]) ->get(); ``` ### Publication Check [#publication-check] The `isPublished()` method applies the same rule as the `publish` scope to a product you already loaded: ```php if (! $product->isPublished()) { abort(404); } ``` ### Filtering the Catalog [#filtering-the-catalog] The following scopes back the filters of the Store API, and work the same in your own queries. The first five take one or more slugs or public IDs, and `option` takes the `key` or the `value` of attribute values. Each matches a product that has any of the values: | Scope | Keeps the products | |-------|--------------------| | `category(...)` | In one of these categories, skipping disabled categories and the categories under them | | `categoryTree(...)` | In one of these categories or in any enabled category below them | | `collection(...)` | In one of these collections, if the collection is published | | `byBrand(...)` | Of one of these brands, if the brand is enabled | | `tag(...)` | With one of these tags | | `option(...)` | With an attribute value, or a variant option value, whose `key` or `value` matches | | `availability($value = true)` | That can be bought now: in stock, on backorder or external. Pass `false` for the others | | `matching($term)` | Whose name, description or SKU contains the term, ignoring case | The scopes combine with each other: ```php use Shopper\Models\Product; $products = Product::query() ->publish() ->categoryTree('menswear') ->byBrand('nike', 'adidas') ->option('blue') ->availability() ->paginate(24); ``` `matching` runs a `LIKE` query on the database. For a search engine with typo tolerance and facets, use the search index described on the [Search](/3.x/search) page. ## How Products Work [#how-products-work] The `type` column holds a `Shopper\Core\Enum\ProductType` case, chosen when the product is created. The type decides which sections of the admin panel apply to the product and how the cart and the Store API treat it: | Type | Value | Shipping | Variants | Attributes | Stock checked at checkout | Use case | |------|-------|----------|----------|------------|---------------------------|----------| | Standard | `standard` | Yes | No | Yes | On the product | A book, a poster, a mug | | Variant | `variant` | Yes | Yes | Yes | On each variant | A T-shirt in several sizes and colors | | Virtual | `virtual` | No | No | Yes | No | An ebook, a software license | | External | `external` | No | No | No | No | A product sourced from another supplier | A standard product holds its own price, stock and media. It suits anything sold in a single version. A variant product holds the description, the images and the categories, and leaves prices and stock to its variants. The Store API refuses to add the product itself to a cart: the customer picks a variant. See [Product Variants](/3.x/product-variants). A virtual product skips shipping, and the cart sells it without checking stock. The admin panel adds a **Files** section to it, described in [Downloadable Files](#downloadable-files). An external product comes from a supplier. The admin panel asks for its `external_id`, the identifier of the product at the supplier, and for the supplier when the `supplier` feature is enabled. The Store API lists it as always in stock, and refuses to add it to a cart. The model has a method for each type, and one for each capability: ```php $product->isStandard(); $product->isVariant(); $product->isVirtual(); $product->isExternal(); $product->canUseShipping(); $product->canUseAttributes(); $product->canUseVariants(); $product->tracksInventory(); ``` `canUseShipping()` and `tracksInventory()` are true for standard and variant products, `canUseAttributes()` for every type except external, and `canUseVariants()` for variant products only. The cart reads `tracksInventory()` to decide whether to check the stock. The admin panel can skip the type choice in the Add product form: the "Set as default product type" toggle stores the type in the `default_product_type` setting, listed in [Setting Keys](/3.x/settings#setting-keys). ## Media [#media] Products have three media collections. The core model declares them, and `Shopper\Models\Product` registers them with Spatie Media Library, so `addMedia()`, `getMedia()` and `getFirstMediaUrl()` are available on that class and on any class that extends it. The core `Shopper\Core\Models\Product` class has no media methods. | Collection | Name | Files | Accepted types | |------------|------|-------|----------------| | Gallery | `shopper.media.storage.collection_name`, `uploads` by default | Several | `shopper.media.accepts_mime_types` | | Thumbnail | `shopper.media.storage.thumbnail_collection`, `thumbnail` by default | One | `shopper.media.accepts_mime_types` | | Files | `files`, not configurable | Several | `shopper.media.accepts_file_types` | The gallery and the thumbnail are stored on the disk named in `shopper.media.storage.disk_name`, `public` by default, and the files on the private disk of `shopper.media.storage.files_disk`, `local` by default. Each image gets the resized copies listed under `shopper.media.conversions`: `large` (800 by 800) and `medium` (500 by 500) by default. To add images, read the collection name from the configuration: ```php $product->addMedia($request->file('image')) ->toMediaCollection(config('shopper.media.storage.collection_name')); $product->addMediaFromUrl('https://cdn.example.com/classic-t-shirt-front.jpg') ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); ``` Adding an image to the thumbnail collection replaces the previous one. To display the thumbnail, `getThumbnailUrl()` takes a conversion name. It returns the thumbnail, or the first gallery image when the product has no thumbnail, or the fallback image of `shopper_fallback_url()` when it has neither: ```blade title="resources/views/products/_card.blade.php" {{ $product->name }} ``` Load the `media` relation with your products to avoid one query per product in a listing. ### Downloadable Files [#downloadable-files] The `files` collection holds the files of a virtual product: an ebook in PDF, a ZIP of fonts, a spreadsheet template. The admin panel shows the **Files** section on virtual products only. The accepted types come from `shopper.media.accepts_file_types`, which leaves out HTML, SVG and JavaScript so an uploaded file cannot run a script on your domain. These files are stored apart from the images, on the disk named in `shopper.media.storage.files_disk`. The default, `local`, keeps them in `storage/app/private` with the disk configuration Laravel ships, out of reach of any public URL. Point it to another disk without public access, such as a private S3 bucket, as described in [Storage Disk](/3.x/media#storage-disk). A file added from your code goes to the same disk: ```php $product->addMedia(storage_path('app/ebooks/sneaker-care-guide.pdf')) ->toMediaCollection('files'); $product->getMedia('files'); ``` The Store API never returns the URL of these files. A virtual product carries `files`, with the `id` (the UUID of the media), `name`, `extension` and `size` in bytes of each file, so the product page can show what the customer gets: ```json { "files": [ { "id": "4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13", "name": "sneaker-care-guide", "extension": "pdf", "size": 2483012 } ] } ``` A signed-in customer downloads the files of an order in two calls. `GET /store/customers/me/orders/{orderId}?include=items` returns the items, and each item of a virtual product carries the same `files` attribute once the payment status of the order is Paid or Partially refunded. The storefront then asks for a link to one file, with the public IDs of the order and the item and the `id` of the file: ```bash curl "https://example.com/store/customers/me/orders/01JQ8Z6N4W2T5V3K9R7M1H0XAB/items/01JQ8Z6N5C8E2D4F6G1J3K5M7P/files/4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13" \ -H "Authorization: Bearer 1|customer-token" ``` The response holds the link and the moment it expires: ```json { "data": { "url": "https://example.com/store/files/4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13?expires=1773308767&signature=3bd70b02156440e6703239eb610bc1d851c2682d68acd1fd2dc3dafca9a2a9cb", "expires_at": "2026-03-12T09:46:07+00:00" } } ``` The link works for five minutes, a duration with no configuration key: request a new one for each download and send the browser to its `url` right away. When the file is stored on a disk that uses the `s3` driver, `url` is a presigned URL of the bucket that downloads the file as an attachment. On any other disk, it points to `GET /store/files/{fileId}`, the route named `shopper.store.files.download`, which streams the file as an attachment and answers 403 when the signature is missing, altered or expired. Shopper does not count downloads: the customer can ask for a new link as often as needed. The link request answers with an error in these cases: | Status | When | |--------|------| | 401 | The request has no customer token | | 403 | The payment status of the order is Pending, Authorized, Refunded or Voided. The error code is `forbidden` | | 404 | The order does not exist or belongs to another customer, the item is not part of the order, the item's product is deleted or no longer virtual, or the file is not one of the current files of that product | The endpoint reads the orders of the signed-in customer only, so the Store API gives no download link for a guest order. The JavaScript SDK wraps the link request in `fileLink()`, which takes the three IDs and returns the `url` and `expires_at`. The `ProductFile` type of `@shopperlabs/shopper-types` describes a file, in `Product.files` and `OrderItem.files`: ```ts import Shopper from '@shopperlabs/shopper-sdk' const sdk = new Shopper({ baseUrl: 'https://example.com' }) await sdk.auth.login({ email: 'amara@example.com', password: 'correct-horse-battery-staple' }) const { url } = await sdk.store.customer.fileLink( '01JQ8Z6N4W2T5V3K9R7M1H0XAB', '01JQ8Z6N5C8E2D4F6G1J3K5M7P', '4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13', ) window.location.assign(url) ``` To move files stored on another disk to `files_disk`, run the command below. `php artisan shopper:upgrade` runs it as its last step, and you run it yourself after you change `files_disk`: ```bash php artisan shopper:files:secure ``` The command copies each file to `files_disk` and deletes the original, so a moved file gets a new `id`. ## Pricing [#pricing] Products use the `HasPrices` trait. Prices are stored in the `sh_prices` table through the polymorphic `priceable` columns, with one price per currency. `getPrice()` returns the `Shopper\Core\Models\Price` of a currency, or of the store default currency when you pass none, and `null` when the product has no price in it: ```php $price = $product->getPrice('USD'); echo shopper_money_format($price->amount, $price->currency_code); ``` Amounts are stored in cents, as described on the [Money](/3.x/money) page. A variant product has no price of its own: each variant carries its prices. The [Pricing](/3.x/pricing) page covers compare-at and cost amounts and `resolvePrice()`. ## Stock Management [#stock-management] Products use the `HasStock` trait. Stock is not a column of the products table. Each stock movement is a row of `sh_inventory_histories`, the ledger, with the quantity added or removed, the location, the event label, the user and an optional reference such as an order. The `sh_stock_levels` table keeps the running quantity of each product at each location, and is updated in the same transaction as the ledger. Every movement belongs to an inventory location, so every method that writes stock takes an `inventoryId`. How a store spreads its stock over several locations is covered on the [Locations](/3.x/locations) page. Only standard and variant products track stock (`tracksInventory()`). When a customer adds one to a cart, the cart checks the stock unless the product allows backorders. For a variant product, stock is kept on each variant: see [Product Variants](/3.x/product-variants). ### Querying Stock [#querying-stock] The `stock` attribute returns the current quantity across every location, read from `sh_stock_levels`: ```php $product->stock; $product->inStock(2); ``` `inStock()` takes the quantity a customer wants, `1` by default, and returns `true` when the stock covers it. It ignores `allow_backorder`: check that flag yourself when you sell on backorder. To read the stock at one location, or at a past date, pass the location ID or the date. A date replays the ledger up to that moment, which is useful for reports: ```php $product->stockInventory($warehouse->id); $product->getStock('2026-01-15'); $product->getStock(now()->subDays(7)); $product->stockInventory($warehouse->id, '2026-01-15'); ``` The ledger itself is the `inventoryHistories` relation: ```php $movements = $product->inventoryHistories() ->with('inventory') ->latest() ->take(20) ->get(); ``` The `security_stock` column holds the safety stock set in the admin panel. Shopper stores it and sends no alert when the stock falls below it: compare it in your own code, such as a scheduled command that emails the team. ### Modifying Stock [#modifying-stock] To add stock, for example when a shipment arrives at the warehouse, use `mutateStock()`: ```php use Shopper\Core\Models\Inventory; $warehouse = Inventory::query()->default()->first(); $product->mutateStock( inventoryId: $warehouse->id, quantity: 50, event: 'Shipment received', description: 'Purchase order 12345, spring restock', userId: auth()->id(), ); ``` To remove stock, use `decreaseStock()`. It always records a negative quantity, whatever the sign you pass. The `reference` argument links the movement to the model that caused it: ```php $product->decreaseStock( inventoryId: $warehouse->id, quantity: 2, event: 'Damaged in storage', reference: $order, ); ``` To set the stock to an exact quantity after a physical count, use `setStock()`. It compares the new quantity with the total stock of the product across every location, and writes the difference to the location you pass. It returns `null` and writes nothing when the quantities are equal: ```php $product->setStock( newQuantity: 75, inventoryId: $warehouse->id, event: 'Inventory count', ); ``` On a store with several locations, the result of `setStock()` is the total you pass, not the quantity at that location. Use `mutateStock()` with the difference you computed from `stockInventory()` to correct a single location. To erase the ledger and start again, optionally with a new quantity at one location, use `clearStock()`: ```php $product->clearStock( inventoryId: $warehouse->id, newQuantity: 100, event: 'Stock reset', ); ``` `clearStock()` deletes every ledger row and every stock level of the product, at every location. Use it for resets and corrections, never for regular adjustments. ### Avoiding N+1 Queries [#avoiding-n1-queries] Reading `$product->stock` runs one query. In a loop over a listing, that is one query per product. `loadCurrentStock()` loads the stock of a whole collection in one query: ```php use Shopper\Models\Product; $products = Product::query()->publish()->get(); Product::loadCurrentStock($products); ``` Both methods take an Eloquent collection, and variants have the same methods. To load the stock of one location instead of the total, use `loadStockForInventory()`: ```php Product::loadStockForInventory($products, $warehouse->id); ``` ### Preventing Lazy Stock Loading [#preventing-lazy-stock-loading] Following the pattern of Laravel's `Model::preventLazyLoading()`, you can make every unplanned stock read fail during development. Once enabled, reading `$product->stock` on a product whose stock was not loaded in bulk throws a `Shopper\Core\Exceptions\LazyStockLoadingException`: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Models\Product; public function boot(): void { Product::preventLazyStockLoading(! app()->isProduction()); } ``` ## Dimensions [#dimensions] The `*_value` columns hold the dimensions used for shipping, and the `*_unit` columns hold their unit, cast to the `Weight`, `Length` and `Volume` enums of the `Shopper\Core\Enum\Dimension` namespace. The `HasDimensions` trait adds one attribute per dimension that returns the value and its unit as a string, or `null` when the value is empty: ```php $product->weight; $product->height; $product->width; $product->depth; $product->volume; ``` For a product with `weight_value` set to `1.50` and `weight_unit` set to `kg`, `$product->weight` returns `"1.50 kg"`. The admin panel shows the **Shipping** section, where these fields are edited, on standard and variant products only. ## SEO Fields [#seo-fields] The `seo_title` and `seo_description` columns hold the title and the description a storefront puts in the page head. They are limited to 60 and 160 characters, the lengths search engines display. The admin panel edits them, with the `metadata` key-value pairs, in the **SEO** section of the product. Fall back to the name and the summary when they are empty: ```blade title="resources/views/products/show.blade.php" {{ $product->seo_title ?? $product->name }} ``` ## Configuration [#configuration] Products have no feature flag: the products section of the admin panel is always on. The flags of `config/shopper/features.php` hide the matching fields and sections of the product editor: `brand`, `category`, `collection`, `tag`, `attribute` and `supplier`, the only one disabled on a fresh install. See [Feature Flags](/3.x/configuration#feature-flags). The model is swapped through the `product` key of `config/shopper/models.php`, as shown in [Extending the Model](#extending-the-model). Media settings live in `config/shopper/media.php`: | Key | Default | Used for | |-----|---------|----------| | `storage.collection_name` | `uploads` | Name of the gallery collection | | `storage.thumbnail_collection` | `thumbnail` | Name of the thumbnail collection | | `storage.disk_name` | `public` | Disk of the gallery and the thumbnail | | `storage.files_disk` | `local` | Disk of the `files` collection, which must not be public | | `accepts_mime_types` | JPEG, PNG, WebP, AVIF | Images accepted in the gallery and the thumbnail | | `accepts_file_types` | PDF, ZIP, RAR, 7z, Word, Excel, text, CSV | Files accepted in the `files` collection | | `max_size.thumbnail` | `1024` | Maximum size of a thumbnail upload in the admin panel, in kilobytes | | `max_size.images` | `2048` | Maximum size of a gallery image upload in the admin panel, in kilobytes | | `conversions` | `large`, `medium` | Resized copies generated for each image | The pages and sections of the product editor are Livewire components you can replace. `php artisan shopper:component:publish product` creates `config/shopper/components/product.php`, as described in [Components](/3.x/configuration#components). ## Creating Products [#creating-products] Create the product, then attach what the admin panel would attach. This creates a standard Classic T-Shirt with a price, a category and a channel: ```php use Shopper\Core\Enum\ProductType; use Shopper\Core\Models\Channel; use Shopper\Core\Models\Currency; use Shopper\Models\Product; $product = Product::query()->create([ 'name' => 'Classic T-Shirt', 'slug' => 'classic-t-shirt', 'sku' => 'TSHIRT-001', 'type' => ProductType::Standard, 'summary' => 'A heavyweight cotton T-shirt.', 'is_visible' => true, 'published_at' => now(), 'brand_id' => $nike->id, ]); $product->prices()->create([ 'amount' => 2999, 'currency_id' => Currency::query()->where('code', 'USD')->value('id'), ]); $product->categories()->attach($tShirts->id); $product->channels()->attach(Channel::query()->default()->value('id')); ``` Then add its first stock and its thumbnail: ```php use Shopper\Core\Models\Inventory; $product->mutateStock( inventoryId: Inventory::query()->default()->value('id'), quantity: 100, event: 'Initial stock', ); $product->addMediaFromUrl('https://cdn.example.com/classic-t-shirt.jpg') ->toMediaCollection(config('shopper.media.storage.thumbnail_collection')); ``` A product created in code differs from one created in the admin panel in four ways: - `is_visible` is `false` unless you set it, and `published_at` takes the column default, the time the migration ran. Set both. - The product is attached to no channel unless you attach it, and disappears from a Store API catalog that resolves a channel. - The slug stays `null` unless you pass one, and the Store API finds products by slug. - No `ProductCreated` event is dispatched. See [Events](#events). Scout indexes the product on save once it is visible and its publication date has passed, and the observer queues the automatic collection sync. For many products at once, the CSV import of the admin panel creates them with their prices, stock and images, as described on the [Import](/3.x/import) page. ## Retrieving Products [#retrieving-products] A storefront starts from the `publish` scope, adds the filters of the page, and loads the relations it displays. This controller lists the products of a category and of its subcategories: ```php title="app/Http/Controllers/CategoryController.php" namespace App\Http\Controllers; use Illuminate\Contracts\View\View; use Shopper\Models\Product; class CategoryController extends Controller { public function show(string $slug): View { $products = Product::query() ->publish() ->categoryTree($slug) ->with(['brand', 'media', 'prices.currency']) ->latest('published_at') ->paginate(24); Product::loadCurrentStock($products->getCollection()); return view('categories.show', ['products' => $products]); } } ``` To load the page of one product, filter on the slug after the `publish` scope, so an unpublished product answers 404: ```php $product = Product::query() ->publish() ->where('slug', 'classic-t-shirt') ->with([ 'brand', 'categories', 'variants.prices.currency', 'relatedProducts' => fn ($query) => $query->publish(), ]) ->firstOrFail(); ``` `Product::findBySlug('classic-t-shirt')` also throws a `ModelNotFoundException` when no product matches, but it ignores the publication state: keep it for back-office code. To fill a home page block with featured products: ```php $featured = Product::query() ->publish() ->where('featured', true) ->latest('published_at') ->take(8) ->get(); ``` Code that must honor a swapped model, such as a package or a shared action, resolves the class from the contract, as described in [Resolving Models in Your Code](/3.x/models#resolving-models-in-your-code): ```php use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query() ->publish() ->where('slug', 'classic-t-shirt') ->firstOrFail(); ``` ## Updating Products [#updating-products] Update the columns with `update()` and the links with the relations: ```php $product->update([ 'summary' => 'A heavyweight organic cotton T-shirt.', 'published_at' => now()->addWeek(), ]); $product->categories()->sync([$tShirts->id, $organic->id]); $product->channels()->syncWithoutDetaching([$mobileApp->id]); ``` Each save updates the search index for a visible, published product and queues the automatic collection sync. Like `create()`, `update()` dispatches no event: the admin panel dispatches `ProductUpdated` from the Overview form of the product editor only. ## Deleting Products [#deleting-products] Products are soft deleted: `delete()` sets `deleted_at`, and `restore()` brings the row back. ```php $product->delete(); ``` Deleting a product runs the `deleting` hook of `ProductObserver`, which deletes its media and its prices and clears its stock ledger at every location, even though the product row is only soft deleted. `restore()` brings the product back without them. ## Events [#events] Product events live in `Shopper\Core\Events\Products`: `ProductCreated`, `ProductUpdated`, `ProductDeleted` and `ProductImportCompleted`. The first three are dispatched after the database transaction commits. The admin panel and the CSV import dispatch them; no observer does, so `Product::create()` in your own code dispatches nothing. When your code creates products that listeners or webhooks must see, dispatch the event yourself: ```php use Shopper\Core\Events\Products\ProductCreated; event(new ProductCreated($product)); ``` The [Events](/3.x/events#product-events) page lists when each event fires and what it carries. The events are also sent as the `product.created`, `product.updated` and `product.deleted` [webhooks](/3.x/webhooks). ## Permissions [#permissions] The admin panel checks these permissions on the product pages: | Permission | Checked for | |------------|-------------| | `products.browse` | The product list | | `products.create` | The Add product form and the CSV import | | `products.edit` | Every section of the product editor | | `products.delete` | Deleting a product | `products.read` is seeded and not checked by the admin panel. Variants have their own `products.variants.*` permissions, removing an attribute from a product needs `attributes.delete`, and the "Set as default product type" toggle needs `system.settings`. The [Access Control](/3.x/acl#access-by-section) page lists every permission by section. ## In the Admin [#in-the-admin] The **Products** page lists the products with their thumbnail, type, SKU, brand, stock, visibility and publication date, and filters them by name, type, visibility, sales channel and publication date. The **Add product** form walks through the type, the general information, the brand, categories, channels and collections, the images, and the SKU, barcode and initial quantity, which goes to the default location. The product editor has an **Overview**, **Media**, **Stock & Inventory**, **SEO** and **Related Products** section for every product, plus **Attributes**, **Variants**, **Pricing**, **Shipping** and **Files** depending on the type. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes products read-only, and only published products: | Endpoint | Returns | |----------|---------| | `GET /store/products` | The published products, paginated | | `GET /store/products/{slug}` | One published product, or a 404 | | `GET /store/products/{slug}/reviews` | The approved reviews of the product | A product resource has the `products` type and its public ID as `id`. Its attributes are the name, slug, SKU, barcode, summary, description, `featured`, type, publication date, SEO fields, metadata, images, thumbnail, prices in every enabled currency and calculated price in the request currency (none for a variant product), and the stock: `stock` and `in_stock` for a standard or virtual product, `in_stock` alone for a variant or external product. A virtual product adds its `files`, without URLs (see [Downloadable Files](/3.x/products#downloadable-files)), an external product its `external_id`. The list endpoint accepts these parameters. The filters, sorts and includes other than `currency`, `price_min` and `price_max` come from `ProductResource`, and you can add or remove them as [Extending the Allowlists](/3.x/store-api/json-api#extending-the-allowlists) shows: | Parameter | Values | |-----------|--------| | `filter[...]` | `name`, `sku`, `q` (the `matching` scope), `featured`, `in_stock` (the `availability` scope), `category`, `category_tree`, `collection`, `brand`, `tag`, `option`, `currency`, `price_min`, `price_max` | | `sort` | `name`, `created_at`, `published_at`, `price` (prefix with `-` for descending) | | `include` | `brand`, `variants`, `categories`, `collections`, `options`, `tags`, `relatedProducts`, `rating`, `price_range` | ```bash curl "https://example.com/store/products?filter[category_tree]=menswear&filter[in_stock]=true&sort=-published_at&include=brand" \ -H "X-Shopper-Channel: web-store" ``` The `X-Shopper-Channel` header limits the catalog to the products of that channel, as described in [The Store API](/3.x/channels#the-store-api) section of the channels page. A `price` sort or a price filter needs a currency: `filter[currency]`, the currency of the customer's zone, or the store default. The Store API [Catalog](/3.x/store-api/catalog) guide covers the product endpoints. # Requirements (/3.x/requirements) Shopper is a Laravel package: a server that runs Laravel 12 or 13 runs Shopper once a few more PHP extensions are installed. Composer checks every requirement on this page when you install Shopper, and stops with the name of anything that is missing. ## Server Requirements [#server-requirements] - PHP 8.3 or higher. The continuous integration runs on PHP 8.3, 8.4 and 8.5. - MySQL 8+, PostgreSQL 15+ or SQLite. The test suite runs on these three databases. MariaDB is not part of it. ### PHP Extensions [#php-extensions] Shopper needs the extensions listed in Laravel's [server requirements](https://laravel.com/docs/deployment#server-requirements), plus these: | Extension | Why Shopper needs it | |-----------|----------------------| | `intl` | Currency, number and locale formatting in `shopper/core` and Filament | | `gd` | Required by `milon/barcode`, which draws the barcode on the variant page. GD is also the default image driver of Spatie Media Library, which builds the thumbnails of product, category and brand images | | `exif` | Required by Spatie Media Library, which reads the metadata of uploaded images | | `zip`, `xmlreader` | Required by OpenSpout, the spreadsheet library of Filament's actions package | | `iconv` | Required by `bacon/bacon-qr-code`, which draws the QR code a user scans to set up two-factor authentication | The `soap` extension that Shopper 2 needed is no longer required. GD stays required even if you prefer ImageMagick for your images. To build the thumbnails with ImageMagick, install the `imagick` extension and set the image driver of Spatie Media Library in your `.env` file: ```bash title=".env" IMAGE_DRIVER=imagick ``` ## Laravel and Package Versions [#laravel-and-package-versions] | Package | Version | |---------|---------| | Laravel | 12.68+ or 13.27+ | | Filament | 5.11+ | | Livewire | 4.1+ | Composer installs Filament and Livewire as dependencies of Shopper, so you do not require them in your application. Shopper 3 does not run on Laravel 11: upgrade your application to Laravel 12 or 13 first. If your store runs Shopper 2, follow the [upgrade guide](/3.x/upgrade). ## Development Environments [#development-environments] ### Laravel Herd [#laravel-herd] [Laravel Herd](https://herd.laravel.com/) is the recommended development environment for macOS and Windows. It provides PHP, Nginx and database services with no configuration, and its PHP builds include every extension listed on this page. ### Laravel Valet [#laravel-valet] [Laravel Valet](https://laravel.com/docs/valet) is a lightweight development environment for macOS. It maps every subdirectory of a directory (such as `~/Sites`) to a `.test` domain, and can share your sites publicly through local tunnels. ### Docker [#docker] Any Docker setup that provides the PHP version, the extensions and one of the databases above works with Shopper. # Reviews (/3.x/reviews) Customers rate the products they bought and tell other customers what they think: a star rating from 1 to 5, an optional title and text, and whether they recommend the product. Each review is a row of the `reviews` table, linked to the product it rates and to the customer who wrote it. A new review is pending until a merchant approves it. Only approved reviews reach the storefront: the Store API, the average rating on the dashboard and the rating rule of automatic collections all ignore pending reviews. Shopper stores and moderates reviews; collecting them on your storefront is up to your code, as shown in [Review Submission](#review-submission). ## Model [#model] The model is `Shopper\Core\Models\Review`. It implements the `Shopper\Core\Models\Contracts\Review` contract. It has no key in `config/shopper/models.php`, so it cannot be swapped: to add a relationship to it, use `resolveRelationUsing()` as described in [Models You Cannot Swap](/3.x/models#models-you-cannot-swap). The `HasPublicId` trait fills `public_id` with a ULID when a review is created, and adds `findByPublicId()` and the `wherePublicId` scope. The Store API returns it as the `id` of each review. The model casts `approved` and `is_recommended` to booleans and has an `approved` scope. Products receive reviews through the `Shopper\Core\Models\Traits\InteractsWithReviews` trait, described in [HasReviews Contract](#hasreviews-contract). ## Database Schema [#database-schema] Reviews are stored in the `sh_reviews` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `is_recommended` | boolean | no | false | Whether the customer recommends the product | | `rating` | integer | no | - | Star rating | | `title` | text | yes | null | Review title | | `content` | text | yes | null | Review text | | `approved` | boolean | no | false | Whether the review is published | | `reviewrateable_type` | string | no | - | Morph type of the reviewed model, `product` for a product | | `reviewrateable_id` | bigint | no | - | ID of the reviewed model | | `author_type` | string | no | - | Morph type of the author | | `author_id` | bigint | no | - | ID of the author | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The `rating` column accepts any integer. The admin panel and the Store API count ratings from 1 to 5, so validate that range when you create a review. An index on `reviewrateable_type`, `reviewrateable_id`, `approved` and `created_at` serves the list of approved reviews of a product, newest first. The reviewed model and the author are polymorphic columns without foreign keys. Deleting a product or a customer leaves their reviews in the table. ## Relationships [#relationships] A review belongs to the model it rates and to the customer who wrote it. Both relationships are polymorphic. ### Reviewrateable (Product) [#reviewrateable-product] `reviewrateable` returns the reviewed product. A product review stores the `product` alias in `reviewrateable_type`, so the relationship returns an instance of the class configured for the `product` key, as explained in [Morph Map](/3.x/models#morph-map): ```php $product = $review->reviewrateable; ``` ### Author (User) [#author-user] `author` returns the customer, an instance of your `User` model. Shopper registers no morph alias for the `User` model, so `author_type` stores its class name, such as `App\Models\User`: ```php $customer = $review->author; $name = $review->author?->full_name; ``` The author is `null` when the customer was deleted. To list the reviews of a customer, compare `author_type` with the value of `getMorphClass()`, as shown in [Retrieving Reviews](#retrieving-reviews). ## HasReviews Contract [#hasreviews-contract] The product model implements the `Shopper\Core\Contracts\HasReviews` contract with the `InteractsWithReviews` trait. The trait adds a `ratings` relationship, which returns every review of the product, pending ones included, and the rating methods below. Product variants have no reviews of their own: a customer reviews the product. The trait works on any model, but the admin page and the Store API only read product reviews. ## Rating Methods [#rating-methods] The trait adds methods to read, count and average the reviews of a product. Several of them count pending reviews unless you ask otherwise, so check each one before you display its result to customers. ### Getting Ratings [#getting-ratings] The `ratings` relationship is the most direct way to read the reviews of a product. Combine it with the `approved` scope for the storefront: ```php $reviews = $product->ratings() ->approved() ->with('author') ->latest() ->get(); ``` The trait also has helpers that take an ID and return a collection of reviews ordered by `created_at`, newest first by default: ```php $product->getAllRatings($product->id); $product->getApprovedRatings($product->id); $product->getNotApprovedRatings($product->id); $product->getRecentRatings($product->id, limit: 5); $product->getRecentUserRatings($customer->id, limit: 5, approved: true); ``` `getRecentRatings()` returns approved reviews only. `getRecentUserRatings()` takes the ID of a customer and returns their reviews on every product. These helpers filter on `reviewrateable_id` or `author_id` without the morph type, so they mix models once a second model receives reviews. The `ratings` relationship has no such limit. ### Rating Counts [#rating-counts] `countRating()` returns the number of reviews of the product, pending ones included. `sumRating()` returns the sum of the ratings, wrapped in a collection: ```php $all = $product->countRating(); $published = $product->ratings()->approved()->count(); $sum = $product->sumRating(onlyApproved: true)->first(); ``` ### Average Ratings [#average-ratings] `averageRating()` returns the average rating wrapped in a collection. Pass `round` to round it in the query and `onlyApproved` to leave out pending reviews, which it counts by default: ```php $average = $product->averageRating(round: 1, onlyApproved: true)->first(); ``` The value is `null` when the product has no review. On a product list, load the count and the average with the products instead of calling these methods once per product: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::query() ->publish() ->withCount(['ratings as reviews_count' => fn (Builder $query) => $query->approved()]) ->withAvg(['ratings as average_rating' => fn (Builder $query) => $query->approved()], 'rating') ->paginate(12); ``` ### Rating Percentage [#rating-percentage] `ratingPercent()` returns the share of reviews with exactly the given rating, as a percentage rounded to one decimal. It counts pending reviews: ```php $fiveStars = $product->ratingPercent(5); ``` For the rating distribution of a product page, group the approved reviews by rating in one query: ```php $distribution = $product->ratings() ->approved() ->selectRaw('rating, COUNT(*) as total') ->groupBy('rating') ->pluck('total', 'rating'); ``` The contract also declares `averageCustomerServiceRating()`, `averageQualityRating()`, `averageFriendlyRating()`, `averagePricingRating()` and the matching `count*Rating()` methods. They read columns that the `reviews` table does not have, and throw a `QueryException`: do not call them. ## Configuration [#configuration] Reviews are on by default. Their settings are the feature flag, the admin components and the Store API options described in [From a Storefront](#from-a-storefront). ### Disabling Reviews [#disabling-reviews] If your store does not collect reviews, disable the feature in `config/shopper/features.php`: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'review' => FeatureState::Disabled, ]; ``` The reviews page is no longer registered and the Reviews item leaves the sidebar. The flag only changes these two: the Store API review endpoints, the rating of the Top Selling Products widget on the [Dashboard](/3.x/dashboard#top-selling-products) and the rating rule of automatic collections keep reading the reviews already stored. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Components [#components] The reviews section of the admin panel is made of one page and one slide-over. To replace either with your own Livewire component, publish the component file of the section: ```bash php artisan shopper:component:publish review ``` The command creates `config/shopper/components/review.php`: ```php title="config/shopper/components/review.php" use Shopper\Livewire; return [ 'pages' => [ 'review-index' => Livewire\Pages\Reviews\Index::class, ], 'components' => [ 'slide-overs.review-detail' => Livewire\SlideOvers\ReviewDetail::class, ], ]; ``` To add content above or below the reviews table without replacing the page, register a view on the `REVIEWS_TABLE_BEFORE` or `REVIEWS_TABLE_AFTER` render hook of `Shopper\View\CatalogRenderHook`. The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below read products through the product contract, so they keep working after you swap the product model. ### Creating Reviews [#creating-reviews] A review is created pending, because the `approved` column defaults to `false`. The model has no `$fillable` list: pass only validated fields, or a request that sends `approved` publishes its own review. #### Via Product Model [#via-product-model] `rating()` creates a review of the product, with the customer as its author: ```php use Shopper\Core\Models\Contracts\Product; $product = resolve(Product::class)::query() ->where('slug', 'classic-t-shirt') ->firstOrFail(); $review = $product->rating([ 'rating' => 5, 'title' => 'Fits perfectly', 'content' => 'Soft cotton, true to size, and it kept its shape after ten washes.', 'is_recommended' => true, ], $customer); ``` #### Via Review Model [#via-review-model] `createRating()` does the same from the review model, with the product as its first argument: ```php use Shopper\Core\Models\Review; $review = (new Review)->createRating($product, [ 'rating' => 4, 'title' => 'Good quality', 'content' => 'Nice fabric, the color is a little darker than on the photos.', 'is_recommended' => true, ], $customer); ``` #### Direct Creation [#direct-creation] Through the `ratings` relationship, Eloquent fills `reviewrateable_type` and `reviewrateable_id`. Fill the author columns yourself, with the morph class of the customer: ```php $review = $product->ratings()->create([ 'rating' => 5, 'title' => 'Best purchase this year', 'is_recommended' => true, 'author_type' => $customer->getMorphClass(), 'author_id' => $customer->getKey(), ]); ``` Do not write `get_class($product)` in `reviewrateable_type`: the product stores its `product` alias, and the Store API and the admin panel look reviews up by that alias. ### Updating Reviews [#updating-reviews] Update a review like any Eloquent model. `updateRating()` on the product finds the review by its ID and updates it: ```php $review->update([ 'rating' => 4, 'content' => 'Still great after six months, one seam came loose.', ]); $product->updateRating($review->id, ['title' => 'Great, with one flaw']); ``` ### Approval Management [#approval-management] `updatedApproved()` publishes or unpublishes a review. The `approved` scope keeps the published ones: ```php use Shopper\Core\Models\Review; $review->updatedApproved(true); $review->updatedApproved(false); $published = Review::query()->approved()->count(); ``` The Approve, Reject and Mark as spam actions of the admin panel call the same method: approving sets `approved` to `true`, and both rejecting and marking as spam set it to `false`. A rejected review stays in the table, and a merchant can approve it later. ### Deleting Reviews [#deleting-reviews] Reviews are deleted for good, the model has no soft deletes. Delete a review directly, or through the product with its ID: ```php $review->delete(); $product->deleteRating($review->id); ``` ### Retrieving Reviews [#retrieving-reviews] Query the `Review` model for reviews across products, such as the moderation queue or the reviews of one customer: ```php use Shopper\Core\Models\Review; $pending = Review::query() ->where('approved', false) ->with(['author', 'reviewrateable']) ->oldest() ->get(); $customerReviews = Review::query() ->where('author_type', $customer->getMorphClass()) ->where('author_id', $customer->getKey()) ->with('reviewrateable') ->latest() ->get(); $review = Review::findByPublicId('01JZ8Q4X7M2N3P5R6S7T8V9W0Y'); ``` ### Storefront Example [#storefront-example] A storefront built in the same Laravel application reads and creates reviews with the model. The examples below show a product page and a review form. #### Review Display [#review-display] The product page loads the count and the average of the approved reviews with the product, then paginates the reviews: ```php title="app/Http/Controllers/ProductController.php" publish() ->where('slug', $slug) ->withCount(['ratings as reviews_count' => fn (Builder $query) => $query->approved()]) ->withAvg(['ratings as average_rating' => fn (Builder $query) => $query->approved()], 'rating') ->firstOrFail(); $reviews = $product->ratings() ->approved() ->with('author') ->latest() ->paginate(10); return view('products.show', ['product' => $product, 'reviews' => $reviews]); } } ``` The view shows the summary, then each review: ```blade title="resources/views/products/show.blade.php"

    {{ number_format((float) $product->average_rating, 1) }} out of 5, from {{ $product->reviews_count }} reviews

    @foreach ($reviews as $review)

    {{ $review->title }}

    {{ $review->rating }}/5 by {{ $review->author?->first_name }}, {{ $review->created_at->diffForHumans() }}

    {{ $review->content }}

    @if ($review->is_recommended)

    Recommends this product

    @endif
    @endforeach {{ $reviews->links() }} ``` #### Review Submission [#review-submission] The review form posts to a route of your application. The controller validates the fields, refuses a second review of the same product by the same customer, and creates the review pending: ```php title="app/Http/Controllers/ProductReviewController.php" publish() ->where('slug', $slug) ->firstOrFail(); $validated = $request->validate([ 'rating' => ['required', 'integer', 'between:1,5'], 'title' => ['nullable', 'string', 'max:255'], 'content' => ['nullable', 'string', 'max:2000'], 'is_recommended' => ['boolean'], ]); $customer = $request->user(); $alreadyReviewed = $product->ratings() ->where('author_type', $customer->getMorphClass()) ->where('author_id', $customer->getKey()) ->exists(); if ($alreadyReviewed) { return back()->withErrors(['rating' => 'You have already reviewed this product.']); } $product->rating($validated, $customer); return back()->with('status', 'Thank you, your review will appear once it is approved.'); } } ``` Register the route behind the `auth` middleware, so every review has a customer: ```php title="routes/web.php" use App\Http\Controllers\ProductReviewController; Route::post('/products/{slug}/reviews', [ProductReviewController::class, 'store']) ->middleware('auth') ->name('products.reviews.store'); ``` ## Events [#events] Shopper dispatches no review event of its own. Listen to the Eloquent model events instead. The admin panel approves and rejects reviews with `update()`, so the `updated` event fires on each moderation. This listener emails the customer when their review is published: ```php title="app/Providers/AppServiceProvider.php" use App\Notifications\ReviewPublished; use Shopper\Core\Models\Review; public function boot(): void { Review::updated(function (Review $review): void { if ($review->wasChanged('approved') && $review->approved) { $review->author?->notify(new ReviewPublished($review)); } }); } ``` The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks three permissions of the `reviews` resource, in the Products group: | Permission | Allows | |------------|--------| | `reviews.browse` | Opening the reviews page and a review | | `reviews.edit` | Approving and rejecting a review | | `reviews.delete` | Deleting a review, one at a time or in bulk, and marking a review as spam | The Reviews sidebar item is shown to users who have `products.browse`, while the page itself checks `reviews.browse`. `reviews.read` and `reviews.create` are seeded with the others, but the admin panel never checks them. Shopper 2.x named these permissions `browse_reviews`, `edit_reviews` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants moderate reviews under Customers, Reviews. The page opens with the average rating, the number of reviews and how many arrived in the last 30 days, the share of 5-star reviews and the number of reviews pending moderation, then a breakdown by rating and the share of customers who recommend the product. The table has All, Pending and Approved tabs, lists the customer, product, rating, status and date of each review, and filters by rating, product, customer and recommendation. A review opens in a slide-over with the Approve, Reject and Mark as spam actions. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the approved reviews under the `store` prefix, set by `SHOPPER_API_PREFIX`. There is no endpoint to submit a review: a storefront that collects reviews posts them to a route of its own Laravel application, as in [Review Submission](#review-submission). | Endpoint | Returns | |----------|---------| | `GET /store/products/{slug}/reviews` | The approved reviews of a published product, paginated, newest first. Filter with `filter[rating]=5`, sort with `sort=rating` or `sort=-created_at` | | `GET /store/reviews` | The latest approved reviews across the store, for a testimonials block. Not paginated, capped at `latest_limit` | A review resource has the type `reviews` and carries `title`, `content`, `rating`, `is_recommended`, `created_at` and an `author` object. The author is reduced to a display name, the first name and the initial of the last name such as `Sarah K.`, and an `avatar` picture URL. The author's ID never leaves the API. The product reviews endpoint adds the aggregates of the approved reviews to `meta`, so a product page needs one request: ```json { "meta": { "reviews_count": 5, "average_rating": 4.2, "rating_distribution": { "1": 0, "2": 1, "3": 0, "4": 1, "5": 3 } } } ``` On the products endpoints, `include=rating` adds `rating`, the average of the approved reviews rounded to one decimal, and `reviews_count` to each product: ```bash curl "https://example.com/store/products?include=rating" ``` The `rating` filter and the `created_at` and `rating` sorts of the product reviews endpoint come from `Shopper\Api\Http\Resources\ReviewResource`, and [Extending the Allowlists](/3.x/store-api/json-api#extending-the-allowlists) shows how to change them. The number of reviews `/store/reviews` returns, 20 by default, is set by `reviews.latest_limit` in `config/shopper/api.php`: ```php title="config/shopper/api.php" 'reviews' => [ 'latest_limit' => 20, ], ``` The review endpoints are not filtered by the channel of the request, as noted in [Channels](/3.x/channels#what-the-channel-changes), and they do not read the `review` feature flag: they keep answering after you disable reviews in the admin panel. The JavaScript SDK wraps both endpoints: ```ts import Shopper from '@shopperlabs/shopper-sdk' const sdk = new Shopper({ baseUrl: 'https://example.com' }) const { data, meta } = await sdk.store.product.reviews('classic-t-shirt', { filter: { rating: 5 }, page: { size: 10 }, }) const testimonials = await sdk.store.review.latest() ``` The Store API [Catalog](/3.x/store-api/catalog#reviews) guide covers the review endpoints. # Search (/3.x/search) Shopper indexes its catalog with [Laravel Scout](https://laravel.com/docs/scout). Products, brands, categories, collections, orders and your `User` model are searchable models: Scout sends a document to the search index each time one of them is saved, and removes it when the record is deleted. Shopper decides what each document holds through indexer classes, keeps the product documents up to date when a brand, a category or a variant changes, and lets you choose the search engine of each model. `shopper/core` requires `laravel/scout`, so Scout is installed with Shopper. Its default `collection` driver needs no search server: it reads the database and matches the records in PHP. Moving to Typesense, Meilisearch or Algolia is a change of configuration followed by an import. The index serves your own code. The tables of the admin panel and the product filter of the Store API search the database with SQL, as described in [In the Admin](#in-the-admin) and [From a Storefront](#from-a-storefront). ## Searchable Models [#searchable-models] Shopper models use the `Shopper\Core\Models\Traits\Searchable` trait. It wraps Scout's `Laravel\Scout\Searchable` trait and hands the index name, the decision to index a record and the content of its document to an indexer class from the `Shopper\Core\Search` namespace. The `InteractsWithShopper` trait of your `User` model uses it too. | Model | Indexer | Index | Indexed when | |-------|---------|-------|--------------| | Product | `ProductIndexer` | `products` | `is_visible` is `true` and `published_at` is in the past | | Brand | `BrandIndexer` | `brands` | `is_enabled` is `true` | | Category | `CategoryIndexer` | `categories` | The category and all its parents are enabled | | Collection | `CollectionIndexer` | `collections` | `published_at` is in the past | | Order | `OrderIndexer` | `orders` | Always | | User | `CustomerIndexer` | `users` | Always | The index name is the table of the model without the Shopper table prefix, so `sh_products` becomes `products`. Scout's `prefix` option, set by `SCOUT_PREFIX`, goes in front of it: with `SCOUT_PREFIX=shop_`, products go to the `shop_products` index. Set a prefix when several stores, or the staging and production copies of one store, share a search server. Documents are identified by the [public ID](/3.x/models#public-ids) of the record. The Scout key of every model with a `public_id` column is that ULID, and the `id` field of the document holds the same value, so the auto-increment IDs of your tables never reach the search engine. The `CustomerIndexer` does not appear in `config/shopper/search.php`. Shopper registers it when the application boots, for the class in `config('auth.providers.users.model')`, unless the `indexers` array already lists that class. ## Indexed Fields [#indexed-fields] Each indexer builds the document of a record in its `toSearchableArray()` method. Dates are sent as Unix timestamps, so an engine can sort and filter on them as numbers, and HTML tags are stripped from descriptions. ### Products [#products] The product document holds what a storefront search needs to match and filter a product without loading its relations: | Field | Content | |-------|---------| | `id` | The public ID of the product | | `name`, `slug`, `sku` | The columns of the same name | | `skus` | The SKUs of its variants | | `description`, `summary` | The text of the columns, without HTML | | `type` | The product type: `standard`, `variant`, `virtual` or `external` | | `brand` | The name of its brand, or `null` when the brand is disabled | | `categories` | The names of its categories, without the hidden ones | | `channels` | The public IDs of its [channels](/3.x/channels) | | `published_at`, `created_at` | Timestamps | A category is hidden when it, or one of its parents, is disabled. A search for "Nike" finds the Air Max sneakers through their brand, and a search for a variant SKU such as `TSHIRT-WHITE-M` finds the Classic T-Shirt. ### Brands, Categories and Collections [#brands-categories-and-collections] Their documents hold `id`, `name`, `slug`, `description` and `created_at`. The collection document adds `published_at`. ### Orders and Customers [#orders-and-customers] The order document holds `id`, `number`, `email`, `status` (the value of the `OrderStatus` enum, such as `processing`), `customer` (the full name of the customer), `total` (the `price_amount` column, in [cents](/3.x/money)), `currency_code` and `created_at`. The user document holds `id`, `name` (the first and last names), `email` and `created_at`. Both documents carry email addresses. With a hosted engine such as Algolia, those addresses are stored by the engine provider. To keep them in your database, leave orders and users on the `collection` driver with [`engine_map`](#choosing-an-engine-per-model), or register an indexer that leaves the email out. ### Field Lists [#field-lists] Each indexer also declares the fields an engine should search, filter and sort on, through its `getSearchableFields()`, `getFilterableFields()` and `getSortableFields()` methods. The Shopper packages do not read these lists themselves: the `shopper/search` add-on uses them to build Typesense collection schemas. Keep them in line with `toSearchableArray()` when you write your own indexer. | Indexer | Searchable | Filterable | Sortable | |---------|------------|------------|----------| | `ProductIndexer` | `name`, `sku`, `skus`, `description`, `brand`, `categories` | `brand`, `categories`, `channels`, `type` | `created_at`, `published_at` | | `BrandIndexer`, `CategoryIndexer`, `CollectionIndexer` | `name`, `description` | none | `created_at`, `updated_at` | | `OrderIndexer` | `number`, `email`, `customer` | `status` | `created_at`, `total` | | `CustomerIndexer` | `name`, `email` | none | `created_at`, `updated_at` | ## Configuration [#configuration] Search settings live in `config/shopper/search.php`, which the installer publishes with the other [configuration files](/3.x/configuration). It has three keys: `engine_map`, `indexers` and `facets`. Scout keeps its own settings, the driver, the queue and the credentials of each engine, in `config/scout.php`. Shopper does not publish that file. Publish it when you need more than the environment variables: ```bash php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" ``` ### Choosing a Driver [#choosing-a-driver] As in any Scout application, the `SCOUT_DRIVER` environment variable selects the engine, and it defaults to `collection`. To move every searchable model to Meilisearch, install its client and point Scout to your server: ```bash composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle ``` These variables select Meilisearch and give Scout the address and the master key of your server: ```bash title=".env" SCOUT_DRIVER=meilisearch MEILISEARCH_HOST=http://127.0.0.1:7700 MEILISEARCH_KEY=your-master-key ``` Typesense takes `typesense/typesense-php`, `SCOUT_DRIVER=typesense`, `TYPESENSE_HOST` and `TYPESENSE_API_KEY`. Algolia takes `algolia/algoliasearch-client-php`, `SCOUT_DRIVER=algolia`, `ALGOLIA_APP_ID` and `ALGOLIA_SECRET`. The [Scout documentation](https://laravel.com/docs/scout) covers the setup of each engine. A new engine starts with empty indexes: [import](#importing-existing-records) your records once it is configured. ### Collection and Database Drivers [#collection-and-database-drivers] The `collection` driver suits development and small catalogs. On each search, it loads every row of the table, builds the document of each record with its indexer, and keeps the records whose document contains the search term. Searches match every field of the document, so "nike" finds products by their brand name, and hidden or unpublished products never appear. The cost grows with the table: a product search builds a document for every product, with its brand, categories, channels and variants. With this driver, the `where()` and `whereIn()` constraints of a search run as SQL on the table of the model. They take real columns, such as `brand_id`, and cannot filter on document fields such as `channels`. The `database` driver does not work with Shopper's indexers. To find the columns to search, it builds a document from an empty model, and the indexers read dates and relations that an empty model does not have: searching products, brands, categories, collections or orders throws an `Error`, and searching users throws a `QueryException` on a `name` column that does not exist. Use the `collection` driver until you run a search engine. ### Choosing an Engine per Model [#choosing-an-engine-per-model] The `engine_map` key sends a model to another driver than `SCOUT_DRIVER`. A store can search its products on Typesense while orders, customers and the rest of the catalog stay on the `collection` driver: ```php title="config/shopper/search.php" 'engine_map' => [ Product::class => 'typesense', ], ``` The file imports the core model classes at its top. A key written with a core class also covers the class configured for that model in `config/shopper/models.php`, such as `Shopper\Models\Product` or your own `App\Models\Product`. The mapped engine handles everything Scout does for the model: indexing on save, `scout:import`, `scout:flush` and searches. It still needs its client package and its credentials in `config/scout.php`. ### Index Settings [#index-settings] An engine has to know which fields to search, filter and sort on. Scout reads these settings from `config/scout.php`. Typesense needs a collection schema for each model, looked up by the class Scout indexes, which is the class configured for the model: `Shopper\Models\Product` unless you [swapped it](/3.x/models#swapping-a-model). Add a `model-settings` entry to the `typesense` array of `config/scout.php`: ```php title="config/scout.php" 'model-settings' => [ Shopper\Models\Product::class => [ 'collection-schema' => [ 'fields' => [ ['name' => 'id', 'type' => 'string'], ['name' => 'name', 'type' => 'string'], ['name' => 'slug', 'type' => 'string'], ['name' => 'sku', 'type' => 'string', 'optional' => true], ['name' => 'skus', 'type' => 'string[]'], ['name' => 'description', 'type' => 'string'], ['name' => 'summary', 'type' => 'string', 'optional' => true], ['name' => 'type', 'type' => 'string', 'optional' => true, 'facet' => true], ['name' => 'brand', 'type' => 'string', 'optional' => true, 'facet' => true], ['name' => 'categories', 'type' => 'string[]', 'facet' => true], ['name' => 'channels', 'type' => 'string[]'], ['name' => 'published_at', 'type' => 'int64'], ['name' => 'created_at', 'type' => 'int64'], ], 'default_sorting_field' => 'published_at', ], 'search-parameters' => [ 'query_by' => 'name,sku,skus,brand,categories,description', ], ], ], ``` The `shopper/search` add-on generates these Typesense settings from the field lists of the indexers, for every model that has no `model-settings` entry of its own. Meilisearch and Algolia read an `index-settings` array, keyed by index name or model class. For Meilisearch, declare the filterable and sortable fields of the products index: ```php title="config/scout.php" 'meilisearch' => [ 'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'), 'key' => env('MEILISEARCH_KEY'), 'index-settings' => [ 'products' => [ 'filterableAttributes' => ['brand', 'categories', 'channels', 'type'], 'sortableAttributes' => ['created_at', 'published_at'], ], ], ], ``` Then send the settings to the engine. The command adds `SCOUT_PREFIX` to the index name. Pass `--driver` when Meilisearch serves only the models of `engine_map` and `SCOUT_DRIVER` names another driver: ```bash php artisan scout:sync-index-settings --driver=meilisearch ``` ### Custom Indexers [#custom-indexers] To change the document of a model, extend its indexer and register your class under `indexers`. This indexer adds the tags of each product, so a search for "organic cotton" finds the products tagged with it: ```php title="app/Search/ProductIndexer.php" with('tags'); } public function getSearchableFields(): array { return [...parent::getSearchableFields(), 'tags']; } public function toSearchableArray(Model $model): array { return [ ...parent::toSearchableArray($model), 'tags' => $model->tags->pluck('name')->all(), ]; } } ``` In `config/shopper/search.php`, this `indexers` list gives products your indexer and keeps the indexers of Shopper for the other models: ```php title="config/shopper/search.php" 'indexers' => [ Brand::class => BrandIndexer::class, Category::class => CategoryIndexer::class, Collection::class => CollectionIndexer::class, Order::class => OrderIndexer::class, Product::class => App\Search\ProductIndexer::class, ], ``` `makeAllSearchableUsing()` loads the relations of the document when Scout indexes records in bulk, during an import. `shouldBeSearchable()` decides whether a record belongs in the index: override it to keep, for example, the products of a disabled brand out of search. A new field that holds a list or a number needs its own entry in the index settings of the engine. After the change, import the model again so the existing documents get the new field. The `CustomerIndexer` indexes every user, including the members of your team. An indexer registered for the class in `auth.providers.users.model` replaces it, for example to leave administrators and managers out of the `users` index: ```php title="app/Search/CustomerIndexer.php" isAdmin() && ! $model->isManager(); } } ``` This `indexers` list adds your indexer for the `App\Models\User` class: ```php title="config/shopper/search.php" 'indexers' => [ Brand::class => BrandIndexer::class, Category::class => CategoryIndexer::class, Collection::class => CollectionIndexer::class, Order::class => OrderIndexer::class, Product::class => ProductIndexer::class, App\Models\User::class => App\Search\CustomerIndexer::class, ], ``` ### Facets [#facets] The `facets` key lists, per model, the fields the `shopper/search` add-on returns as facets, with the label of each one. The Shopper packages do not read it. By default, products have a `brand` facet and a `categories` facet. ## Keeping the Index in Sync [#keeping-the-index-in-sync] Scout's model observer updates the document of a record each time it is saved, and removes it when the record is deleted or no longer passes the `shouldBeSearchable()` check of its indexer: a brand saved as disabled leaves the `brands` index. Shopper adds the cases where a product document depends on another model: - Renaming, enabling, disabling or deleting a brand reindexes its products. - Renaming, moving, enabling, disabling or deleting a category reindexes the category, its descendants and their products. Descendants that became hidden leave the `categories` index. - Creating or deleting a variant, or changing its SKU, reindexes its product. These updates run once the database transaction commits. Set `SCOUT_QUEUE=true` to have Scout send the documents from your queue workers instead of during the request. ### Importing Existing Records [#importing-existing-records] Records saved before a model had an engine, such as the catalog of a store that moves to Typesense, are added with Scout's `scout:import` command. Pass the class configured in `config/shopper/models.php`, so the import uses the same class, and the same Typesense settings, as the rest of Shopper: ```bash php artisan scout:import "Shopper\Models\Product" php artisan scout:import "Shopper\Models\Brand" php artisan scout:import "Shopper\Models\Category" php artisan scout:import "Shopper\Models\Collection" php artisan scout:import "Shopper\Core\Models\Order" php artisan scout:import "App\Models\User" ``` The import loads the relations each document needs and skips the records the indexer rejects, such as hidden products. It does not remove documents that should no longer be in the index: add `--fresh` to empty the index before importing. `scout:flush` empties the index of a model without importing anything. ### Scheduled Publications [#scheduled-publications] A product or a collection whose `published_at` is in the future is not indexed when it is saved, and nothing saves it again when that date comes. It stays out of the index until its next save or import. If you schedule publications, schedule the import of products and collections as well, as often as your publication times require. This schedule imports the products and the collections every hour: ```php title="routes/console.php" use Illuminate\Support\Facades\Schedule; Schedule::command('scout:import', ['Shopper\Models\Product'])->hourly(); Schedule::command('scout:import', ['Shopper\Models\Collection'])->hourly(); ``` ## Usage [#usage] Search a model with Scout's `search()` method. In code that must honor a swapped model, resolve the product class from its contract, as recommended in [Resolving Models in Your Code](/3.x/models#resolving-models-in-your-code): ```php use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::search('running shoes')->paginate(12); ``` The results are Eloquent models, loaded from the database in the order the engine ranked them. The product indexer keeps hidden, unpublished and scheduled products out of the index, with one exception described in [In the Admin](#in-the-admin). To eager load relations on the results, pass a callback to `query()`: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Models\Contracts\Product; $products = resolve(Product::class)::search('classic t-shirt') ->query(fn (Builder $query) => $query->with(['brand', 'prices'])) ->paginate(12); ``` On an engine that indexes them as filterable, `where()` filters on the fields of the document. A storefront that sells on several channels keeps the products of its own channel, here the Nike products of the Web Store: ```php use Shopper\Core\Models\Channel; use Shopper\Core\Models\Contracts\Product; $channel = Channel::findBySlug('web-store'); $products = resolve(Product::class)::search('air max') ->where('channels', $channel->public_id) ->where('brand', 'Nike') ->paginate(12); ``` On the `collection` driver, `where()` reads the columns of the products table instead, as described in [Collection and Database Drivers](#collection-and-database-drivers). ## In the Admin [#in-the-admin] The admin panel does not query the search index. The tables of products, variants, orders, customers, brands, categories and collections search their own columns with SQL, through Filament's searchable columns, and the admin panel has no global search. Merchants change the index by editing records: the product pages save a product, its variants and its prices, then send the product to the index once. That step only adds or updates documents: a product hidden, or given a future publication date, on the product page keeps its document in the index, until a save outside the product page or an [import](#importing-existing-records) with `--fresh` removes it. The [User Guide](/3.x/user-guide) shows the admin screens. ## From a Storefront [#from-a-storefront] The Store API does not use Scout. `GET /store/products` takes a `filter[q]` parameter that runs the `matching` scope of the product model: a case-insensitive `LIKE` on the name, description and SKU of the product, combined with the channel of the request and its other filters. It does not match brand names, category names or variant SKUs. ```bash curl "https://example.com/store/products?filter[q]=t-shirt" \ -H "X-Shopper-Channel: web-store" ``` The `shopper/search` add-on adds search endpoints backed by Scout to the Store API: `GET /store/search`, with facets on Typesense, and `GET /store/search/suggest`, which searches products, brands, categories and collections at once. The Store API [Catalog](/3.x/store-api/catalog#filters-sorting-and-includes) guide lists every product filter. # Settings (/3.x/settings) Shopper keeps the configuration a merchant changes from the admin panel, such as the store name, its address, its currencies or the admin theme, in a key-value table rather than in config files: a change applies at once, without a deployment. This page covers that table, how to read and write a setting from your code, how settings are cached, and the keys Shopper itself reads and writes. The settings screen of the admin panel and the `config/shopper/settings.php` file that lists its pages are described in [Configuration](/3.x/configuration#settings). The store details as a merchant fills them in are covered on the [Setup Store](/3.x/setup-store) page. ## Settings Model [#settings-model] Each setting is a row of the `Shopper\Core\Models\Setting` model, stored in the `sh_settings` table with the default table prefix. A row holds one key and its value. The `value` column is JSON and the model casts it to `array`, so a setting holds any JSON value: a string such as the store name, an integer ID, a boolean, or a list such as the store currencies. The model implements `Shopper\Core\Models\Contracts\Setting`. It has no entry in `config/shopper/models.php` and cannot be swapped for a class of your own. ### Database Schema [#database-schema] The `create_settings_table` migration of `shopper/core` creates the table: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto increment | Primary key | | `key` | string | no | none | Setting key, unique | | `display_name` | string | yes | `null` | Label of the key | | `value` | json | yes | `null` | Setting value, cast to `array` | | `locked` | boolean | no | `false` | Set once the merchant has confirmed the value, see [Locked Settings](#locked-settings) | | `created_at`, `updated_at` | timestamp | yes | `null` | Timestamps | When the admin panel saves a key, it fills `display_name` with the translated label of the field, "Store name" for `name`, or with the key in title case for a key it does not know. The `locked` attribute is hidden from the model's array and JSON output. ## Retrieving Settings [#retrieving-settings] The `shopper_setting()` helper of `shopper/core` returns the value of a key, or `null` when the key does not exist: ```php $storeName = shopper_setting('name'); $currencyIds = shopper_setting('currencies'); ``` It works the same in the Blade views of your storefront: ```blade title="resources/views/components/footer.blade.php" ``` Values come back with their JSON type: `currencies` is an array of currency IDs, `setup_guide_done` a boolean. A key that holds an ID returns the ID, so load the model yourself: ```php use Shopper\Core\Models\Country; $country = Country::query()->find(shopper_setting('country_id')); ``` The store logo and cover are file paths on the media disk set in `config/shopper/media.php`. Build their URL from that disk: ```blade title="resources/views/components/header.blade.php" @if ($logo = shopper_setting('logo')) {{ shopper_setting('name') }} @endif ``` The default currency has its own helper: `shopper_currency()` returns the code of the currency stored in `default_currency_id`, such as `EUR`, and `USD` when no default currency is set. The [Money](/3.x/money) page shows how Shopper formats amounts with it. To read several keys in one query, use the model. The `value` cast also applies to `pluck()`: ```php use Shopper\Core\Models\Setting; $address = Setting::query() ->whereIn('key', ['street_address', 'postal_code', 'city', 'state']) ->pluck('value', 'key'); ``` This query goes to the database every time: the cache described below only applies to `shopper_setting()`. ## Caching [#caching] `shopper_setting()` keeps each value in your application cache for 24 hours, under the key `shopper-setting.{key}`, for example `shopper-setting.name`. The admin panel reads several settings on every request (the store name in the top bar, the email and street address checked before each page, the theme), and the cache keeps those reads off the database. The helper relies on Laravel's `Cache::remember()`, which explains two behaviors: - `Cache::remember()` treats a cached `null` as a miss, so each read of a key that does not exist, or that holds `null`, queries the database. - `withCache: false` keeps a value read from the database for one second instead of 24 hours. When the key is already in the cache, the helper still returns the cached value. To read the database whatever the cache holds, query the model. ```php shopper_setting('name', withCache: false); ``` `shopper_currency()` keeps the currency code for one hour under `shopper-setting.default_currency`. ### Clearing the Cache [#clearing-the-cache] When Shopper saves a setting, it forgets the cache key of each key it wrote, and also `shopper-setting.default_currency` when it writes `default_currency_id`. A setting you write through the model keeps its old cached value for up to 24 hours unless you forget its key, as shown in [Writing Settings](#writing-settings). ## Writing Settings [#writing-settings] The admin panel saves settings through the `Shopper\Traits\SaveSettings` trait of `shopper/framework`. Use it in your own admin pages, for instance a settings page registered as shown in [Adding a Settings Page](/3.x/configuration#adding-a-settings-page). Its `saveSettings()` method takes an array of keys and values, writes them in one database transaction, fills their `display_name` and forgets the cache of each key: ```php title="app/Livewire/Shopper/ShippingNotice.php" namespace App\Livewire\Shopper; use Illuminate\Contracts\View\View; use Livewire\Component; use Shopper\Traits\SaveSettings; final class ShippingNotice extends Component { use SaveSettings; public ?string $notice = null; public function mount(): void { $this->authorize('system.settings'); $this->notice = shopper_setting('shipping_notice'); } public function save(): void { $this->authorize('system.settings'); $this->saveSettings(['shipping_notice' => $this->notice]); } public function render(): View { return view('livewire.shopper.shipping-notice'); } } ``` Outside such a class, for example in a seeder or an Artisan command, write the row with the model, then forget its cache key: ```php use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Setting; Setting::query()->updateOrCreate( ['key' => 'shipping_notice'], ['value' => 'Free shipping on orders over $50'], ); Cache::forget('shopper-setting.shipping_notice'); ``` ### Locked Settings [#locked-settings] `saveSettings()` takes a second argument, `locked`, which is `true` by default. Shopper uses it in the setup wizard: each step saves its fields with `locked: false` when the merchant moves to the next step, and the final submit saves every field with `locked: true`. A save with `locked: false` never overwrites a locked row: ```php $this->saveSettings(['name' => 'Classic Apparel'], locked: false); ``` If `name` is already locked, this call leaves it as it is. The settings pages save with `locked: true`, so a merchant's edit always applies. A row you create through the model starts with `locked` set to `false`, the column default. ## Setting Keys [#setting-keys] These are the keys Shopper writes and reads. Your own keys live in the same table, so pick names that do not collide with them. | Key | Value | Written by | Read by | |-----|-------|------------|---------| | `name` | String | Setup wizard, General settings | Admin top bar, setup wizard, default inventory, Store API | | `legal_name` | String | General settings | Store API | | `email` | String | Setup wizard, General settings | Setup check of the admin panel, default inventory, Store API | | `phone_number` | String | Setup wizard, General settings | Default inventory, Store API | | `about` | HTML from the rich text editor | General settings | Store API | | `logo` | Path on the media disk | General settings | Store API | | `cover` | Path on the media disk | General settings | Store API | | `street_address` | String | Setup wizard, General settings | Setup check of the admin panel, default inventory, Store API | | `postal_code` | String | Setup wizard, General settings | Default inventory, Store API | | `city` | String | Setup wizard, General settings | Default inventory, Store API | | `state` | String | Setup wizard, General settings | Store API | | `country_id` | Country ID | Setup wizard, General settings | Default country of phone inputs and of the `Shopper\Core\Rules\Phone` rule, default inventory, Store API | | `currencies` | Array of currency IDs | Setup wizard, General settings | Price forms of products and variants, zone form, currency filters of the orders list and the revenue chart, campaign form, product import, cart currency check of the Store API, Store API | | `default_currency_id` | Currency ID | Setup wizard, General settings | `shopper_currency()`, variant generator prices, price rules of automatic collections, product import, Store API | | `social_links` | List of `platform` and `url` pairs | Setup wizard, General settings | Store API | | `admin_theme` | Theme ID | Appearance settings | Theme of the admin panel, for every user | | `default_product_type` | A `Shopper\Core\Enum\ProductType` value, such as `variant` | "Set as default product type" toggle of the new product form | New product form, which then skips the type step | | `setup_guide_done` | `true` | Dashboard setup guide | Dashboard | | `permissions_dot_notation_applied` | Date of the run | `shopper:upgrade:permissions` | The same command, so that it runs once | | `zero_decimal_fix_applied` | Date of the run | `shopper:upgrade:fix-zero-decimal-currencies` | The same command, so that it runs once | The `social_links` value keeps the order the merchant set, with a `platform` from the `Shopper\Core\Enum\SocialPlatform` enum (`facebook`, `instagram`, `x`, `tiktok` and others) and the profile `url`: ```php [ ['platform' => 'instagram', 'url' => 'https://instagram.com/classicapparel'], ['platform' => 'tiktok', 'url' => 'https://tiktok.com/@classicapparel'], ] ``` Shopper 2.x stored the social links in three keys: `facebook_link`, `instagram_link` and `twitter_link`. When `social_links` is empty, the General settings page builds it from these keys, and the first save writes `social_links`. The old rows are left in the table. ## Setup Wizard and Settings Pages [#setup-wizard-and-settings-pages] On the first login, the setup wizard asks for the store information, its address and its social links. It saves only the keys listed in the table above as written by the setup wizard, and ignores any other key in the submitted form. The first two steps save their fields with `locked: false` when the merchant clicks next, and the wizard fills its form from these rows when it opens again. The final submit saves every field with `locked: true` and creates the default inventory from the store name, email and address, in one transaction. Until `email` and `street_address` both have a value, every admin page behind the login redirects to the wizard, as described in [Dashboard](/3.x/dashboard#access-requirements). Once they do, the wizard redirects to the dashboard. The wizard is open to administrators and to users with the `system.settings` permission. The **General** settings page loads the store keys and saves the whole form, locked, when the merchant saves. The **Appearance** page saves `admin_theme`. Both require the `system.settings` permission, described on the [Permissions](/3.x/acl) page. ## Store API [#store-api] `GET /store/settings` returns the public store settings to a storefront, without authentication (`store` is the default prefix of the Store API, set by `SHOPPER_API_PREFIX`). The settings table also holds keys meant for the admin panel only, such as `admin_theme` and `setup_guide_done`, so the endpoint returns only the keys listed under `settings.expose` in `config/shopper/api.php`: ```php title="config/shopper/api.php" 'settings' => [ 'expose' => [ 'name', 'legal_name', 'about', 'email', 'phone_number', 'street_address', 'city', 'postal_code', 'state', 'country_id', 'logo', 'cover', 'social_links', 'default_currency_id', 'currencies', ], 'max_age' => 300, ], ``` Six keys come back in a public shape instead of their stored value: | Setting key | Attribute | Returned value | |-------------|-----------|----------------| | `country_id` | `country` | The ISO 3166-1 alpha-2 `code` and the country `name`, translated in the language of the request | | `default_currency_id` | `default_currency` | The currency code returned by `shopper_currency()` | | `currencies` | `currencies` | The currency codes, sorted by currency name | | `logo`, `cover` | `logo`, `cover` | An object with an absolute `url` | | `social_links` | `social_links` | Each link with its `platform`, `url` and the platform `label`; links with an unknown platform or an empty URL are left out | The other keys come back as stored, and `null` when the merchant never filled them in. Two attributes are always added: `default_locale`, the locale the response is written in, and `supported_locales`, the locales of `config/shopper/admin.php`. A request picks its language with the `Accept-Language` header, matched against these locales: ```json { "data": { "id": "store", "type": "settings", "attributes": { "name": "Classic Apparel", "legal_name": "Classic Apparel LLC", "about": "

    Organic cotton basics, made to last.

    ", "email": "hello@classic-apparel.com", "phone_number": "+33142685300", "street_address": "12 Rue de la Paix", "city": "Paris", "postal_code": "75002", "state": null, "country": { "code": "FR", "name": "France" }, "logo": { "url": "https://classic-apparel.com/storage/01JD8XQ6S9W3T4N5V6B7C8D9EF.png" }, "cover": null, "social_links": [ { "platform": "instagram", "url": "https://instagram.com/classicapparel", "label": "Instagram" } ], "default_currency": "EUR", "currencies": ["EUR", "USD"], "default_locale": "en", "supported_locales": [ { "code": "en", "label": "English" }, { "code": "fr", "label": "Français" } ] } } } ``` The endpoint reads the listed keys in one query, without the `shopper_setting()` cache, except `default_currency`, which comes from the cached `shopper_currency()`. The response is public and cacheable: it carries `max-age` and `s-maxage` set to `max_age` (300 seconds by default), an `ETag`, and `Vary: Accept-Language`. A client that sends the ETag back in `If-None-Match` gets a `304 Not Modified` while nothing changed. Browsers and shared caches can serve the previous response for up to `max_age` seconds after a merchant edits the settings. To expose a key of your own, add it to the list. It comes back as stored: ```php title="config/shopper/api.php" 'settings' => [ 'expose' => [ // ... 'shipping_notice', ], ], ``` With the JavaScript SDK, `sdk.store.setting.retrieve()` returns all the attributes and `sdk.store.setting.get('email')` a single one. The Store API [Store and Regions](/3.x/store-api/store#reading-the-store-settings) guide covers the settings endpoint. # Setup Store (/3.x/setup-store) Every store has a name, a contact email, an address, the currencies it sells in and its pages on social networks. A merchant enters these details in the setup wizard on the first login to the admin panel, then edits them on the General settings page. Shopper stores each detail as a row of the settings table, under a key such as `name`, `email` or `street_address`, and your storefront reads it with `shopper_setting()`. This page maps each field of the wizard and of the General page to its setting key. The `Setting` model, the `shopper_setting()` helper, its cache and the full list of keys are covered on the [Settings](/3.x/settings) page. ## Setup Wizard [#setup-wizard] After installing Shopper and creating an admin user, log in at `/cpanel/login` (`cpanel` is the default prefix, set by `SHOPPER_PREFIX`). Until the store has an `email` and a `street_address`, every admin page behind the login redirects to the wizard at `/cpanel/initialize`, as described in [Access Requirements](/3.x/dashboard#access-requirements). The wizard has three steps: Information, Address and Social Links. Clicking **Next** saves the fields of the current step. Clicking **Save** on the last step saves every field, creates the default inventory location in the same database transaction, and opens the dashboard. The [Setup Wizard and Settings Pages](/3.x/settings#setup-wizard-and-settings-pages) section explains how these saves use locked rows. The wizard belongs to the admin panel and cannot be replaced: its route points to the `Shopper\Livewire\Pages\Initialization` class directly, and the component configuration has no entry for it. ## Store Information [#store] The first step asks for the identity of the store and the currencies it sells in: | Field | Setting key | Rules | |-------|-------------|-------| | Store name | `name` | Required, 100 characters at most | | Email address | `email` | Required, a valid email address | | Country | `country_id` | Optional, the ID of a country | | Currencies | `currencies` | Required, at least one currency | | Default currency | `default_currency_id` | Required, one of the selected currencies | The country is where the store is based. The phone inputs of the admin panel and the `Shopper\Core\Rules\Phone` rule use it as their default country. The currencies list shows every row of the currencies table, sorted by name, and the default currency list only the selected ones. `currencies` holds the IDs of the selected currencies, and `default_currency_id` the ID of the main one, which `shopper_currency()` turns into a code such as `EUR`. The [Currencies](/3.x/currencies) page covers selling in several currencies, and [Money](/3.x/money) how amounts are formatted. ## Address [#address] The second step asks for the store address. The Store API returns it with the other store details, and Shopper copies it to the default inventory location, described in [Default Location](#default-location): | Field | Setting key | Rules | |-------|-------------|-------| | Street Address | `street_address` | Required, 255 characters at most | | Postal / Zip code | `postal_code` | Required, 20 characters at most | | State | `state` | Optional, 100 characters at most | | City | `city` | Required, 100 characters at most | | Phone number | `phone_number` | Optional, 30 characters at most | The wizard stores the phone number as typed. The General settings page checks that it is a valid number, reading it with the store country's dialing code when it has none, and stores it in E.164 format, such as `+33142685300`. ## Social Links [#social-links] The last step is optional. The merchant adds one row per platform, picks the platform and pastes the full URL of the store's profile: Each platform can be added once, so a store has 12 links at most. The URL must be valid and its host must belong to the platform, with or without `www.` and including subdomains. Rows can be dragged to change their order: | Platform | Value | Accepted hosts | |----------|-------|----------------| | Facebook | `facebook` | `facebook.com`, `fb.com`, `fb.me` | | Instagram | `instagram` | `instagram.com`, `instagr.am` | | X (Twitter) | `x` | `x.com`, `twitter.com` | | LinkedIn | `linkedin` | `linkedin.com`, `lnkd.in` | | YouTube | `youtube` | `youtube.com`, `youtu.be` | | TikTok | `tiktok` | `tiktok.com` | | Pinterest | `pinterest` | `pinterest.com` | | Snapchat | `snapchat` | `snapchat.com` | | WhatsApp | `whatsapp` | `whatsapp.com`, `wa.me` | | Telegram | `telegram` | `telegram.me`, `t.me` | | GitHub | `github` | `github.com` | | Website | `website` | Any host | The platforms are the cases of the `Shopper\Core\Enum\SocialPlatform` enum. The links are saved in the `social_links` key, in the order the merchant set, as a list of `platform` and `url` pairs. The [Setting Keys](/3.x/settings#setting-keys) section shows the stored shape and how the `facebook_link`, `instagram_link` and `twitter_link` keys of Shopper 2.x are converted. ## Default Location [#default-location] When the merchant clicks **Save** on the last step, the wizard creates the default inventory location, or updates it when one already exists. The location takes the store name, email, street address, postal code, city, phone number and country, and its code is the slug of the store name, such as `classic-apparel`. The default location exists only once that last step is saved. Shopper puts the initial quantity of a new product in the default location, and the Store API uses its address as the origin when it asks carriers for shipping rates. Changing the address on the General settings page later leaves the location as it is: merchants edit it on the Locations settings page, described in [Locations](/3.x/locations). ## Channel [#channel] The wizard does not create sales channels. The installer creates the default channel before the first login: `ChannelSeeder` adds an enabled "Web Store" channel marked as default, as described in [Default Channel](/3.x/channels#default-channel). ## Updating the Store Details [#update-setting] After the wizard, merchants edit the store details under **Settings**, **General**, at `/cpanel/setting/general`. The page has five sections and saves them all at once: | Section | Fields | Setting keys | |---------|--------|--------------| | Store details | Store name, Email address, Phone number | `name`, `email`, `phone_number` | | Assets | Logo, Cover photo | `logo`, `cover` | | Store address | Legal name of the company, About, Street Address, City, Postal / Zip code, State, Country | `legal_name`, `about`, `street_address`, `city`, `postal_code`, `state`, `country_id` | | Store currency | Currencies, Default currency | `currencies`, `default_currency_id` | | Social links | One row per platform | `social_links` | The fields shared with the wizard follow the same rules, without the length limits on the street address, postal code, state and city, and with three additions: - The legal name is required. The wizard does not ask for it, so the merchant fills it in on the first save of this page. - The logo and the cover are images of up to 1 MB, of a type listed in `config('shopper.media.accepts_mime_types')`. They are stored on the disk set by `config('shopper.media.storage.disk_name')`, and the setting holds the file path. [Retrieving Settings](/3.x/settings#retrieving-settings) shows how to build their URL. - The about text comes from a rich text editor and is stored as HTML. Images inserted in it go to the same disk, in the folder set by `config('shopper.media.storage.collection_name')`. ### Replacing the General Page [#replacing-the-general-page] The page is the `Shopper\Livewire\Pages\Settings\General` Livewire component, registered under the `pages.general` key of the settings components. Publish that configuration: ```bash php artisan shopper:component:publish setting ``` Then point the key to your own class in the published file: ```php title="config/shopper/components/setting.php" use App\Livewire\Shopper\StoreSettings; return [ 'pages' => [ 'general' => StoreSettings::class, // ... ], ]; ``` Your class can extend `Shopper\Livewire\Pages\Settings\General`. Save the keys of your own fields with the `SaveSettings` trait, as shown in [Writing Settings](/3.x/settings#writing-settings). The entry of the page on the settings screen is `Shopper\Navigation\Setting\Items\GeneralSetting`, listed in `config/shopper/settings.php` and described in [Configuration](/3.x/configuration#settings). ## Reading the Store Details [#reading-the-store-details] A storefront reads the store details with `shopper_setting()`. This view composer gives the footer the contact details and the social links, with the label of each platform: ```php title="app/View/Composers/StoreFooterComposer.php" find(shopper_setting('country_id')); $socialLinks = collect(shopper_setting('social_links') ?? []) ->filter(fn (array $link): bool => SocialPlatform::tryFrom($link['platform']) !== null) ->map(fn (array $link): array => [ 'label' => SocialPlatform::from($link['platform'])->getLabel(), 'url' => $link['url'], ]) ->values(); $view->with([ 'storeName' => shopper_setting('name'), 'storeEmail' => shopper_setting('email'), 'storePhone' => shopper_setting('phone_number'), 'storeAddress' => [ shopper_setting('street_address'), shopper_setting('postal_code').' '.shopper_setting('city'), $country?->translated_name, ], 'socialLinks' => $socialLinks, ]); } } ``` Register it in a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\View\Composers\StoreFooterComposer; use Illuminate\Support\Facades\View; public function boot(): void { View::composer('components.footer', StoreFooterComposer::class); } ``` `shopper_setting()` caches each value for 24 hours, and the wizard and the General page clear the cache of every key they save, so the footer shows a merchant's edit on the next request. The [Caching](/3.x/settings#caching) section covers the cases where a value stays cached. ## Events [#events] Shopper dispatches no event of its own when the store details change. The wizard and the General page write each key with `Setting::query()->updateOrCreate()`, so the Eloquent `saved` event of `Shopper\Core\Models\Setting` fires once for each key they save. Listen to it to clear a cache of your own: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Setting; public function boot(): void { Setting::saved(function (Setting $setting): void { if (in_array($setting->key, ['name', 'email', 'phone_number', 'social_links'], true)) { Cache::forget('storefront.footer'); } }); } ``` ## Permissions [#permissions] The wizard opens for administrators and for users with the `system.settings` permission, and answers with a 403 error to anyone else. The General page checks `system.settings` when it opens and again when it saves. The [System Permissions](/3.x/acl#system-permissions) section lists what `system.settings` gives access to. ## In the Admin [#in-the-admin] Merchants complete the setup wizard once, on their first login, in three steps: Information, Address and Social Links. They edit the same details later under **Settings**, **General**, along with the legal name, the about text, the logo and the cover photo. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API returns the store details at `GET /store/settings`, without authentication: the name, legal name, about text, email, phone number, address, country, logo and cover URLs, social links and currencies. The [Store API](/3.x/settings#store-api) section of the Settings page lists the attributes and how to expose a key of your own, and the Store API [Store and Regions](/3.x/store-api/store#reading-the-store-settings) guide covers the endpoint. # Suppliers (/3.x/suppliers) A supplier is the vendor or manufacturer that ships a product for you. Shopper uses suppliers for dropshipping: the merchant links an External product to its supplier, forwards the order to that supplier once the customer has paid, and the supplier ships the parcel to the customer. The store never holds stock of that product. Shopper stores the supplier, the link between a product and its supplier, and the fulfillment status of each order item. It does not contact the supplier: placing the order with the supplier and reading its tracking number are up to your code, as shown in [Dropshipping Workflow](#dropshipping-workflow). Suppliers are disabled on a fresh install. Enable them in `config/shopper/features.php`, as shown in [Feature Flag](#feature-flag). ## Model [#model] The model is `Shopper\Core\Models\Supplier`. It implements the `Shopper\Core\Models\Contracts\Supplier` contract, which declares the `products` relationship, and it is registered under the `supplier` key of `config/shopper/models.php`, so you can swap it. Two traits change what you can do with a supplier. `HasSlug` cleans every slug you assign and adds `findBySlug()`, as described in [Creating Suppliers](#creating-suppliers). `HasPublicId` fills `public_id` with a ULID when a supplier is created, and adds `findByPublicId()` and the `wherePublicId` scope, as described in [Public IDs](/3.x/models#public-ids). The model casts `is_enabled` to a boolean and `metadata` to an array. ### Extending the Model [#extending-the-model] To add relationships or methods, extend the core class: ```php title="app/Models/Supplier.php" hasMany(PurchaseOrder::class); } } ``` Then register your class in `config/shopper/models.php`: ```php title="config/shopper/models.php" return [ 'supplier' => App\Models\Supplier::class, ]; ``` Run `php artisan config:cache` in production after the change. The [Models](/3.x/models#swapping-a-model) page explains what follows your class once it is registered. ## Database Schema [#database-schema] Suppliers are stored in the `sh_suppliers` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Supplier name | | `slug` | string | yes | null | URL-friendly identifier, unique | | `email` | string | yes | null | Contact email | | `phone` | string | yes | null | Contact phone | | `contact_name` | string | yes | null | Name of the person you deal with | | `website` | string | yes | null | Supplier website URL | | `description` | longText | yes | null | Description of the supplier | | `notes` | longText | yes | null | Internal notes | | `is_enabled` | boolean | no | false | Whether the supplier can be linked to products | | `metadata` | jsonb | yes | null | Additional custom data | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The products table holds the link in a nullable, indexed `supplier_id` column. Its foreign key sets it to `null` when the supplier is deleted, so deleting a supplier keeps its products. ## Relationships [#relationships] A supplier has many products, and a product belongs to at most one supplier. ### Products [#products] `products` returns the products linked to the supplier, as instances of the class configured for the `product` key: ```php $catalog = $supplier->products() ->publish() ->orderBy('name') ->get(); $count = $supplier->products()->count(); ``` ### Product to Supplier [#product--supplier] `supplier` on a product returns its supplier, or `null` when the product has none: ```php $supplier = $product->supplier; $isDropshipped = $product->supplier_id !== null; ``` ## Query Scopes [#query-scopes] The `enabled` scope keeps the enabled suppliers. `findBySlug()` throws a `ModelNotFoundException` when no supplier matches, and `findByPublicId()` returns `null`: ```php use Shopper\Core\Models\Contracts\Supplier; $suppliers = resolve(Supplier::class)::query()->enabled()->get(); $techParts = resolve(Supplier::class)::findBySlug('techparts'); ``` ## Configuration [#configuration] Suppliers are off by default. Their settings are the feature flag, the model key described in [Extending the Model](#extending-the-model), and the admin components. ### Feature Flag [#feature-flag] Enable suppliers in `config/shopper/features.php`: ```php title="config/shopper/features.php" use Shopper\Enum\FeatureState; return [ 'supplier' => FeatureState::Enabled, ]; ``` Once enabled, the suppliers page is registered at `/cpanel/products/suppliers`, a Suppliers item appears under Catalog, Products in the sidebar, and the product page of an External product shows a Supplier field. The flag only changes the admin panel: the model and the `supplier_id` column work whether it is on or off. The [Configuration](/3.x/configuration#feature-flags) page lists every feature flag. ### Components [#components] The suppliers page and form belong to the product section of the admin panel. Publish its component file to replace either with your own Livewire component: ```bash php artisan shopper:component:publish product ``` The command creates `config/shopper/components/product.php`. The supplier entries are these two: | Key | Group | Default class | |-----|-------|---------------| | `supplier-index` | `pages` | `Shopper\Livewire\Pages\Supplier\Index` | | `slide-overs.supplier-form` | `components` | `Shopper\Livewire\SlideOvers\SupplierForm` | To add content above or below the suppliers table without replacing the page, register a view on the `SUPPLIERS_TABLE_BEFORE` or `SUPPLIERS_TABLE_AFTER` render hook. They are constants of `Shopper\View\SalesRenderHook`. The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below resolve the supplier class from its contract, so they keep working after you swap the model. ### Creating Suppliers [#creating-suppliers] The model accepts every column through `create()`. Pass a slug: it is not derived from the name in code, only the admin form fills it from the name when the field is left empty. ```php use Shopper\Core\Models\Contracts\Supplier; $techParts = resolve(Supplier::class)::query()->create([ 'name' => 'TechParts Co., Ltd', 'slug' => 'techparts', 'email' => 'orders@techparts.com', 'phone' => '+86 755 1234 5678', 'contact_name' => 'Zhang Wei', 'website' => 'https://techparts.com', 'description' => '

    Electronics components and accessories manufacturer based in Shenzhen.

    ', 'notes' => 'Minimum order: 50 units. Lead time: 5-7 days.', 'is_enabled' => true, ]); ``` The `HasSlug` trait runs every slug through `Str::slug()` and appends a counter when another supplier has it already: `techparts-1`, then `techparts-2`. ### Updating Status [#updating-status] `updateStatus()` enables a supplier, or disables it when you pass `false`. The admin form only offers enabled suppliers on the product page: ```php $techParts->updateStatus(); $techParts->updateStatus(false); ``` ### Retrieving Suppliers [#retrieving-suppliers] Load the enabled suppliers with the number of products linked to each, or search them by name and email: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Models\Contracts\Supplier; $suppliers = resolve(Supplier::class)::query() ->enabled() ->withCount('products') ->orderBy('name') ->get(); $results = resolve(Supplier::class)::query() ->enabled() ->where(fn (Builder $query) => $query ->where('name', 'like', "%{$search}%") ->orWhere('email', 'like', "%{$search}%")) ->get(); ``` ### Metadata [#metadata] The `metadata` column stores data that has no column of its own, cast to an array. The admin form edits it as a list of keys and values: ```php $techParts->update([ 'metadata' => [ 'payment_terms' => 'net_30', 'currency' => 'USD', 'minimum_order' => 50, 'lead_time_days' => 7, ], ]); $leadTime = $techParts->metadata['lead_time_days'] ?? null; ``` The Store API does not return suppliers, so metadata stays internal to the store. ### Linking Products to Suppliers [#linking-products-to-suppliers] In the admin panel, the link is made on the product page of an [External product](/3.x/products). When suppliers are enabled, that page shows two required fields: the External ID, the product's identifier in the supplier's catalog, unique across products, and the Supplier, chosen among the enabled suppliers. Products of the other types show no supplier field. In code, set `supplier_id` on the product. The column accepts any product type: ```php use Shopper\Core\Enum\ProductType; use Shopper\Core\Models\Contracts\Product; $earbuds = resolve(Product::class)::query()->create([ 'name' => 'Wireless Bluetooth Earbuds', 'slug' => 'wireless-bluetooth-earbuds', 'type' => ProductType::External, 'external_id' => 'TP-EB-2041', 'supplier_id' => $techParts->id, 'is_visible' => true, 'published_at' => now(), ]); $earbuds->update(['supplier_id' => $otherSupplier->id]); $earbuds->update(['supplier_id' => null]); ``` The Store API refuses External products in carts: adding one answers with the `purchasable_unavailable` error. A storefront built on the Store API can display a supplier's External products but cannot sell them. See [From a Storefront](#from-a-storefront). ## Dropshipping Workflow [#dropshipping-workflow] An order of a supplier's product follows the usual [order](/3.x/orders) and [fulfillment](/3.x/fulfillment) flow. What changes is who ships: you forward the items to the supplier, then record the shipment with the tracking number the supplier sends back. ### 1. Setup [#1-setup] Create the supplier and link its products, as shown in [Creating Suppliers](#creating-suppliers) and [Linking Products to Suppliers](#linking-products-to-suppliers): ```php $earbuds->update(['supplier_id' => $techParts->id]); ``` ### 2. Customer Places Order [#2-customer-places-order] The order is created as any other. Each order item starts with the `Pending` fulfillment status and points to what the customer bought through its polymorphic `product` relationship: the product, or the variant for a product with variants. ### 3. Forward to Supplier [#3-forward-to-supplier] After the customer has paid, place the order with the supplier, using the shipping address of the order. Then mark the supplier's items as forwarded. Shopper never sets the `ForwardedToSupplier` status itself; your code does: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Enum\FulfillmentStatus; $order->items() ->where('fulfillment_status', FulfillmentStatus::Pending) ->whereHasMorph( 'product', [config('shopper.models.product')], fn (Builder $query) => $query->where('supplier_id', $techParts->id), ) ->update(['fulfillment_status' => FulfillmentStatus::ForwardedToSupplier]); ``` Use `whereHasMorph()` with the product class. `whereHas()` on a polymorphic relationship queries the table of every type stored in `product_type`, and the variants table has no `supplier_id` column. ### 4. Supplier Ships [#4-supplier-ships] When the supplier sends its tracking number, create a shipment for the forwarded items with `CreateShipmentAction`. Pass the ID of a [carrier](/3.x/carriers) when the supplier ships with one you have set up, or `null`: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Actions\CreateShipmentAction; use Shopper\Core\Actions\RecordShipmentEventAction; use Shopper\Core\Enum\FulfillmentStatus; use Shopper\Core\Enum\ShipmentStatus; $itemIds = $order->items() ->where('fulfillment_status', FulfillmentStatus::ForwardedToSupplier) ->whereHasMorph( 'product', [config('shopper.models.product')], fn (Builder $query) => $query->where('supplier_id', $techParts->id), ) ->pluck('id') ->all(); $shipment = resolve(CreateShipmentAction::class)->execute( $order, carrierId: null, itemIds: $itemIds, trackingNumber: 'YT2412345678901234', trackingUrl: 'https://t.17track.net/en#nums=YT2412345678901234', ); $shipment->items()->update(['fulfillment_status' => FulfillmentStatus::Shipped]); resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::PickedUp); ``` The shipment is created with the `Pending` status and takes only the items that are not in another shipment yet. Recording the pickup stamps `shipped_at`, moves a New order to Processing and updates the order's shipping status. The pickup moves `Pending` items to `Shipped` and leaves `ForwardedToSupplier` items as they are, which is why the example sets them to `Shipped` first. ### 5. Delivery Confirmation [#5-delivery-confirmation] When the supplier confirms the delivery, record it on the shipment. A manual event follows the allowed transitions, so a picked-up shipment goes out for delivery before it is delivered; `execute()` returns `null` and changes nothing when the transition is not allowed: ```php resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::OutForDelivery); resolve(RecordShipmentEventAction::class)->execute($shipment, ShipmentStatus::Delivered); ``` The Delivered event stamps `received_at`, moves the shipment's items to `Delivered`, completes a paid order once all its items are delivered, and dispatches `OrderShipmentDelivered`. The [Events](/3.x/events#shipment-events) page lists the shipment events. ## Querying by Supplier [#querying-by-supplier] Order items carry no `supplier_id`: query them through their product. The first query lists the items still waiting on a supplier, with what you need to place the order; the second sums the delivered sales of a supplier, in cents as described in [Money](/3.x/money), before discounts, and before taxes unless the order's tax zone includes them in prices: ```php use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\DB; use Shopper\Core\Enum\FulfillmentStatus; use Shopper\Core\Models\OrderItem; $waiting = OrderItem::query() ->whereIn('fulfillment_status', [ FulfillmentStatus::Pending, FulfillmentStatus::ForwardedToSupplier, ]) ->whereHasMorph( 'product', [config('shopper.models.product')], fn (Builder $query) => $query->where('supplier_id', $techParts->id), ) ->with(['order.customer', 'order.shippingAddress']) ->get(); $delivered = OrderItem::query() ->where('fulfillment_status', FulfillmentStatus::Delivered) ->whereHasMorph( 'product', [config('shopper.models.product')], fn (Builder $query) => $query->where('supplier_id', $techParts->id), ) ->sum(DB::raw('unit_price_amount * quantity')); ``` These queries match the items of products linked to the supplier. External products have no variants. If you link a product with variants in code, its order items point to the variants: add `config('shopper.models.variant')` to the types and filter on the variant's `product` relationship. ## Events [#events] Shopper dispatches no supplier event of its own. Listen to the Eloquent model events instead. They are dispatched under the core class name as well, so a listener registered on `Shopper\Core\Models\Supplier` keeps firing after you swap the model. A store that stops selling the products of a disabled supplier can hide them: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Core\Models\Supplier; public function boot(): void { Supplier::updated(function (Supplier $supplier): void { if ($supplier->wasChanged('is_enabled') && ! $supplier->is_enabled) { $supplier->products()->get()->each->update(['is_visible' => false]); } }); } ``` Updating each product, instead of one query on the relationship, fires the product events that resync collections and the search index. The [Events](/3.x/events#listening-to-events) page covers listeners and queues. ## Permissions [#permissions] The admin panel checks four permissions of the `suppliers` resource, in the Products group: | Permission | Allows | |------------|--------| | `suppliers.browse` | Opening the suppliers page and seeing the Suppliers sidebar item | | `suppliers.create` | Opening the form for a new supplier | | `suppliers.edit` | Editing a supplier, enabling and disabling suppliers in bulk | | `suppliers.delete` | Deleting a supplier, one at a time or in bulk | `suppliers.read` is seeded with the others, but the admin panel never checks it. Linking a product to a supplier happens on the product page, which requires `products.edit`. Shopper 2.x named these permissions `browse_suppliers`, `add_suppliers` and so on; the [Access Control](/3.x/acl#upgrading-from-2x) page explains how the upgrade renames them. ## In the Admin [#in-the-admin] Merchants manage suppliers under Catalog, Products, Suppliers, once the feature flag is on. The page lists each supplier with its name, email, contact, phone, visibility and last update, and filters by visibility. Bulk actions enable, disable or delete the selected suppliers. The supplier form opens in a slide-over with three sections: General (name, slug, email, phone, contact name, website, visibility), Description (description and internal notes) and Metadata. The Supplier field of an External product sits on its product page. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API does not expose suppliers: no endpoint lists them, and the product resource carries neither `supplier_id` nor a supplier relationship. An External product carries its `external_id`, and its `in_stock` is always `true`, because the supplier holds the stock. The cart endpoints refuse External products with the `purchasable_unavailable` error, so they cannot be bought through the Store API. The Store API [Cart](/3.x/store-api/cart#errors) guide lists the cart errors. # Taxes (/3.x/taxes) Shopper computes taxes for each cart line from the address the order ships to. You define tax zones (a country, or a province of a country), give each zone one or more percentage rates, and attach rules to the rates that apply only to some products, product types or categories. The cart pipeline applies them every time a cart is calculated, and the order keeps a copy of each line's taxes when it is placed. Tax amounts are integers in cents, like every amount in Shopper. The [Money](/3.x/money) page covers cents and formatting. ## How It Works [#how-it-works] The tax system has four parts: 1. `TaxZone`: a country, or a province within a country, with its tax behavior (prices with or without tax) and an optional tax provider. 2. `TaxRate`: a percentage attached to a zone. The default rate of a zone applies to every item that no rule targets. 3. `TaxRateRule`: a target on a rate. When a cart line matches a rule, that rate replaces the default rate of the zone. 4. `TaxCalculationProvider`: the service that receives an item and a context and returns `TaxLine` value objects. The built-in `Shopper\Core\Taxes\SystemTaxProvider` reads the zones, rates and rules above. When a cart is calculated, the `CalculateTax` step reads the shipping address of the cart, `Shopper\Core\Taxes\TaxCalculator` resolves the zone of that address and the provider of the zone, and the step stores one `CartLineTaxLine` for each tax line the provider returns. When the customer checks out, the order copies those lines. ## Tax Zones [#tax-zones] A tax zone defines where a tax configuration applies: a country, and optionally a province or state of that country. Its most important setting is `is_tax_inclusive`, which says whether the prices of the store already include tax (VAT, as in Europe) or whether tax is added on top of them (sales tax, as in the United States). The model is `Shopper\Core\Models\TaxZone`. It implements the `Shopper\Core\Models\Contracts\TaxZone` contract and is registered under the `tax_zone` key of `config/shopper/models.php`, so resolve it from the contract in shared code: ```php use Shopper\Core\Models\Contracts\TaxZone; use Shopper\Core\Models\Country; $france = Country::query()->where('cca2', 'FR')->firstOrFail(); $franceZone = resolve(TaxZone::class)::query()->create([ 'country_id' => $france->id, 'name' => 'Standard VAT', 'is_tax_inclusive' => true, ]); ``` A zone with a `province_code` applies to one province or state only: ```php $usa = Country::query()->where('cca2', 'US')->firstOrFail(); $californiaZone = resolve(TaxZone::class)::query()->create([ 'country_id' => $usa->id, 'province_code' => 'US-CA', 'name' => 'California', 'is_tax_inclusive' => false, ]); ``` To find the zone of a shipping address, the calculator first looks for a zone of the address country whose `province_code` equals the `state` of the address. When none exists, it falls back to the zone of that country with no `province_code`. When the country has no zone either, the cart has no tax. The comparison is an exact string match. The admin panel suggests ISO 3166-2 codes such as `US-CA` or `FR-IDF`; whichever format you choose for `province_code`, your storefront must send the same value in the `state` of the shipping address. The `display_name` attribute returns the translated name of the country, followed by the zone name when the zone has one. ### Zone Schema [#zone-schema] Zones are stored in the `sh_tax_zones` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `country_id` | bigint | yes | null | The country of the zone, set to null when the country is deleted | | `parent_id` | bigint | yes | null | Parent zone, stored for your own code: `SystemTaxProvider` does not read it | | `provider_id` | bigint | yes | null | The [tax provider](#tax-providers) of the zone, the default provider when null | | `name` | string | yes | null | Label of the zone | | `province_code` | string | yes | null | Province or state, compared with the `state` of the shipping address | | `is_tax_inclusive` | boolean | no | `false` | Whether prices already include tax | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The pair of `country_id` and `province_code` is unique. ### Zone Relationships [#zone-relationships] The relationships load the configured class for zones and rates: | Relationship | Type | Description | |---|---|---| | `country()` | `BelongsTo` | The country of the zone | | `rates()` | `HasMany` | The tax rates of the zone | | `provider()` | `BelongsTo` | The `TaxProvider` assigned to the zone | | `parent()` | `BelongsTo` | The parent zone | | `children()` | `HasMany` | The child zones | ## Tax Rates [#tax-rates] Each zone has one or more rates. The rate marked `is_default` applies to every item of the zone that no rule targets. France charges 20% VAT on most goods: ```php use Shopper\Core\Models\Contracts\TaxRate; $standardVat = resolve(TaxRate::class)::query()->create([ 'tax_zone_id' => $franceZone->id, 'name' => 'TVA 20%', 'code' => 'FR_VAT_STANDARD', 'rate' => 20, 'is_default' => true, ]); ``` France also has a reduced rate of 5.5% on food. Create it as a second rate of the same zone, then point it at the right products with a [rule](#tax-rate-rules): ```php $reducedVat = resolve(TaxRate::class)::query()->create([ 'tax_zone_id' => $franceZone->id, 'name' => 'TVA 5.5%', 'code' => 'FR_VAT_REDUCED', 'rate' => 5.5, 'is_default' => false, ]); ``` Give each zone exactly one default rate. Nothing prevents a second one, and the system provider then uses whichever it loads first. A zone without a default rate taxes only the items that a rule targets. The model is `Shopper\Core\Models\TaxRate`. It implements the `Shopper\Core\Models\Contracts\TaxRate` contract and is registered under the `tax_rate` key of `config/shopper/models.php`. ### Tax Rate Schema [#tax-rate-schema] Rates are stored in the `sh_tax_rates` table: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `tax_zone_id` | bigint | no | - | The zone of the rate, deleting the zone deletes its rates | | `name` | string | no | - | Name stored on the tax lines and shown on invoices (`TVA 20%`) | | `code` | string | yes | null | Machine-readable identifier (`FR_VAT_STANDARD`) | | `rate` | decimal(8,4) | no | `0` | Percentage, `20` means 20%, cast to a float | | `is_default` | boolean | no | `false` | Applies when no rule matches the item | | `is_combinable` | boolean | no | `false` | Stored and shown in the admin panel: `SystemTaxProvider` does not read it | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Rate Relationships [#rate-relationships] A rate belongs to its zone and holds the rules that select it: | Relationship | Type | Description | |---|---|---| | `taxZone()` | `BelongsTo` | The zone of the rate | | `rules()` | `HasMany` | The `TaxRateRule` records that apply this rate to some items | ## Tax Rate Rules [#tax-rate-rules] A rule applies a rate to some items instead of the default rate of the zone. The system provider loads the rates of the zone with their rules, goes through the rates that have rules, and uses the first rate with a rule that matches the item. When no rule matches, it uses the default rate. The rates are not sorted, so avoid two rates of the same zone whose rules match the same item. A rule has two fields: `reference_type` says what kind of value to match, and `reference_id` holds that value as a string. This rule applies the reduced rate to every product of the "Groceries" category: ```php use Shopper\Core\Models\TaxRateRule; TaxRateRule::query()->create([ 'tax_rate_id' => $reducedVat->id, 'reference_type' => 'category', 'reference_id' => (string) $groceries->id, ]); ``` A rule can also target one product: ```php TaxRateRule::query()->create([ 'tax_rate_id' => $zeroRate->id, 'reference_type' => 'product', 'reference_id' => (string) $childrensBook->id, ]); ``` Or every product of a [product type](/3.x/products#how-products-work), such as virtual goods: ```php TaxRateRule::query()->create([ 'tax_rate_id' => $digitalServicesRate->id, 'reference_type' => 'product_type', 'reference_id' => 'virtual', ]); ``` `Shopper\Core\Models\TaxRateRule` has no configuration key, so it is always loaded with its own class (see [Models You Cannot Swap](/3.x/models#models-you-cannot-swap)). ### Rule Reference Types [#rule-reference-types] For a cart line that holds a variant, the rule reads the parent product of the variant: its ID, its type and its categories. | `reference_type` | `reference_id` | Matches when | |---|---|---| | `product_type` | A `ProductType` value: `standard`, `variant`, `virtual` or `external` | The type of the product equals the value | | `product` | A product ID, as a string | The product has that ID | | `category` | A category ID, as a string | The product is attached to that category. A product attached only to a child category does not match its parent | A product with variants has the type `variant`. The override form of the admin panel offers `standard`, `virtual` and `external` only, so a rule on `variant` products is created in code. ### Rule Schema [#rule-schema] Rules are stored in the `sh_tax_rate_rules` table: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `tax_rate_id` | bigint | no | - | The rate the rule selects, deleting the rate deletes its rules | | `reference_type` | string | no | - | `product_type`, `product` or `category` | | `reference_id` | string | no | - | The value to match | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The combination of `tax_rate_id`, `reference_type` and `reference_id` is unique: the same rule cannot be attached twice to a rate. ## Configuration [#configuration] Taxes have no feature flag. The `CalculateTax` step is part of the `cart` pipeline in `config/shopper/cart.php`, after the discount steps and before the totals; the [cart](/3.x/cart#calculation-pipeline) page describes the pipeline. To add methods or relationships to zones or rates, extend `Shopper\Core\Models\TaxZone` or `Shopper\Core\Models\TaxRate` and register your class: ```php title="config/shopper/models.php" 'tax_zone' => App\Models\TaxZone::class, 'tax_rate' => App\Models\TaxRate::class, ``` The [Models](/3.x/models#swapping-a-model) page explains how swapping works. `TaxRateRule`, `TaxProvider` and `OrderTaxLine` have no configuration key. ### Zone Cache [#zone-cache] `TaxCalculator` keeps the zone it resolves for each country and province in the application cache, under keys that start with `shopper.tax-zones.`, so carts do not query the zones on every calculation. Only the zone is cached: rates and rules are read from the database, and a change to them applies from the next request. Saving or deleting a zone through Eloquent increments the `shopper.tax-zones.version` cache entry, which makes every cached zone obsolete. A change that bypasses model events, such as a mass update with the query builder or a migration, does not. Increment the version yourself after it: ```php use Illuminate\Support\Facades\Cache; Cache::increment('shopper.tax-zones.version'); ``` ## Inclusive vs Exclusive Taxes [#inclusive-vs-exclusive-taxes] The `is_tax_inclusive` flag of the zone decides how the system provider computes the tax of a line and how the cart builds its total. In both cases the provider taxes the whole line total (unit price times quantity, minus the line's discounts) and rounds the result to the nearest cent. In a tax-exclusive zone (sales tax), tax is added on top of the price: ```text tax = round(line_total * rate / 100) total = line_total + tax ``` A line of 10000 cents in a zone at 10% gets 1000 cents of tax, and the customer pays 11000 cents. In a tax-inclusive zone (VAT), the price already contains the tax, and the provider extracts it: ```text tax = round(line_total - line_total / (1 + rate / 100)) total = line_total ``` A line of 10000 cents at 20% VAT contains 10000 - 10000 / 1.2 = 1666.67, rounded to 1667 cents of tax, and 8333 cents before tax. The customer pays 10000 cents. The cart pipeline exposes the flag as `taxInclusive` on its context, and the Store API as `tax_inclusive` on the cart, so a storefront can show "VAT included" or add the tax as a separate line at checkout. Shipping is added to the total as it is, in both cases: Shopper creates no tax line for shipping. ## Cart Integration [#cart-integration] Tax calculation is a step of the cart pipeline. `Shopper\Cart\Pipelines\CalculateTax` runs after the automatic promotions and the discount codes, so the tax base of a line is its subtotal minus its discount adjustments. The step reads the country (`cca2`) and the `state` of the cart's shipping address. When the cart has no shipping address, or the address has no country, the step does nothing and the cart has no tax. Otherwise it builds a `TaxCalculationContext` with the country code, the `state` as province code and the customer ID of the cart, then, for each cart line: 1. Deletes the existing `CartLineTaxLine` records of the line. 2. Skips the line when its taxable amount is zero or less. 3. Wraps the line in a `Shopper\Cart\Taxes\CartLineTaxAdapter` and passes it to `TaxCalculator::calculate()`. 4. Stores one `CartLineTaxLine` for each returned `TaxLine`, and adds the amounts to `taxTotal` on the pipeline context. It then sets `taxInclusive` from the zone of the address, or to `false` when no zone matches. Calculate a cart through the cart manager and read the taxes from the context and the lines: ```php use Shopper\Cart\CartManager; $context = resolve(CartManager::class)->calculate($cart); $context->taxTotal; $context->taxInclusive; $cart->load('lines.taxLines'); foreach ($cart->lines as $line) { foreach ($line->taxLines as $taxLine) { $taxLine->name; $taxLine->rate; $taxLine->amount; } } ``` `Shopper\Cart\Models\CartLineTaxLine` stores the same `code`, `name`, `rate`, `amount` and `tax_rate_id` columns as an [order tax line](#ordertaxline-schema), with a `cart_line_id` in place of the polymorphic owner. When a provider returns a tax line without a code, the step stores the name as the code. Once the customer has opened a payment with a provider driver (any driver other than `manual`), the cart keeps its tax lines: `CalculateTax` sums the stored lines instead of computing them again, and `taxInclusive` comes from the payment session. A change that alters the total, such as a new shipping address, releases the payment session first, and the next calculation computes the taxes again. The amount the customer authorizes stays equal to the total of the order. The [payments](/3.x/payments) page covers payment sessions. ## Persisting Tax Lines on Orders [#persisting-tax-lines-on-orders] When a cart becomes an order, `Shopper\Cart\Actions\CreateOrderFromCartAction` calculates the cart one last time, then copies its taxes to the order (see [order conversion](/3.x/cart#order-conversion)): - the `tax_amount` of the order is the tax total of the cart; - the `tax_amount` of each order item is the sum of the tax lines of its cart line; - each tax line of a cart line becomes an `OrderTaxLine` attached to the order item, with its `code`, `name`, `rate`, `amount` and `tax_rate_id`. The order keeps these values: editing or deleting a zone or a rate later does not change the orders already placed. Deleting a rate sets `tax_rate_id` to null on its tax lines and keeps the other columns. Tax lines are attached to order items only. The model is `Shopper\Core\Models\OrderTaxLine`, which implements the `Shopper\Core\Models\Contracts\OrderTaxLine` contract. Its `taxable()` relationship returns the order item, and `taxRate()` the rate it was computed from. ### OrderTaxLine Schema [#ordertaxline-schema] Order tax lines are stored in the `sh_order_tax_lines` table: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `taxable_type` | string | no | - | Class of the owner, `Shopper\Core\Models\OrderItem` for the lines Shopper creates | | `taxable_id` | bigint | no | - | ID of the owner | | `code` | string | no | - | Code of the rate when the order was placed | | `name` | string | no | - | Name of the rate when the order was placed | | `rate` | decimal(8,4) | no | - | Percentage when the order was placed, cast to a float | | `amount` | integer (unsigned) | no | `0` | Tax amount in cents | | `tax_rate_id` | bigint | yes | null | The rate used, set to null when the rate is deleted | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | ### Accessing Tax Lines on an Order [#accessing-tax-lines-on-an-order] Load the tax lines with the items of the order: ```php use Shopper\Core\Models\Contracts\Order; $order = resolve(Order::class)::query() ->with('items.taxLines') ->findOrFail($orderId); $order->tax_amount; foreach ($order->items as $item) { $item->tax_amount; foreach ($item->taxLines as $taxLine) { $taxLine->name; $taxLine->rate; $taxLine->amount; } } ``` An invoice often lists the tax per rate. Group the lines of every item by code: ```php $taxSummary = $order->items ->flatMap->taxLines ->groupBy('code') ->map->sum('amount'); ``` ## Tax Providers [#tax-providers] A provider computes the tax lines of an item. Shopper binds the `Shopper\Core\Contracts\TaxCalculationProvider` contract to `SystemTaxProvider`, which applies the zones, rates and rules of the database, and `TaxCalculator` uses it as the default provider. A `Shopper\Core\Models\TaxProvider` record assigns another provider to a zone. When the zone of an address has a `provider_id` and that provider is enabled, the calculator resolves `TaxCalculationProvider` from the container again, with the `identifier` of the record as the `provider` parameter. When the provider is disabled, the zone uses the default provider. ### Provider Schema [#provider-schema] Providers are stored in the `sh_tax_providers` table: | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `identifier` | string | no | - | Unique code of the provider (`avalara`, `taxjar`) | | `is_enabled` | boolean | no | `true` | Whether zones use this provider | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | The model has a `taxZones()` relationship and an `isEnabled()` method. ### Custom Tax Providers [#custom-tax-providers] For regions that need an external tax service such as Avalara or TaxJar, implement the `TaxCalculationProvider` contract and assign your provider to those zones. The contract has two methods: ```php use Shopper\Core\Contracts\TaxableItem; use Shopper\Core\Taxes\TaxCalculationContext; use Shopper\Core\Taxes\TaxLine; interface TaxCalculationProvider { public function identifier(): string; /** @return array */ public function getTaxLines(TaxableItem $item, TaxCalculationContext $context): array; } ``` This provider asks an Avalara client of your application for the tax of each item: ```php title="app/Taxes/AvalaraTaxProvider.php" resolvedZone; $defaultRate = $zone->rates()->where('is_default', true)->firstOrFail(); $quote = $this->client->quote( amount: $item->getTaxableTotal(), countryCode: $context->countryCode, provinceCode: $context->provinceCode, taxIncluded: $zone->is_tax_inclusive, ); return [ new TaxLine( taxRateId: $defaultRate->id, name: $quote->jurisdictionName, code: $quote->jurisdictionCode, rate: $quote->rate, amount: $quote->taxAmountInCents, ), ]; } } ``` Two values of a `TaxLine` must follow the zone. `taxRateId` is stored in the `tax_rate_id` foreign key of the cart and order tax lines, so it must be the ID of an existing rate: give the zone a default rate and reference it. And the cart reads `is_tax_inclusive` from the zone to build its total, whatever provider computed the lines, so the amount must be the tax contained in the price for an inclusive zone and the tax added to it for an exclusive one. Register the provider in a service provider of your application. `TaxCalculator` receives its default provider from the same `TaxCalculationProvider` binding, so binding the contract straight to your class would make it the provider of every zone. Bind it to a closure that returns your class for its identifier and the system provider otherwise: ```php title="app/Providers/AppServiceProvider.php" use App\Taxes\AvalaraTaxProvider; use Illuminate\Contracts\Foundation\Application; use Shopper\Core\Contracts\TaxCalculationProvider; use Shopper\Core\Taxes\SystemTaxProvider; public function register(): void { $this->app->scoped( TaxCalculationProvider::class, fn (Application $app, array $parameters): TaxCalculationProvider => match ($parameters['provider'] ?? null) { 'avalara' => $app->make(AvalaraTaxProvider::class), default => $app->make(SystemTaxProvider::class), }, ); } ``` Then create the `TaxProvider` record and assign it to the zones that use it: ```php use Shopper\Core\Models\TaxProvider; $avalara = TaxProvider::query()->create([ 'identifier' => 'avalara', 'is_enabled' => true, ]); $californiaZone->update(['provider_id' => $avalara->id]); ``` The `identifier` of the record and the key you match in the binding select the class: Shopper does not call the `identifier()` method. Return the same value from it to keep the three in line. The calculator resolves the provider once per country and province during a request. ### The TaxCalculationContext [#the-taxcalculationcontext] `Shopper\Core\Taxes\TaxCalculationContext` is a read-only value object that carries what the calculator needs to resolve the zone and the provider: | Property | Type | Description | |---|---|---| | `countryCode` | `string` | ISO 3166-1 alpha-2 country code (`FR`, `US`, `DE`) | | `provinceCode` | `?string` | Province or state, compared with the `province_code` of the zones | | `customerId` | `?int` | ID of the customer of the cart. `SystemTaxProvider` does not read it | | `resolvedZone` | `?TaxZone` | The zone, set by the calculator before it calls the provider | ### The TaxableItem Contract [#the-taxableitem-contract] Any object you pass to `TaxCalculator::calculate()` implements `Shopper\Core\Contracts\TaxableItem`: | Method | Return | Description | |--------|--------|-------------| | `getTaxableTotal()` | `int` | The taxable total of the whole line in cents, after its discounts | | `getProductType()` | `?string` | The `ProductType` value of the product | | `getProductId()` | `?int` | The ID of the product | | `getCategoryIds()` | `array` | The IDs of the categories the product is attached to | The contract asks for the line total rather than a unit amount and a quantity. The provider taxes that total in one pass, so a line whose discount does not divide evenly by its quantity is never rounded per unit: exclusive zones do not overcharge by a cent, and inclusive breakdowns stay balanced (the amount before tax plus the tax equals the price). Shopper ships one adapter, `Shopper\Cart\Taxes\CartLineTaxAdapter`, which wraps a cart line during cart calculation. To compute a tax outside a cart, such as the price with tax on a product page of a sales-tax store, implement the contract on your own class: ```php title="app/Taxes/ProductPriceTaxableItem.php" amount; } public function getProductType(): ?string { return $this->product->type?->value; } public function getProductId(): ?int { return $this->product->id; } public function getCategoryIds(): array { return $this->product->categories()->pluck('id')->all(); } } ``` Then call the calculator with a context built from the customer's address. `$priceAmount` is the price of the product in cents, in the currency of the customer (see [Pricing](/3.x/pricing)): ```php use App\Taxes\ProductPriceTaxableItem; use Shopper\Core\Taxes\TaxCalculationContext; use Shopper\Core\Taxes\TaxCalculator; $calculator = resolve(TaxCalculator::class); $context = new TaxCalculationContext(countryCode: 'US', provinceCode: 'US-CA'); $taxLines = $calculator->calculate(new ProductPriceTaxableItem($product, $priceAmount), $context); $taxAmount = array_sum(array_column($taxLines, 'amount')); $pricesIncludeTax = $calculator->resolveZone($context)?->is_tax_inclusive ?? false; ``` `calculateMany()` takes an array of items and the same context, and returns their tax lines in the same order. ## Events [#events] Shopper dispatches no tax events. To react when a zone or a rate changes, listen to the Eloquent events of the models, such as `eloquent.saved: Shopper\Core\Models\TaxZone`. The [Events](/3.x/events) page lists the events Shopper dispatches. ## Permissions [#permissions] The Taxes page of the admin panel and every action on it (adding, editing and deleting zones, rates and overrides) check the `system.settings` permission. The [Permissions](/3.x/acl) page describes it. ## In the Admin [#in-the-admin] Merchants manage taxes on the Taxes page of the settings. They add a zone for a country and an optional province code, choose whether prices include tax, and pick a tax provider among the enabled `TaxProvider` records (the admin panel has no screen to create these records). On a zone, "Add Rate" creates a rate and "Create Override" a rate with its targets: product types, products or categories. The setup guide of the dashboard marks its taxes step as done once a zone exists. Set `Items\TaxSetting::class` to `false` in `config/shopper/settings.php` to remove the page from the settings screen ([Configuration](/3.x/configuration#settings)). The [user guide](/3.x/user-guide) walks through the screens. ## From a Storefront [#from-a-storefront] The Store API returns the taxes of a cart with its totals, all in cents: | Resource | Attribute | Content | |----------|-----------|---------| | Cart | `tax_total` | The tax of every line | | Cart | `tax_inclusive` | `true` when the prices of the zone include tax | | Cart line | `tax_total` | The tax of the line | | Cart line | `tax_lines` | The tax lines of the line, each with `code`, `name`, `rate` and `amount` | | Order | `tax_amount` | The tax of the order | For a line of 5000 cents in the French zone above, at 20% VAT included, the attributes of the line include: ```json { "tax_total": 833, "tax_lines": [ { "code": "FR_VAT_STANDARD", "name": "TVA 20%", "rate": 20.0, "amount": 833 } ] } ``` Taxes depend on the shipping address: send it with the cart addresses endpoint, with the country in `country_code` and the province in `state`, in the format of the `province_code` of your zones. Until the cart has a shipping address, `tax_total` is 0. When `tax_inclusive` is `true`, the total already contains `tax_total`: show it as "VAT included". When it is `false`, show it as a line added to the subtotal. The order items of the Store API carry no tax fields, and the Store API exposes no endpoint for tax zones or rates. The Store API [Orders](/3.x/store-api/orders#amounts) guide shows which order amount includes tax. # Team (/3.x/team) A team member is a user of your application's `User` model who holds a role other than the customer role, `config('shopper.admin.roles.user')`. Team members and customers share the `users` table: the role decides who opens the admin panel and what they can do there. Merchants manage the team from Settings, Staff & permissions, at `/cpanel/setting/team` with the default prefix. Roles and permissions are described on the [Permissions](/3.x/acl) page, and the rules that limit what a non-administrator can do on this screen in [Team Management Safeguards](/3.x/acl#team-management-safeguards). ## Team Members [#team-members] Shopper seeds two team roles, `administrator` and `manager`, and both open the admin panel. A member who holds only a role you created, such as a "Fulfillment" role for the warehouse team, opens the admin panel when that role holds the `system.dashboard` permission. The [Roles](/3.x/acl#roles) section lists the seeded roles. A user can hold several roles. A customer who receives the `manager` role keeps their orders and addresses and appears on the Team screen, because the screen lists every user with at least one role other than the customer role. ## Adding a Team Member [#adding-a-team-member] The **Add administrator** button of the Team screen opens a slide-over with three sections: | Section | Fields | |---------|--------| | Login information | Email, password, Send Invite | | Personal information | First name, last name, gender, phone number | | Role information | One or more roles | The email, the password, the first name, the last name and at least one role are required. The **Generate** link next to the password field fills it with a random password of 16 characters. The email address must not belong to an existing user: to give a customer access to the admin panel, assign a role to their account, as shown in [Assigning Roles](#assigning-roles). The role list never shows the customer role, and shows the administrator role only to administrators. Shopper marks the new member's email as verified, so they can sign in at once. ### Preparing the User Model [#preparing-the-user-model] The slide-over creates the user with Eloquent's `create()` method, so your `User` model must accept its attributes by mass assignment. Declare them with the `Fillable` attribute, along with the other columns Shopper writes, explained on the [Customers](/3.x/customers#user-model-integration) page: ```php title="app/Models/User.php" use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; #[Fillable([ 'first_name', 'last_name', 'email', 'password', 'phone_number', 'gender', 'birth_date', 'opt_in', 'email_verified_at', 'avatar_type', 'avatar_location', 'last_login_at', 'last_login_ip', 'store_two_factor_secret', 'store_two_factor_recovery_codes', ])] class User extends Authenticatable implements ShopperUser { use InteractsWithShopper; use Notifiable; } ``` The `Notifiable` trait sends the [welcome email](#welcome-email). Keep the `Hidden` attribute and the other contracts described in [Prepare Your User Model](/3.x/installation#prepare-your-user-model). ### In Code [#in-code] A seeder or an import adds team members the same way, with the role names read from `config('shopper.admin.roles')`: ```php use App\Models\User; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; $user = User::query()->create([ 'first_name' => 'Jane', 'last_name' => 'Cooper', 'email' => 'jane@example.com', 'password' => Hash::make(Str::password(16)), 'email_verified_at' => now(), ]); $user->assignRole(config('shopper.admin.roles.manager')); ``` The `shopper:user` command creates the first administrator from the terminal, as described in [Admin User Creation](/3.x/acl#admin-user-creation). ## Welcome Email [#welcome-email] Shopper creates the account with the password typed or generated in the slide-over. The new member receives access in one of two ways. With **Send Invite** on, Shopper sends the `Shopper\Notifications\AdminSendCredentials` notification by email once the member is created. The message holds the URL of the store from `config('app.url')`, the member's email address and password, a **Login** button to the admin login page, and a request to change the password from the profile page after the first sign-in. The notification is sent during the request, through the `mail` channel, so the mailer of your application must be configured. With **Send Invite** off, Shopper sends nothing. The merchant passes the sign-in details on, or tells the member to open the login page and click **Forgot your password?** to choose their own password. That link is shown while `password_reset` is `true` in `config/shopper/auth.php`, the default. The email text comes from the `mails.admin` keys of Shopper's translation files. When the store enables them, a new member who signs in can turn on [two-factor authentication](/3.x/two-factor) or add a passkey from their profile page. ## Assigning Roles [#assigning-roles] The slide-over gives a member their roles when it creates them. The Team screen does not change the roles of an existing member: change them in code, with the methods of [Assigning Roles](/3.x/acl#assigning-roles). `syncRoles()` replaces every role of the user, so a manager moving to the warehouse team keeps only the new role: ```php use App\Models\User; $user = User::query()->where('email', 'jane@example.com')->firstOrFail(); $user->syncRoles(['fulfillment']); ``` Roles are checked on every request, so the change applies to the member's next page or action in the admin panel. A user who keeps only the customer role, or no role, no longer appears on the Team screen and can no longer open the admin panel. Removing the roles this way keeps the account, unlike deleting it. ## The Team Screen [#the-team-screen] The Team screen has two parts. The roles part shows a card for each role except the customer role, with the number of accounts that hold it. A card opens the role page, which has three tabs: Role for its name, display name and description, Users for the members who hold it, and Permissions. Users with `system.settings` create a role from the button next to the title. The Administrators accounts table lists the team members: | Column | Content | |--------|---------| | Full name | The member's name and photo, with a badge on your own row | | Role | Every role the member holds | | Joined | The creation date of the account | | Last signed in | The `last_login_at` column of the user | Each row has a **Copy user ID** action and a **Delete user** action. The `shopper:user` command fills `last_login_at` when it creates an administrator, and the sign-in of the admin panel does not update it. To keep the column current, update it from a listener on Laravel's `Login` event, which the admin panel dispatches on every password and passkey sign-in: ```php title="app/Listeners/RecordTeamMemberSignIn.php" namespace App\Listeners; use Illuminate\Auth\Events\Login; class RecordTeamMemberSignIn { public function handle(Login $event): void { $event->user->forceFill([ 'last_login_at' => now(), 'last_login_ip' => request()->ip(), ])->saveQuietly(); } } ``` `saveQuietly()` skips the model events, so a sign-in does not reindex the user in the search engine. ## Removing a Team Member [#removing-a-team-member] Only an administrator deletes team members, one at a time with **Delete user** or several at once with the bulk action. Neither action can delete your own account or the last administrator, as listed in [Team Management Safeguards](/3.x/acl#team-management-safeguards). Deleting a team member deletes the user. Shopper detaches their roles and deletes their addresses first. Orders the user placed as a customer stay in the store, without a customer. To take away access and keep the account, remove the roles instead, as shown in [Assigning Roles](#assigning-roles). ## Permissions [#permissions] The Team screen checks two system permissions, and keeps two actions for administrators: | Permission | Allows | |------------|--------| | `system.users` | Opening the Team screen and the role pages, listing the members, adding a member | | `system.settings` | Creating, renaming and deleting roles, granting and revoking permissions | | Administrator role | Deleting team members, creating and deleting permissions, opening the administrator role | A user with `system.users` can give a new member any role except administrator, whatever permissions that role holds. The [Permissions](/3.x/acl#team-management-safeguards) page explains this rule. ## Customizing the Team Screen [#customizing-the-team-screen] The Team screen, the members table and the slide-over are Livewire components of the `setting` group. The [Components](/3.x/acl#components) section of the Permissions page lists their keys and explains how a replacement keeps the safeguards. ## Events [#events] Shopper dispatches no event of its own when a team member is added or deleted. The `User` model fires Eloquent's `created` and `deleted` events, but `created` runs before the slide-over assigns the roles, so a listener on it cannot tell a team member from a customer. The [Events](/3.x/events) page lists the events Shopper dispatches. ## In the Admin [#in-the-admin] Merchants open the Team screen from Settings, Staff & permissions. It lists the roles and the team members, adds a member through the Add administrator slide-over, opens each role to edit its permissions, and deletes members. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API does not expose team members: no endpoint lists, creates or deletes them. Its registration endpoint, `/store/auth/register`, gives every new account the customer role. The Store API [Authentication](/3.x/store-api/authentication#registering-a-customer) guide covers registration. # Themes (/3.x/themes) The admin panel ships with three color themes: Default (zinc grays and a blue accent), Midnight (a navy top bar, slate grays and a sky blue accent) and Evergreen (stone grays and a sage green accent). A theme changes the colors of the admin panel: the layout and the components stay the same. A merchant picks one on the **Appearance** page of the settings, and it applies to every user of the admin panel. Dark mode is separate from the theme. Each user switches between light, dark and system in the account menu, and the choice is kept in their browser. Each built-in theme has a dark variant. Themes only cover the admin panel. Your storefront has its own design, built by your application. ## Configuration [#configuration] `config/shopper/themes.php` registers the themes the Appearance page offers and names the default one: ```php title="config/shopper/themes.php" return [ 'default' => 'default', 'registered' => [ 'default' => [ 'name' => 'Default', 'author' => 'Shopper', 'has_dark' => true, ], 'midnight' => [ 'name' => 'Midnight', 'author' => 'Shopper', 'has_dark' => true, ], 'evergreen' => [ 'name' => 'Evergreen', 'author' => 'Shopper', 'has_dark' => true, ], ], ]; ``` `default` is the theme the admin panel uses until a merchant saves one on the Appearance page. When it names a theme that is not registered, the first registered theme is used. Each key of `registered` is the theme ID, and its array accepts these keys: | Key | Type | Default | Description | |-----|------|---------|-------------| | `name` | string | The ID in headline case | Name shown on the Appearance page | | `author` | string | `Shopper` | Shown after the name, as in "Default by Shopper" | | `has_dark` | bool | `true` | Whether the theme defines dark mode colors. The admin panel shows and applies the theme the same way either way | | `css` | string | `null` | URL of a stylesheet the admin panel loads while the theme is active, see [Creating a Theme](#creating-a-theme) | ## The Active Theme [#the-active-theme] The Appearance page saves the ID of the chosen theme in the `admin_theme` setting, described on the [Settings](/3.x/settings#setting-keys) page. Users who hold the `system.settings` permission can open it, as listed in [System Permissions](/3.x/acl#system-permissions). Clicking a theme previews it at once, and the Save button applies it. `Shopper\Theme\ThemeManager` holds the registered themes. Shopper binds it as a singleton and fills it from `config('shopper.themes.registered')`. Resolve it to read the active theme: ```php use Shopper\Theme\ThemeManager; $theme = resolve(ThemeManager::class)->active(); ``` `active()` returns the theme saved in `admin_theme`, or the default theme when the setting is empty or names a theme that is no longer registered. Removing a theme from the configuration therefore never leaves the admin panel without one. | Method | Returns | |--------|---------| | `active()` | The theme in use | | `default()` | The theme named in `config('shopper.themes.default')` | | `all()` | A collection of every registered theme | | `find(string $id)` | The theme with this ID, or `null` | | `has(string $id)` | Whether a theme with this ID is registered | | `register(Theme $theme)` | Adds a theme, or replaces the one with the same ID | | `registerMany(array $themes)` | Adds themes from an array shaped like `registered` | Each theme is a `Shopper\Theme\Theme` object with the `id`, `name`, `author`, `hasDark` and `css` properties. ## How a Theme Works [#how-a-theme-works] The admin layout writes the ID of the active theme on the `` element, as in ``. A theme is a block of CSS custom properties scoped to `[data-theme='midnight']`, and every color of the admin panel reads one of these properties. The default theme declares its values on `:root` too, so a property that another theme leaves out keeps its default value. | Properties | Colors | |------------|--------| | `--theme-sh-header`, `--theme-sh-header-border`, `--theme-sh-header-fg`, `--theme-sh-header-fg-muted`, `--theme-sh-header-hover` | Top bar: background, bottom border, text, secondary text, hovered items | | `--theme-sh-body` | Page background | | `--theme-sh-sidebar`, `--theme-sh-sidebar-hover`, `--theme-sh-sidebar-active`, `--theme-sh-settings-sidebar-hover` | Sidebar background, hovered and active items, hovered items of the settings menu. The last two fall back to `--theme-sh-sidebar-hover` | | `--theme-sh-surface`, `--theme-sh-card`, `--theme-sh-table-header` | Panels, cards and table headers | | `--theme-sh-muted`, `--theme-sh-muted-strong`, `--theme-sh-skeleton` | Light fills, stronger fills, loading placeholders | | `--theme-sh-border` | Borders | | `--theme-sh-fg`, `--theme-sh-fg-secondary`, `--theme-sh-fg-muted` | Text, secondary text, muted text | | `--theme-sh-accent`, `--theme-sh-accent-fg` | Accent color and the text on it. The default theme sets them to the primary color | | `--primary-50` to `--primary-950`, `--color-primary-50` to `--color-primary-950` | Primary color of buttons, links and focus rings. The built-in themes set both ramps to the same values | | `--gray-50` to `--gray-950` | Grays of the Filament components: form fields, tables, modals | Dark mode adds the `dark` class to ``. The dark colors of a theme go in a `.dark[data-theme='id']` block. A theme that changes the page, sidebar or card colors must also set them in that block: otherwise its light values stay in place in dark mode, because the theme block takes precedence over the dark colors of the default theme. ## Creating a Theme [#creating-a-theme] A theme of your own is a stylesheet that sets these properties, registered with its `css` key. The admin panel adds the stylesheet after its own, on the pages where the theme is active. Its stylesheet is compiled with Tailwind CSS and only holds the color variables it uses, so write your colors as literal values rather than `var(--color-orange-500)`. This Sunset theme gives the top bar a dark brown, the primary color an orange, and the grays a warm stone tint: ```css title="public/css/admin-themes/sunset.css" [data-theme='sunset'] { --primary-50: #fff7ed; --primary-100: #ffedd5; --primary-200: #fed7aa; --primary-300: #fdba74; --primary-400: #fb923c; --primary-500: #f97316; --primary-600: #ea580c; --primary-700: #c2410c; --primary-800: #9a3412; --primary-900: #7c2d12; --primary-950: #431407; --color-primary-50: #fff7ed; --color-primary-100: #ffedd5; --color-primary-200: #fed7aa; --color-primary-300: #fdba74; --color-primary-400: #fb923c; --color-primary-500: #f97316; --color-primary-600: #ea580c; --color-primary-700: #c2410c; --color-primary-800: #9a3412; --color-primary-900: #7c2d12; --color-primary-950: #431407; --theme-sh-header: #431407; --theme-sh-header-fg: #fafaf9; --theme-sh-header-fg-muted: #fdba74; --theme-sh-header-hover: #7c2d12; --theme-sh-body: #fafaf9; --theme-sh-sidebar: #f5f5f4; --theme-sh-sidebar-hover: #e7e5e4; --theme-sh-border: #e7e5e4; --theme-sh-card: #f5f5f4; --theme-sh-table-header: #f5f5f4; --gray-50: #fafaf9; --gray-100: #f5f5f4; --gray-200: #e7e5e4; --gray-300: #d6d3d1; --gray-400: #a8a29e; --gray-500: #78716c; --gray-600: #57534e; --gray-700: #44403c; --gray-800: #292524; --gray-900: #1c1917; --gray-950: #0c0a09; } .dark[data-theme='sunset'] { --theme-sh-body: #0c0a09; --theme-sh-sidebar: #0c0a09; --theme-sh-sidebar-hover: #1c1917; --theme-sh-border: #292524; --theme-sh-card: #0c0a09; --theme-sh-table-header: #0c0a09; } ``` The theme leaves out the text, surface and muted colors, so it keeps those of the default theme, in light and dark mode. The accent follows the new primary color. Register the theme with the path of the stylesheet, as a new entry of the `registered` array after the built-in themes: ```php title="config/shopper/themes.php" 'sunset' => [ 'name' => 'Sunset', 'author' => 'Northwind Apparel', 'has_dark' => true, 'css' => '/css/admin-themes/sunset.css', ], ``` Sunset now shows on the Appearance page. Because its stylesheet is only loaded while it is the active theme, its card and its preview on that page do not show its colors until you save it and reload the page. Set `'default' => 'sunset'` to use it before anyone picks a theme. ## Registering a Theme from a Package [#registering-a-theme-from-a-package] A package registers its themes at runtime, in the `boot` method of its service provider, with an absolute URL or the public path of its published stylesheet: ```php title="src/ThemesServiceProvider.php" namespace Northwind\AdminThemes; use Illuminate\Support\ServiceProvider; use Shopper\Theme\Theme; use Shopper\Theme\ThemeManager; class ThemesServiceProvider extends ServiceProvider { public function boot(): void { $this->publishes([ __DIR__ . '/../resources/css' => public_path('vendor/northwind-themes'), ], 'northwind-themes'); resolve(ThemeManager::class)->register(new Theme( id: 'sunset', name: 'Sunset', author: 'Northwind', css: '/vendor/northwind-themes/sunset.css', )); } } ``` `register()` replaces a theme with the same ID, so a package can also restyle `midnight` or `evergreen` this way. ## In the Admin [#in-the-admin] Merchants choose the theme under Settings, Appearance: a card per registered theme, with a preview of the top bar, the sidebar and the page in the theme colors, its name and its author. The [User Guide](/3.x/user-guide) walks through the settings screens. ## From a Storefront [#from-a-storefront] Admin themes have no effect on a storefront, and the Store API does not expose the `admin_theme` setting. The Store API [Store and Regions](/3.x/store-api/store#reading-the-store-settings) guide lists the settings it returns. # Two-Factor Authentication (/3.x/two-factor) Shopper offers two optional ways to protect the admin panel sign-in. Two-factor authentication asks for a one-time code from an authenticator app after the password. Passkeys replace the password with Face ID, Touch ID, Windows Hello or a hardware security key. Both are off on a fresh install. Once a method is enabled in the configuration, each team member turns it on for their own account from their profile page. An administrator cannot turn it on or off for another team member from the admin panel. Both methods protect the sign-in of the admin panel. The Store API signs customers in with its own endpoints, described in [From a Storefront](#from-a-storefront). ## Configuration [#configuration] Two keys of `config/shopper/auth.php` make each method available, and both read an environment variable: ```php title="config/shopper/auth.php" return [ '2fa_enabled' => env('SHOPPER_ENABLED_TWO_FACTOR', false), 'passkeys_enabled' => env('SHOPPER_ENABLED_PASSKEYS', false), ]; ``` Set the variables in your `.env` file: ```bash title=".env" SHOPPER_ENABLED_TWO_FACTOR=true SHOPPER_ENABLED_PASSKEYS=true ``` When `2fa_enabled` is `false`, the profile page hides the Two Factor Authentication section and the sign-in asks for no code, even from users who turned it on before. Their secrets stay in the database, so setting the key back to `true` brings the code prompt back for them. The [Configuration](/3.x/configuration#authentication) page lists the other keys of this file. ## Preparing the User Model [#preparing-the-user-model] The profile page shows the Two Factor Authentication section only when your `User` model implements `HasStoreAuthentication`, and the Passkeys section only when it implements `PasskeyUser` from `laravel/passkeys`. Shopper provides a trait for each contract: ```php title="app/Models/User.php" use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passkeys\Contracts\PasskeyUser; use Laravel\Passkeys\PasskeyAuthenticatable; use Shopper\Contracts\HasStoreAuthentication; use Shopper\Contracts\HasStoreAuthenticationRecovery; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; use Shopper\Traits\InteractsWithStoreAuthentication; use Shopper\Traits\InteractsWithStoreAuthenticationRecovery; #[Hidden([ 'password', 'remember_token', 'store_two_factor_secret', 'store_two_factor_recovery_codes', ])] class User extends Authenticatable implements HasStoreAuthentication, HasStoreAuthenticationRecovery, PasskeyUser, ShopperUser { use InteractsWithShopper; use InteractsWithStoreAuthentication; use InteractsWithStoreAuthenticationRecovery; use PasskeyAuthenticatable; } ``` Implement both two-factor contracts together: the profile page shows the recovery codes of every user who turns two-factor authentication on. Leave out `PasskeyUser` and `PasskeyAuthenticatable` while passkeys stay off. The `ShopperUser` contract and the hidden attributes come from [Prepare Your User Model](/3.x/installation#prepare-your-user-model). ### Database Columns [#database-columns] The `shopper/core` migrations add two nullable `text` columns to the `users` table. The traits encrypt both values with Laravel's encrypter before saving them: | Column | Content | |--------|---------| | `store_two_factor_secret` | The secret shared with the authenticator app, encrypted | | `store_two_factor_recovery_codes` | The recovery codes, as an encrypted JSON array | Shopper 2.x named these columns `two_factor_secret` and `two_factor_recovery_codes`. A 3.x migration renames them, so they no longer collide with the columns of Laravel Fortify, and skips the rename when the old columns are missing. The `shopper-upgrade-two-factor-auth` skill, listed in [Upgrade Skills](/3.x/ai-tools#upgrade-skills), updates a 2.x `User` model to the contracts above. ## Enabling Two-Factor Authentication [#enabling-two-factor-authentication] A team member turns two-factor authentication on from the My profile page, at `/cpanel/profile` with the default prefix: In the Two Factor Authentication section, click **Enable Two Factor** and confirm the account password. Scan the QR code with an authenticator app that supports time-based one-time passwords (TOTP), such as Google Authenticator, Microsoft Authenticator or 1Password. Copy the recovery codes shown below the QR code to a password manager. Two-factor authentication is active as soon as the QR code appears: the next sign-in asks for a code. Scan the code and store the recovery codes before leaving the page. The app lists the account under the value of `config('app.name')` and the user's email address, so set `APP_NAME` to the name of the store. Each action of the section asks for the password once: after a confirmation, the next actions skip the prompt for the number of seconds set in `config('auth.password_timeout')`, 10800 in Laravel's default configuration. ## Recovery Codes [#recovery-codes] Recovery codes let a team member sign in without the authenticator app, for example after losing their phone. Shopper generates eight codes, each made of two random strings of 10 characters joined by a hyphen. Each code works once. Signing in with a recovery code replaces that code with a new one, so the list always holds eight codes. From the profile page, **Show Recovery Codes** displays the current list, and **Regenerate Recovery Codes** replaces all eight: the previous codes stop working at once. Both buttons ask for the password. ## Logging In with Two-Factor Authentication [#logging-in-with-two-factor-authentication] When a user with two-factor authentication enters a correct email and password, the login page shows an Authenticate Your Account screen instead of signing them in. They type the 6-digit code from their app, or click **Use a recovery code** to type one of their recovery codes. **Back to login** returns to the email and password form. The password is checked again with the code, and the form allows five attempts per minute across both steps. After a password reset, a user with two-factor authentication goes back to the login page and signs in with a code, instead of being signed in by the reset. ## Disabling Two-Factor Authentication [#disabling-two-factor-authentication] The **Disable** button of the Two Factor Authentication section asks for the password, then deletes the secret and the recovery codes. The next sign-in asks for the password only. Turning two-factor authentication on again creates a new secret, so the user scans a new QR code. A team member who lost both their device and their recovery codes cannot sign in. Turn two-factor authentication off for them from `php artisan tinker`, with the action the profile page uses: ```php use App\Models\User; use Shopper\Actions\Auth\DisableTwoFactorAuthentication; $user = User::query()->where('email', 'jane@example.com')->firstOrFail(); app(DisableTwoFactorAuthentication::class)($user); ``` ## Passkeys [#passkeys] A passkey is a credential stored on the user's device or in their password manager. Signing in with it takes a fingerprint, a face scan or the device PIN, and no password. Shopper uses [laravel/passkeys](https://github.com/laravel/passkeys) for the WebAuthn exchange. A passkey sign-in replaces both the password and the code: a user who also has two-factor authentication is not asked for a code after a passkey, because the passkey already proves both the device and the person. ### Setting Up Passkeys [#setting-up-passkeys] Passkeys need a database table, the model contract and a relying party that matches the admin panel URL: Set `SHOPPER_ENABLED_PASSKEYS=true` in your `.env` file. Add the `PasskeyUser` contract and the `PasskeyAuthenticatable` trait to your `User` model, as shown in [Preparing the User Model](#preparing-the-user-model). The installer does not publish this migration. Publish it from `laravel/passkeys`, then run it: ```bash php artisan vendor:publish --tag=passkeys-migrations php artisan migrate ``` Browsers bind a passkey to a domain. `laravel/passkeys` reads it from the host of `config('app.url')`, so `APP_URL` must match the domain of the admin panel. When the admin panel runs on another domain, publish the configuration with `php artisan vendor:publish --tag=passkeys-config` and set `relying_party_id` and `allowed_origins` in `config/passkeys.php`. Browsers offer passkeys only on HTTPS pages and on `localhost`. ### Registering a Passkey [#registering-a-passkey] The Passkeys section of the profile page lists the user's passkeys, newest first, with the name, the date it was added and the date it was last used. **Add passkey** asks for a name, such as "MacBook Pro", and the account password, then hands over to the browser, which creates the passkey. The button is disabled in a browser without passkey support. Each passkey has a **Delete** action, which asks for the password. A deleted passkey can no longer sign in. ### Signing In with a Passkey [#signing-in-with-a-passkey] The login page shows a **Sign in with a passkey** button below the form, and the email field offers the saved passkeys through the browser's autofill. A successful passkey sign-in regenerates the session and redirects like a password sign-in. Shopper registers its own routes under the admin panel prefix: | Method | URI | Name | Access | |--------|-----|------|--------| | `GET` | `/cpanel/passkeys/login/options` | `shopper.passkeys.login-options` | Guests, 6 requests per minute | | `POST` | `/cpanel/passkeys/login` | `shopper.passkeys.login` | Guests, 6 requests per minute | | `GET` | `/cpanel/passkeys/options` | `shopper.passkeys.registration-options` | Signed-in users who confirmed their password | | `POST` | `/cpanel/passkeys` | `shopper.passkeys.store` | Signed-in users who confirmed their password | While `passkeys_enabled` is `true`, Shopper calls `Passkeys::ignoreRoutes()`, so the routes of `laravel/passkeys` are not registered. A storefront that offers passkeys to customers with the same package defines its own routes. ## Developer Integration [#developer-integration] The traits cover the usual setup. To store the secret elsewhere or verify codes another way, implement the contracts yourself or replace the code provider. ### Contracts and Traits [#contracts-and-traits] `Shopper\Contracts\HasStoreAuthentication` is implemented by `Shopper\Traits\InteractsWithStoreAuthentication`: | Method | Returns | |--------|---------| | `getStoreAuthenticationSecret()` | The secret as stored, encrypted, or `null` when two-factor authentication is off | | `saveStoreAuthenticationSecret(?string $secret)` | Saves the secret encrypted, or clears it with `null` | | `getStoreAuthenticationHolderName()` | The account name shown in the authenticator app, the email address by default | | `getStoreAuthenticationQrCodeSvg()` | The QR code as a 192 pixel SVG | | `getStoreAuthenticationQrCodeUrl()` | The `otpauth://` URL the QR code encodes | `Shopper\Contracts\HasStoreAuthenticationRecovery` is implemented by `Shopper\Traits\InteractsWithStoreAuthenticationRecovery`: | Method | Returns | |--------|---------| | `getStoreAuthenticationRecoveryCodes()` | The decrypted list of codes, or `null` | | `saveStoreAuthenticationRecoveryCodes(?array $codes)` | Saves the codes encrypted, or clears them with `null` | | `replaceStoreAuthenticationRecoveryCode(string $code)` | Swaps a used code for a new one | The login page reads the encrypted secret from the `store_two_factor_secret` attribute when it checks a code. A custom implementation of `HasStoreAuthentication` keeps the secret in that attribute, encrypted with Laravel's encrypter. ### Code Provider [#code-provider] `Shopper\Contracts\TwoFactorAuthenticationProvider` generates the secrets, builds the QR code URL and verifies the codes. The default implementation wraps [pragmarx/google2fa](https://github.com/antonioribeiro/google2fa): | Method | Purpose | |--------|---------| | `generateSecretKey(): string` | Creates a new secret when a user turns two-factor authentication on | | `qrCodeUrl(string $companyName, string $companyEmail, string $secret): string` | Builds the `otpauth://` URL | | `verify(string $secret, string $code): bool\|int` | Checks a code typed on the login page | Bind your own implementation in a service provider to replace it everywhere Shopper uses it: ```php title="app/Providers/AppServiceProvider.php" use App\Auth\TimeBasedCodeProvider; use Shopper\Contracts\TwoFactorAuthenticationProvider; public function register(): void { $this->app->singleton(TwoFactorAuthenticationProvider::class, TimeBasedCodeProvider::class); } ``` ## Events [#events] Shopper dispatches `Shopper\Events\TwoFactor\TwoFactorAuthenticationEnabled` when a user turns two-factor authentication on from their profile page. The event carries the user in `$event->user`. A store that keeps a security log records it with a listener: ```php title="app/Listeners/RecordTwoFactorActivation.php" namespace App\Listeners; use Illuminate\Support\Facades\Log; use Shopper\Events\TwoFactor\TwoFactorAuthenticationEnabled; class RecordTwoFactorActivation { public function handle(TwoFactorAuthenticationEnabled $event): void { Log::info('Two-factor authentication enabled', [ 'user_id' => $event->user->getKey(), ]); } } ``` `Shopper\Events\TwoFactor\TwoFactorAuthenticationDisabled` also exists, but Shopper does not dispatch it when a user turns two-factor authentication off, so a listener on it never runs. Passkeys dispatch the events of `laravel/passkeys`: `Laravel\Passkeys\Events\PasskeyRegistered` and `PasskeyDeleted` carry the user and the passkey, and `PasskeyVerified` fires on each passkey sign-in. The [Events](/3.x/events#admin-panel-events) page lists the other events of the admin panel. ## In the Admin [#in-the-admin] Each team member manages both methods from the My profile page, opened from the account menu of the top bar: the Two Factor Authentication section with its QR code and recovery codes, and the Passkeys section with the list of passkeys. On a customer's page, a badge shows whether two-factor authentication is enabled or disabled for that account. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API does not expose two-factor authentication or passkeys: no endpoint enables them, lists recovery codes or registers a passkey. A storefront that wants a second factor for customers builds it in the application, for example with Laravel Fortify, whose columns no longer collide with Shopper's. The Store API [Authentication](/3.x/store-api/authentication#logging-in) guide covers the login. # Upgrade Guide (/3.x/upgrade) **Estimated Upgrade Time:** 1 to 3 hours for a store with few customizations. Custom admin components, payment or shipping drivers and published config files add to it. Shopper 3.0 moves to Filament 5 and Livewire 4, renames the admin permissions, ships each carrier as its own package and changes several contracts and config files. The `shopper/upgrade` package applies most of these changes with one command. This guide covers the command and the production deploy, then lists every change by impact, with the code before and after. ## Before You Start [#before-you-start] Upgrade the store to Shopper 2.12 first. From 2.10, `composer update` is enough; from an older release, see [Coming From a Release Before 2.7](#coming-from-a-release-before-27) and the [2.x upgrade guides](/2.x/upgrade). Shopper 2.12 already runs on the versions 3.0 requires for Laravel and Spatie Permission, so move the application to them while it is still on 2.12, one change at a time: - Laravel 12.68 or 13.27. Laravel 11 is no longer supported. See the [Laravel upgrade guide](https://laravel.com/docs/12.x/upgrade). - Spatie Permission 7. See the [Spatie Permission upgrade guide](https://spatie.be/docs/laravel-permission/v7/upgrading). Filament 5 and Livewire 4 come with Shopper 3.0. If your application uses them outside Shopper, read the [Filament 5](https://filamentphp.com/docs/5.x/upgrade-guide) and [Livewire 4](https://livewire.laravel.com/docs/4.x/upgrading) upgrade guides as well. PHP 8.3 stays the minimum. The full list is on the [Requirements](/3.x/requirements) page. Then prepare the upgrade itself: - Back up the database and the storage disks. The upgrade rewrites permission names, can change amounts and moves the files of virtual products. - Commit your work. The command rewrites your code with Rector and asks for confirmation when the Git tree has uncommitted changes. - Run the upgrade on a local copy or a staging environment first, with a recent copy of the production database. ## Updating Dependencies [#updating-dependencies] Update the Shopper packages in your `composer.json`: ```json title="composer.json" "shopper/framework": "^2.12", // [!code --] "shopper/framework": "^3.0", // [!code ++] ``` If you installed `shopper/stripe`, change it to `^3.0` as well. Then install the upgrade package as a development dependency and update: ```bash composer require shopper/upgrade:^3.0 --dev composer update ``` While 3.0 is in release candidates, Composer installs it only with `"minimum-stability": "rc"` and `"prefer-stable": true` in your `composer.json`. Shopper's own packages depend on each other at the release candidate version, so requiring `shopper/framework:^3.0@rc` alone is not enough. Shopper no longer installs `gehrisandro/tailwind-merge-laravel`. It registers the `$attributes->twMerge()` macro itself, so Blade components that call it keep working. An application that uses `twMergeFor()`, `withoutTwMergeClasses()`, the `@twMerge` directive or a `config/tailwind-merge.php` file requires the package in its own `composer.json`. The `ivanmitrikeski/laravel-shipping` package is no longer installed. Shopper now installs Laravel Scout, Laravel Sanctum, Laravel Passkeys, `league/csv`, `spatie/laravel-query-builder` and `giggsey/libphonenumber-for-php`. ## Running the Upgrade [#running-the-upgrade] Run the command on your local copy: ```bash php artisan shopper:upgrade ``` The command asks for confirmation, then runs seven steps in order: | Step | Command | What it does | |------|---------|--------------| | 1 | `migrate --force` | Runs the 3.0 migrations. | | 2 | `shopper:upgrade:rector` | Renames the moved classes and namespaces in your code. | | 3 | `shopper:upgrade:permissions --force` | Renames the admin permissions to dot notation. See [Permissions](#permissions-use-dot-notation). | | 4 | `shopper:upgrade:fix-zero-decimal-currencies --force` | Divides by 100 the amounts in zero-decimal currencies. See [Zero-Decimal Amounts](#zero-decimal-amounts). | | 5 | `shopper:stock:reconcile --fix` | Rewrites the stock snapshot from the inventory ledger. See [Reconciling Stock Levels](/3.x/locations#reconciling-stock-levels). | | 6 | `shopper:link --force` | Recreates the storage link and links the panel assets at `public/vendor/shopper`. | | 7 | `shopper:files:secure` | Moves the files of virtual products to the private disk. See [Downloadable Files](/3.x/products#downloadable-files). | When it finishes, the command lists the carrier packages your 2.x config or `.env` enabled and that are not installed yet, with the `composer require` line to run. Rector scans `app` by default. If your code lives in other directories as well, list them, separated by commas: ```bash php artisan shopper:upgrade --path=app,src ``` In a CI job or any run without a terminal, the confirmation answers no and the command stops. Pass `--force` to run every step without asking. Run the command once. Step 4 passes `--force`, which skips the check that the zero-decimal fix already ran: on a store that sells in a zero-decimal currency, a second run divides those amounts by 100 again, then stops with an error before steps 5 to 7. If a run stops partway, run the remaining steps one by one with their own commands from the table. The zero-decimal step expects the amounts Shopper wrote before 2.7, multiplied by 100. A store that already ran `shopper:fix-zero-decimal-currencies` under 2.x, or that started on 2.7 or later, holds whole units: on such a store, do not run `shopper:upgrade`. Run the other steps one by one, as in [Upgrading Production](#upgrading-production), and leave out the zero-decimal step. Review the Rector changes with `git diff`, then work through the [High Impact Changes](#high-impact-changes) the command does not apply: published config files, permission checks in your code and the scheduler. Let Boost add the [upgrade skills](/3.x/ai-tools#upgrade-skills) if a coding agent works on the upgrade with you, and run your test suite. ## Upgrading Production [#upgrading-production] The Rector step changed your code, and you commit that code. The other steps change the database and the files, and they run again on production when you deploy 3.0. Put the store in maintenance mode, deploy, then run the steps one by one: ```bash php artisan down php artisan migrate --force php artisan shopper:upgrade:permissions --force php artisan permission:cache-reset php artisan shopper:stock:reconcile --fix php artisan shopper:link --force php artisan shopper:files:secure php artisan up ``` Add `php artisan shopper:upgrade:fix-zero-decimal-currencies --force` after the permissions only when the production store still holds amounts multiplied by 100, as explained in [Zero-Decimal Amounts](#zero-decimal-amounts). The `shopper:upgrade:permissions` and `shopper:upgrade:fix-zero-decimal-currencies` commands come from `shopper/upgrade`. A deploy that runs `composer install --no-dev` does not install it, so for the release that ships 3.0, move the package from `require-dev` to `require`: ```bash composer require shopper/upgrade:^3.0 ``` Some 3.0 migrations rewrite whole tables: the `public_id` columns get a ULID on every row, and the stock levels are built from the inventory history. On a large catalog or order history, they take minutes rather than seconds, so plan the maintenance window from the time they took on your staging copy. Once production runs 3.0, remove the package: ```bash composer remove shopper/upgrade ``` ## High Impact Changes [#high-impact-changes] ### Permissions Use Dot Notation [#permissions-use-dot-notation] **Likelihood of Impact: High** *Affects every application that checks a Shopper permission in its own code, policies, Blade views or seeders.* Shopper 3.0 names permissions `resource.action` instead of `action_resource`, and the `add` action becomes `create`. The upgrade command renames the permissions in the database and the roles keep them. Rename the checks in your own code: ```php $user->can('browse_orders'); // [!code --] $user->can('orders.browse'); // [!code ++] $user->can('add_products'); // [!code --] $user->can('products.create'); // [!code ++] ``` In Blade, the `@can` directives change the same way: ```blade @can('edit_products') @can('products.edit') ``` The resources keep their names, except `product_variants`, which becomes `products.variants`. Three permissions have a fixed name: | 2.x | 3.0 | |-----|-----| | `access_dashboard` | `system.dashboard` | | `access_setting` | `system.settings` | | `view_users` | `system.users` | The order detail page and the shipment slide-overs check `orders.read`, renamed from `read_orders`. Spatie keeps the 2.x names in its cache: clear it after the rename with `php artisan permission:cache-reset`. The `campaigns` resource is new and the rename does not create its permissions. Generate them and give them to the administrator role, as shown in [Generating Permissions](/3.x/acl#generating-permissions). The [ACL page](/3.x/acl#upgrading-from-2x) details the rename. ### Published Config Files [#published-config-files] **Likelihood of Impact: High** *Affects applications with config files published under `config/shopper/` in 2.x.* A published config file is loaded over the package defaults. Shopper fills in a missing key from its own default, but a list such as the cart pipelines or the settings items is replaced as a whole, and an old class name stops the boot. Compare each published file with the 3.0 version and update these ones: **`settings.php`**: the settings items moved to a new namespace, and the old import fails on boot. The list also gains three pages, which stay hidden until you add them: ```php title="config/shopper/settings.php" use Shopper\Settings\Items; // [!code --] use Shopper\Navigation\Setting\Items; // [!code ++] 'items' => [ Items\GeneralSetting::class => true, Items\AppearanceSetting::class => true, // [!code ++] Items\StaffSetting::class => true, Items\LocationSetting::class => true, Items\ChannelSetting::class => true, // [!code ++] Items\PaymentSetting::class => true, Items\CarrierSetting::class => true, Items\LegalSetting::class => true, Items\ZoneSetting::class => true, Items\TaxSetting::class => true, Items\CurrencySetting::class => true, Items\WebhookSetting::class => true, // [!code ++] ], ``` **`cart.php`**: without the new pipeline stage, [automatic discounts](/3.x/discounts#automatic-discounts) never apply to a cart. Add it before `ApplyDiscounts`, with the two new keys: ```php title="config/shopper/cart.php" 'pipelines' => [ 'cart' => [ Pipelines\CalculateLines::class, Pipelines\ApplyAutomaticPromotions::class, // [!code ++] Pipelines\ApplyDiscounts::class, Pipelines\CalculateTax::class, Pipelines\Calculate::class, ], ], 'max_promotions' => 5, // [!code ++] 'totals_ttl_minutes' => 15, // [!code ++] ``` **`orders.php`**: 3.0 builds the order number from the order's own id, where 2.x added the start value to the id of the previous order. Keep `start_sequence_from` at `1` and every new number is one higher than 2.x would have given it. Set it to `0` to continue the 2.x numbering: ```php title="config/shopper/orders.php" 'generator' => [ 'start_sequence_from' => 1, // [!code --] 'start_sequence_from' => 0, // [!code ++] ], ``` See [Order Number Generation](/3.x/orders#order-number-generation). The same file gains `reclaim_pending_after_hours`, covered in [Pending Orders Are Reclaimed](#pending-orders-are-reclaimed). **`payment.php`** and **`shipping.php`**: delete the `drivers` block of each file. Stripe reads `config/shopper/stripe.php` and each carrier reads its own file, see [Carriers Are Separate Packages](#carriers-are-separate-packages). `shipping.php` gains a rates cache: ```php title="config/shopper/shipping.php" 'rates_cache_ttl' => env('SHIPPING_RATES_CACHE_TTL', 600), ``` **`admin.php`** and **`features.php`** gain optional keys: a `notifications.database` block for the admin bell, and the `campaign` feature. Their defaults apply when the keys are missing. `themes.php` is a new file: `php artisan shopper:publish` adds it and keeps your existing files. **`components/*.php`**: the component keys changed in `product.php`, `setting.php`, `discount.php`, `dashboard.php` and `account.php`. Publish each file you had published again, then apply your overrides to it: ```bash php artisan shopper:component:publish discount --force ``` In `discount.php`, for example, `slide-overs.discount-form` is gone, replaced by `slide-overs.add-promotion`, `slide-overs.products-picker`, `slide-overs.customers-picker`, `discounts.stats-panel` and the `discount-edit` page. See [Configuration](/3.x/configuration#components). The `shopper-upgrade-config` and `shopper-upgrade-settings-namespace` [upgrade skills](/3.x/ai-tools#upgrade-skills) guide a coding agent through these files. ### Scheduler and Queue Worker [#scheduler-and-queue-worker] **Likelihood of Impact: High** *Affects every store.* Shopper 2.x scheduled no command. Shopper 3.0 schedules several: reclaiming unpaid pending orders, sending webhook deliveries again, reconciling payments, syncing shipment tracking, pruning abandoned carts and pruning old records. Its event listeners also run on the queue. Without the scheduler and a queue worker, these tasks never run. See [Run the Scheduler and a Queue Worker](/3.x/installation#run-the-scheduler-and-a-queue-worker). ### Carriers Are Separate Packages [#carriers-are-separate-packages] **Likelihood of Impact: High** *Affects stores that use UPS, FedEx or USPS.* Each carrier is now its own package with its own config file, like Stripe. Without the package, the carrier disappears from the shipping settings and `Shipping::driver('ups')` throws an exception. Install the carriers you use: ```bash composer require shopper/ups shopper/fedex shopper/usps php artisan vendor:publish --tag=shopper-ups-config ``` The environment variables keep their names. A value you wrote directly in the `drivers` block of `shipping.php` moves to the carrier's file, where the keys are flat: ```php // config/shopper/shipping.php in 2.x 'drivers' => ['ups' => ['enabled' => true, 'credentials' => ['client_id' => 'abc']]], // config/shopper/ups.php in 3.0 'enabled' => true, 'client_id' => 'abc', ``` Rector renames the driver classes, from `Shopper\Shipping\Drivers\UpsDriver` to `Shopper\Ups\UpsDriver`, and the same for FedEx and USPS. See [UPS](/3.x/carriers/ups), [FedEx](/3.x/carriers/fedex) and [USPS](/3.x/carriers/usps). ### Zero-Decimal Amounts [#zero-decimal-amounts] **Likelihood of Impact: High** *Affects stores that sell in a zero-decimal currency, such as XAF or JPY.* Before 2.7, Shopper multiplied every amount by 100, zero-decimal currencies included. Step 4 of the upgrade divides those amounts by 100. It is right only for a store that still holds them: one that started before 2.7 and never ran `shopper:fix-zero-decimal-currencies`. On any other store, leave the step out, as the [warning above](#running-the-upgrade) explains. Preview what the command would change: ```bash php artisan shopper:upgrade:fix-zero-decimal-currencies --dry-run ``` See [Data From Shopper 2.x](/3.x/money#data-from-shopper-2x) for the tables it changes. ### Zone Relations [#zone-relations] **Likelihood of Impact: High** *Affects every store with zones.* The `zone_has_relations` table links each zone to its countries, carriers and payment methods. 2.x stored the class name of each linked model in `zonable_type`, such as `Shopper\Core\Models\Country`. 3.0 adds `country`, `carrier` and `payment_method` to the morph map and looks for these names, and no 3.0 migration rewrites the existing rows. Until they are rewritten, `$zone->countries`, `$zone->carriers` and `$zone->paymentMethods` come back empty: every zone loses its countries, carriers and payment methods. Create a migration in your application, so production gets the same change when it runs `migrate --force`: ```bash php artisan make:migration rename_shopper_zone_relation_types ``` Rewrite the rows in its `up()` method: ```php use Illuminate\Support\Facades\DB; public function up(): void { $types = [ 'Shopper\Core\Models\Country' => 'country', 'Shopper\Core\Models\Carrier' => 'carrier', 'Shopper\Core\Models\PaymentMethod' => 'payment_method', ]; foreach ($types as $class => $alias) { DB::table(shopper_table('zone_has_relations')) ->where('zonable_type', $class) ->update(['zonable_type' => $alias]); } } ``` The collections linked to a zone keep working: 2.x already stored them as `collection`. ## Medium Impact Changes [#medium-impact-changes] ### Renamed Classes [#renamed-classes] **Likelihood of Impact: Medium** *Affects code that imports these classes. Rector renames them.* | 2.x | 3.0 | |-----|-----| | `Shopper\Settings\*` | `Shopper\Navigation\Setting\*` | | `Shopper\Core\Models\Contracts\ShopperUser` | `Shopper\Models\Contracts\ShopperUser` | | `Shopper\Core\Models\Contracts\Cart`, `CartLine` | `Shopper\Cart\Models\Contracts\Cart`, `CartLine` | | `Shopper\Livewire\Components\Products\Form\*` | `Shopper\Livewire\Pages\Product\*` (`Edit` becomes `Overview`, `RelatedProducts` becomes `Related`) | | `Shopper\Shipping\Drivers\UpsDriver`, `FedExDriver`, `UspsDriver` | `Shopper\Ups\UpsDriver`, `Shopper\FedEx\FedExDriver`, `Shopper\Usps\UspsDriver` | Rector does not replace the `Shopper\Core\Traits\ShopperUser` trait, which 3.0 removes. Use `Shopper\Traits\InteractsWithShopper` on your User model: ```php title="app/Models/User.php" use Shopper\Core\Traits\ShopperUser; // [!code --] use Shopper\Traits\InteractsWithShopper; // [!code ++] ``` A custom product edit screen moves from Livewire form components to pages registered in `config/shopper/components/product.php`. The `shopper-upgrade-product-edit` [upgrade skill](/3.x/ai-tools#upgrade-skills) covers it. ### Contracts [#contracts] **Likelihood of Impact: Medium** *Affects classes that implement these contracts themselves. A model that extends Shopper's model, or a driver that extends Shopper's base driver, already has the new methods.* | Contract | Added in 3.0 | |----------|--------------| | `Shopper\Core\Models\Contracts\Order` | `canTransitionTo(OrderStatus $status): bool`, `transitionTo(OrderStatus $status): void`, `canTransitionPaymentTo(PaymentStatus $status): bool`, `transitionPaymentTo(PaymentStatus $status): void`, `allowsDownloads(): bool`, `promotions(): HasMany` | | `Shopper\Core\Models\Contracts\Category` | `enabledSubtreeIds(): Illuminate\Support\Collection` | | `Shopper\Core\Contracts\Priceable` | `resolvePrice(?PricingContext $context = null): ?ResolvedPrice` | | `Shopper\Payment\Contracts\PaymentDriver` | `mode(): ?PaymentMode`, `supportsRetrieval(): bool` | | `Shopper\Shipping\Contracts\ShippingDriver` | `supportsWebhooks(): bool`, `handleWebhook(Request $request): ?TrackingInfo` | A payment driver that overrides `refundPayment()` takes the new `$context` argument, even when it extends `Shopper\Payment\Drivers\Driver`: ```php public function refundPayment(string $reference, int $amount, ?string $reason = null): PaymentResult // [!code --] public function refundPayment(string $reference, int $amount, ?string $reason = null, array $context = []): PaymentResult // [!code ++] ``` `WebhookResult::$action` is a `Shopper\Payment\Enum\WebhookAction` case, where 2.x took a string. A driver's `handleWebhook()` passes `WebhookAction::Captured` in place of `'captured'`, and the same for `authorized`, `failed`, `canceled`, `refunded` and `ignored`. The enum adds `RefundFailed`. ```php use Shopper\Payment\Enum\WebhookAction; return new WebhookResult(action: 'refunded', reference: $reference, amount: $amount); // [!code --] return new WebhookResult(action: WebhookAction::Refunded, reference: $reference, amount: $amount); // [!code ++] ``` In 2.x every successful refund result settled the refund at once. A 3.x result whose `isPending()` is true (status `pending` or `requires_action`) and whose reference is not the payment reference leaves the refund pending until a `Refunded` or `RefundFailed` webhook carries the same refund ID. A driver whose provider settles refunds later returns `PaymentResult::pendingRefund()` with the provider's refund ID, as described in [Pending Refunds](/3.x/payments#pending-refunds). `PaymentProcessingService::refund()` takes a fifth, optional `$idempotencyKey` argument. A call that repeats a key already used on the order returns that refund without calling the provider: generate the key once per refund and send it again on every retry. A successful result can now be pending, so check `$result->isPending()` before treating the money as returned. A custom settings page implements `SettingItem`, which now extends `NavigationItem` and requires `group(): ?string`. A custom sidebar item returns `?string` from `getActiveWhen()`, where 2.x returned `bool`. The `shopper-upgrade-contracts` [upgrade skill](/3.x/ai-tools#upgrade-skills) covers these changes. ### Product Channel Scope [#product-channel-scope] **Likelihood of Impact: Medium** *Affects storefront code that filters products by sales channel.* ```php Product::query()->forChannel($mobileApp->id)->get(); // [!code --] Product::query()->channel($mobileApp->id)->get(); // [!code ++] ``` See [Filter by Channel](/3.x/products#filter-by-channel). ### Cart Coupons [#cart-coupons] **Likelihood of Impact: Medium** *Affects storefront code that reads `coupon_code` on a cart.* A cart can now hold several promotion codes, so the `coupon_code` column of `carts` is dropped and its values are not copied. Read the codes from `$cart->promotions()`. `applyCoupon(Cart $cart, string $code)` keeps its signature, and `removeCoupon()` takes the code to remove, or removes every code without it: ```php Cart::removeCoupon($cart); // [!code --] Cart::removeCoupon($cart, 'SUMMER10'); // [!code ++] ``` ### Cart Exceptions [#cart-exceptions] **Likelihood of Impact: Medium** *Affects storefront code that adds products to a cart, completes a checkout or signs customers in.* `Cart::add()` throws `MissingPriceException` for a product without a price in the cart currency, where 2.x added the line at 0. Adding a product already in the cart with other metadata throws `CartLineMetadataConflictException`, and a quantity the [quantity rules](/3.x/pricing#quantity-rules) refuse throws `QuantityRuleViolationException`. Converting the cart to an order throws `PriceChangedException` when a unit price went up and `PromotionUnavailableException` when the terms of an applied promotion no longer hold. These exceptions extend `RuntimeException` and share no base class: catch each one where your storefront shows an error. See [Adding Items](/3.x/cart#adding-items) and [Order Conversion](/3.x/cart#order-conversion). When a customer signs in, `associate()` merges the guest cart into the customer's open cart, where 2.x gave the guest cart to the customer and left the other cart aside. See [Associating Cart on Login](/3.x/cart#associating-cart-on-login). ### Order Numbers [#order-numbers] **Likelihood of Impact: Medium** *Affects code that calls `generate_number()`.* The helper takes the sequence to format, which Shopper reads from the order's id once the order exists. A migration also renames duplicate order numbers by appending `-{id}`. ```php $number = generate_number(); // [!code --] $number = generate_number($order->id); // [!code ++] ``` See [Order Number Generation](/3.x/orders#order-number-generation), and the `start_sequence_from` change in [Published Config Files](#published-config-files). ### Pending Orders Are Reclaimed [#pending-orders-are-reclaimed] **Likelihood of Impact: Medium** *Affects stores with orders that stay pending for more than a day.* A pending order whose online payment never lands is cancelled after 24 hours and its stock is released. Offline payments are never reclaimed. Set `reclaim_pending_after_hours` in `config/shopper/orders.php` to change the delay, or to `null` to turn it off. See [Reclaiming Pending Orders](/3.x/orders#reclaiming-pending-orders). ### Capture and Refund Checks [#capture-and-refund-checks] **Likelihood of Impact: Medium** *Affects code that calls `PaymentProcessingService::capture()` or `refund()`.* 2.x passed every capture and refund to the provider. 3.0 checks the order first and throws a `Shopper\Payment\Exceptions\PaymentException`: - `capture()` throws on a cancelled or archived order. On an order already paid, it returns a successful result without calling the provider. - `refund()` throws when the payment status is neither Paid nor Partially refunded, and when the amount is larger than what remains refundable: the captured total minus the refunds made or pending. Catch the exception where your code captures or refunds a payment. ### Stripe Webhooks [#stripe-webhooks] **Likelihood of Impact: Medium** *Affects stores that take payments with Stripe.* In 2.x the application registered its own Stripe webhook route, `/webhooks/stripe` in the starter kits. The Store API now receives the webhooks at `https://example.com/store/webhooks/stripe`: point the endpoint in the Stripe Dashboard to this URL and remove your route and controller. A store without the Store API keeps a route of its own, as shown at the end of [The Event Journal](/3.x/payments#the-event-journal). The driver reads refunds from `refund.created`, `refund.updated` and `refund.failed`, where 2.x read `charge.refunded`. Add the three events to the endpoint, as listed in [Handled Events](/3.x/payments/stripe#handled-events). `STRIPE_WEBHOOK_SECRET` is now required: without it, the driver counts as not configured and carts stop offering the payment methods that use Stripe. Copy the endpoint's signing secret into it, as described in [Configuration](/3.x/payments/stripe#configuration). ### Custom Shipping Drivers [#custom-shipping-drivers] **Likelihood of Impact: Medium** *Affects shipping drivers written for 2.x that extend `Shopper\Shipping\Drivers\Driver`.* The base driver returns `false` from `supportsTracking()`, where 2.x returned `true`. A driver that implements `track()` says so, or the scheduled tracking sync skips its shipments: ```php public function supportsTracking(): bool { return true; } ``` `TrackingInfo` and `TrackingEvent` take a `Shopper\Core\Enum\ShipmentStatus` case as their status, where 2.x took a string: ```php use Shopper\Core\Enum\ShipmentStatus; new TrackingInfo(trackingNumber: $number, status: 'in_transit'); // [!code --] new TrackingInfo(trackingNumber: $number, status: ShipmentStatus::InTransit); // [!code ++] ``` See [Custom Shipping Drivers](/3.x/carriers#custom-shipping-drivers). ### Rate Codes of Carrier Options [#rate-codes-of-carrier-options] **Likelihood of Impact: Medium** *Affects storefronts that find the chosen carrier option from a rate's `serviceCode`.* A rate built from a carrier option holds the option's `public_id`, a ULID, in `serviceCode`, where 2.x held its numeric `id`: ```php CarrierOption::query()->find($rate->serviceCode); // [!code --] CarrierOption::query()->where('public_id', $rate->serviceCode)->first(); // [!code ++] ``` ### Search Through Scout [#search-through-scout] **Likelihood of Impact: Medium** *Affects every store, and most of all applications that already use Laravel Scout.* Shopper 3.0 requires `laravel/scout` and makes products, brands, categories, collections, orders and your User model searchable. These models follow `SCOUT_DRIVER`, like the rest of your application. With Algolia, Meilisearch or Typesense, import the existing records once, as shown in [Importing Existing Records](/3.x/search#importing-existing-records). The `database` driver does not work with Shopper's models, and searching them throws: use `collection`, the default, until you run a search engine. See [Search](/3.x/search). ### Files of Virtual Products [#files-of-virtual-products] **Likelihood of Impact: Medium** *Affects stores that sell downloadable products.* The files of virtual products move to the disk set in `shopper.media.storage.files_disk`, the private `local` disk by default. Each moved file gets a new `id`, so code or links that store a file id need the new one. See [Downloadable Files](/3.x/products#downloadable-files). ### Removed Classes and Components [#removed-classes-and-components] **Likelihood of Impact: Medium** *Affects applications that extend or register these classes.* 3.0 removes these classes: - `Shopper\Livewire\Components\Search` - `Shopper\Livewire\SlideOvers\DiscountForm` and `Shopper\Livewire\SlideOvers\RelatedProductsList` - `Shopper\Livewire\Pages\Settings\Index` - `Shopper\Livewire\Components\Settings\Legal\Privacy`, `Refund`, `Shipping` and `Terms`, replaced by `PolicyForm` - `Shopper\Livewire\Components\Settings\Team\UsersRole` - `Shopper\Traits\CanBeCacheable` - `Shopper\Cart\Discounts\DiscountCalculator` - `Shopper\Core\Actions\CreateOrderTaxLinesAction`, `Shopper\Core\Taxes\OrderItemTaxAdapter` and `Shopper\Core\Listeners\Orders\SyncOrderShippingStatusListener` A published component config that still lists one of them points to a class that no longer exists: publish it again, as in [Published Config Files](#published-config-files). The `shopper.settings.index` route goes with the `Index` page: link to `shopper.settings.shop`, the General settings page. The `x-shopper::user-avatar`, `x-shopper::menu.setting`, `x-shopper::icons.facebook`, `x-shopper::icons.instagram` and `x-shopper::icons.twitter` Blade components are removed. `Shopper::addonPermissions()` is removed too: it had no effect in 2.x, so delete the call. ### Panel Assets [#panel-assets] **Likelihood of Impact: Medium** *Affects deploy scripts and servers that serve the panel assets.* 2.x linked the panel assets at `public/{prefix}`, `public/cpanel` by default. 3.0 links them at `public/vendor/shopper`, and `shopper:link` removes the old link. The panel images and styles are served from `/vendor/shopper/...` and answer 404 until the new link exists. If `public/vendor/shopper` is a directory of published files rather than a link, delete it before you run `shopper:link`. The `/public/cpanel` line can leave your `.gitignore`. ## Low Impact Changes [#low-impact-changes] ### Renamed Zero-Decimal Command [#renamed-zero-decimal-command] **Likelihood of Impact: Low** `shopper:fix-zero-decimal-currencies` becomes `shopper:upgrade:fix-zero-decimal-currencies`. ### Inapplicable Discount Status [#inapplicable-discount-status] **Likelihood of Impact: Low** `Shopper\Core\Enum\DiscountStatus` gains the `Inapplicable` case. A `match` on the enum without a `default` arm needs it. ### Published Scope Compares the Time [#published-scope-compares-the-time] **Likelihood of Impact: Low** The `publish` scope of products compares `published_at` with the current time, where 2.x compared the date only. A product scheduled for later today stays hidden until that time. ### Duplicate Rows Merged [#duplicate-rows-merged] **Likelihood of Impact: Low** The 3.0 migrations remove duplicate rows before adding unique indexes: a product or customer attached twice to the same discount, several prices for the same product or variant in the same currency (the newest row stays), and several lines for the same product in one cart (merged into one line with the total quantity). Order numbers that appear twice are renamed, as in [Order Numbers](#order-numbers). ### Used Discounts Are Locked [#used-discounts-are-locked] **Likelihood of Impact: Low** Once a discount has been used, saving a new `code`, `type` or `value` throws `DiscountTermsFrozenException`, and moving a used fixed-amount discount to another zone throws `DiscountZoneFrozenException`. Code that edits discounts, such as an import, creates a new discount instead. ### Model Scopes Use the Scope Attribute [#model-scopes-use-the-scope-attribute] **Likelihood of Impact: Low** The query scopes of Shopper's models are protected methods marked with `#[Scope]`, such as `publish()` on products, where 2.x declared `scopePublish()`. Calls through a query, such as `Product::query()->publish()`, do not change. A swapped model that overrides a scope declares it the same way: Laravel calls the attribute method first, so a `scopePublish()` override is ignored. ```php title="app/Models/Product.php" use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; public function scopePublish(Builder $query): void // [!code --] #[Scope] // [!code ++] protected function publish(Builder $query): void // [!code ++] ``` ### Registering Custom Drivers [#registering-custom-drivers] **Likelihood of Impact: Low** The closure passed to `Payment::extend()` or `Shipping::extend()` receives the service container, where 2.x passed the driver name. A closure that takes no argument keeps working, one typed `fn (string $name)` throws a `TypeError`. `configuredDrivers()` reads the `enabled` key of `config/shopper/{driver}.php`, where 2.x read `shopper.payment.drivers.{driver}.enabled`. See [Register the Driver](/3.x/payments#step-2-register-the-driver). ### Variant Page URL [#variant-page-url] **Likelihood of Impact: Low** The admin page of a variant moves from `/products/{product}/variants/{variant}` to `/products/{product}/edit/variants/{variant}`. Links built with `route()` keep working, since the route name does not change. ### Sidebar Cache Duration [#sidebar-cache-duration] **Likelihood of Impact: Low** `cache.duration` in `config/shopper/sidebar.php` counts minutes, where 2.x passed it to the cache as seconds. With the default `1440`, a cached sidebar now lasts 24 hours instead of 24 minutes. The cache is off unless `cache.method` is set. ### Rector Removes Unused Imports [#rector-removes-unused-imports] **Likelihood of Impact: Low** The upgrade's Rector step removes the unused `use` statements of every file it scans, along with the class renames. The `git diff` you review after the upgrade includes them. ### TypeScript Types [#typescript-types] **Likelihood of Impact: Low** *Affects storefronts that import `@shopperlabs/shopper-types`, such as the 2.x Inertia starter kits.* The package moves from 1.0 to 3.0. Every `id` is a `ResourceId`, `string | number`, so the types fit models with integer keys and models with UUIDs. 1.0 typed the `id` of `Entity`, `Currency` and `Country` as a number: code that passes one of these ids where a `number` is expected now converts it, with `Number(country.id)` for instance. The `DateEntity` type is removed: dates are ISO 8601 strings. ## Coming From a Release Before 2.7 [#coming-from-a-release-before-27] The 2.x releases changed code that 3.0 relies on: amounts stored in cents (2.7), Filament components moved from `InteractsWithForms` to `InteractsWithSchemas`, slide-overs moved to the `laravelcm/livewire-slide-overs` package, and new two-factor authentication interfaces. Follow the [2.x upgrade guides](/2.x/upgrade) up to 2.12, then this guide. The `shopper-upgrade-money-storage`, `shopper-upgrade-filament-schemas`, `shopper-upgrade-slide-overs` and `shopper-upgrade-two-factor-auth` [upgrade skills](/3.x/ai-tools#upgrade-skills) cover these changes. # Version Support Policy (/3.x/version-support-policy) Shopper follows [Semantic Versioning](https://semver.org/): minor and patch releases never contain breaking changes. Major versions follow Filament's major versions, since the admin panel is built on Filament. A Filament major does not force a Shopper major when the upgrade asks almost nothing of your application. ## Support Policy [#support-policy] | Version | Filament | New features | Bug fixes | Security fixes | |---------|----------|--------------|-----------|----------------| | 1.x | 2.x | Ended July 2023 | Ended July 2023 | Ended July 2023 | | 2.x | 4.x | Ended October 2026 | Until April 2027 | Until October 2027 | | 3.x | 5.x | Until the Shopper 4.0 release | About 1 year after the Shopper 4.0 release | About 2 years after the Shopper 4.0 release | ## New Features [#new-features] New features go into the latest major version only. Once a new major version is released, pull requests that add a feature to an older version are retargeted to the latest major or closed, depending on how far the branches have moved apart. ## Bug Fixes [#bug-fixes] After a new major version is released, the previous major keeps receiving bug fixes until the date in the table. After that date, pull requests for that version are no longer accepted. Bug reports for supported versions are handled in the order they arrive, critical bugs first. A fix is written for the latest major version. Anyone can backport it to another supported version with a pull request on that version's branch. ## Security Fixes [#security-fixes] A major version receives security fixes until the date in the table, after its bug fixes have stopped. Report a vulnerability privately through [GitHub](https://github.com/shopperlabs/shopper/security/advisories/new) or by email at [arthur@shopperlabs.co](mailto:arthur@shopperlabs.co), never in a public issue. Every reported vulnerability is addressed promptly. A Shopper version that still receives security fixes can run on a PHP, Laravel, Filament or Livewire version that no longer does. An application on an older Shopper version stays exposed to the vulnerabilities of those dependencies: keep them on supported versions too. # Webhooks (/3.x/webhooks) Outgoing webhooks send an HTTP request to an external system when something happens in your store: an order is paid, a package is delivered, a product changes. An ERP, a warehouse, a marketing tool or another Laravel application receives the event without access to your database or your code. Inside your own application, listen to the [events](/3.x/events) instead: a listener runs in your process and receives the models themselves. This page covers the webhooks your store sends. The webhooks a payment provider or a carrier sends to your store are covered on the [Payments](/3.x/payments#webhooks) and [Carriers](/3.x/carriers) pages. A webhook subscription is an HTTPS URL, the events it listens to and a signing secret. When a subscribed event fires, Shopper builds the payload once, stores it, and queues one delivery per subscription on the `webhooks` queue. A queued job signs each delivery, posts it, and retries it when the endpoint fails. Without a worker on that queue nothing is sent, see [Queue Worker](/3.x/installation#queue-worker). The payload is built during the request that fired the event, after its database transaction commits (see [Dispatched After Commit](/3.x/events#dispatched-after-commit)). An error while preparing webhooks never breaks that request: Shopper logs it as `Webhook fan-out failed.` and the order or the product is saved as usual. ## Available Events [#available-events] A subscription picks events by their public name, the string the receiver gets in the `event` field. Shopper registers fourteen, listed by the `Shopper\Core\Enum\WebhookEventType` enum: | Name | Event class | Sent when | Data | |------|-------------|-----------|------| | `order.created` | `OrderCreated` | An order is created, at checkout or by your code | [Order](#order-data) | | `order.paid` | `OrderPaid` | The payment status of the order becomes Paid | [Order](#order-data) | | `order.cancelled` | `OrderCancelled` | The order is cancelled | [Order](#order-data) | | `order.shipped` | `OrderShipped` | The shipping status of the order becomes Shipped | [Order](#order-data) | | `order.completed` | `OrderCompleted` | The order moves to Completed | [Order](#order-data) | | `shipment.created` | `OrderShipmentCreated` | A package is created for the order | [Shipment](#shipment-data) | | `shipment.delivered` | `OrderShipmentDelivered` | A package reaches Delivered | [Shipment](#shipment-data) | | `shipment.delivery_failed` | `OrderShipmentDeliveryFailed` | A package reaches Delivery failed | [Shipment](#shipment-data) | | `shipment.returned` | `OrderShipmentReturned` | A package reaches Returned | [Shipment](#shipment-data) | | `product.created` | `ProductCreated` | A product is created in the admin panel or by a CSV import | [Product](#product-data) | | `product.updated` | `ProductUpdated` | The main product form is saved in the admin panel | [Product](#product-data) | | `product.deleted` | `ProductDeleted` | A product is deleted from the admin panel | [Product](#product-data) | | `customer.registered` | `CustomerRegistered` | A customer is created in the admin panel or signs up through the Store API | [Customer](#customer-data) | | `cart.completed` | `CartCompleted` | The checkout turns a cart into an order | [Order](#order-data) | The [Events](/3.x/events#all-events-reference) page gives the namespace of each class and the exact moments it fires. `product.updated` only follows the main product form: saving the pricing, inventory, media or SEO of a product sends nothing, as [Product Events](/3.x/events#product-events) explains. The first thirteen names come from the `events` key of `config/shopper/webhooks.php`. The `shopper/cart` package registers `cart.completed` itself, so the name exists only when that package is installed. Its data is the order the cart became. Your own events join the list through [Registering Custom Events](#registering-custom-events). ## Payload [#payload] Shopper sends a `POST` request with a JSON body and these headers: | Header | Value | |--------|-------| | `Content-Type` | `application/json` | | `X-Shopper-Event` | The event name, such as `order.paid` | | `X-Shopper-Event-Id` | The public ID of the event, the same for every subscription and every attempt | | `X-Shopper-Delivery-Id` | The public ID of the delivery to this subscription | | `X-Shopper-Signature` | The signature of the body, see [Signatures](#signatures) | The body wraps the data of the resource in an envelope. An `order.paid` request looks like this: ```json { "id": "01JZ9C3M8R2T6V4X7B1N5Q0WKD", "event": "order.paid", "created_at": "2026-11-17T14:32:08+00:00", "attempt": 1, "resource": { "type": "order", "id": "01JZ8Q4V6S3W9D2M7K5T1B8XNC" }, "data": { "id": "01JZ8Q4V6S3W9D2M7K5T1B8XNC", "number": "ORD-20261117-000042", "status": "new", "payment_status": "paid", "shipping_status": "unfulfilled", "price_amount": 6498, "tax_amount": 1000, "shipping_amount": 500, "currency_code": "USD", "email": "jane@example.com", "created_at": "2026-11-17T14:30:51+00:00" } } ``` | Field | Description | |-------|-------------| | `id` | Public ID of the event, a ULID. Store it to skip an event you already processed | | `event` | Event name | | `created_at` | When the event fired, in ISO 8601 | | `attempt` | Attempt number of this delivery, starting at 1 | | `resource.type` | Type of the resource, see below | | `resource.id` | [Public ID](/3.x/models#public-ids) of the resource. Find the record with `findByPublicId()` | | `data` | The attributes of the resource, listed below | The payload is a snapshot. Shopper serializes the resource when the event fires and stores the result on the event: a retry sends the same `data` with a higher `attempt`, even when the order has changed since. Orders and products are identified by their morph alias, `order` and `product`. Shipments and customers have no alias in the [morph map](/3.x/models#morph-map), so their `resource.type` is a class name: `Shopper\Core\Models\OrderShipping`, and your user model class for customers, such as `App\Models\User`. Route requests on the `event` field. ### Order Data [#order-data] The `order.*` events and `cart.completed` send the order. Amounts are integers in cents, see [Money](/3.x/money). | Field | Type | Description | |-------|------|-------------| | `id` | string | Public ID of the order | | `number` | string | Order number | | `status` | string | `new`, `processing`, `completed`, `cancelled` or `archived` | | `payment_status` | string | `pending`, `authorized`, `paid`, `partially_refunded`, `refunded` or `voided` | | `shipping_status` | string | `unfulfilled`, `partially_shipped`, `shipped`, `partially_delivered`, `delivered`, `partially_returned` or `returned` | | `price_amount` | integer | Order total | | `tax_amount` | integer | Tax total | | `shipping_amount` | integer or null | Shipping cost | | `currency_code` | string | ISO 4217 code of the order currency | | `email` | string or null | Email of the customer | | `created_at` | string | Creation date, in ISO 8601 | ### Shipment Data [#shipment-data] The `shipment.*` events send the package, an `OrderShipping` record, with a reference to its order. | Field | Type | Description | |-------|------|-------------| | `id` | string | Public ID of the package | | `order_id` | string | Public ID of the order | | `order_number` | string | Order number | | `status` | string | `pending`, `picked_up`, `in_transit`, `at_sorting_center`, `out_for_delivery`, `delivered`, `delivery_failed` or `returned` | | `carrier` | string or null | Name of the carrier | | `carrier_driver` | string or null | Driver of the carrier, `null` for a carrier without one | | `tracking_number` | string or null | Tracking number | | `tracking_url` | string or null | Tracking page of the carrier | | `shipped_at` | string or null | Date the package left, in ISO 8601 | | `received_at` | string or null | Date the package was delivered, in ISO 8601 | | `returned_at` | string or null | Date the package was returned, in ISO 8601 | ### Product Data [#product-data] The `product.*` events send the product. `product.deleted` carries the product as it was just before the deletion. | Field | Type | Description | |-------|------|-------------| | `id` | string | Public ID of the product | | `name` | string | Product name | | `slug` | string | URL slug | | `sku` | string or null | SKU | | `type` | string | `standard`, `variant`, `virtual` or `external` | | `is_visible` | boolean | Whether the product is visible on the storefront | | `published_at` | string | Publication date, in ISO 8601 | | `updated_at` | string | Date of the last update, in ISO 8601 | ### Customer Data [#customer-data] `customer.registered` sends the customer. A field without a value is left out of the object. | Field | Type | Description | |-------|------|-------------| | `id` | string | Public ID of the customer | | `email` | string | Email address | | `first_name` | string | First name | | `last_name` | string | Last name | | `created_at` | string | Registration date, in ISO 8601 | ## Signatures [#signatures] Every request carries an `X-Shopper-Signature` header that proves it comes from your store and was not changed on the way: ```text X-Shopper-Signature: t=1794925928,v1=f930421f7fd276df4af2e4c0ad2b465fb31174122fc554d928e7a03f2f4d23cb ``` `t` is the Unix time at which the attempt was sent. `v1` is the HMAC-SHA256, in lowercase hexadecimal, of the timestamp, a period and the raw request body, keyed with the secret of the subscription. Shopper signs each attempt when it sends it, so `t` stays recent on the tenth retry as on the first. A receiver verifies a request in four steps: 1. Read the raw body before decoding it. A body decoded and encoded again no longer matches the signature. 2. Read `t` and `v1` from the header, which matches `/^t=(\d+),v1=([a-f0-9]{64})$/`. 3. Refuse a timestamp more than 300 seconds away from the current time, so a captured request cannot be replayed later. 4. Compute the HMAC-SHA256 of `{t}.{body}` with the secret and compare it with `v1` in constant time. This controller does it in another Laravel application, with the secret stored under `shopper.webhook_secret` in its `config/services.php`. It hands the event to a queued job and answers at once: ```php title="app/Http/Controllers/ShopperWebhookController.php" namespace App\Http\Controllers; use App\Jobs\SyncShopperEvent; use Illuminate\Http\Request; use Illuminate\Http\Response; class ShopperWebhookController { public function __invoke(Request $request): Response { $payload = $request->getContent(); $header = (string) $request->header('X-Shopper-Signature'); if (! preg_match('/^t=(\d+),v1=([a-f0-9]{64})$/', $header, $matches)) { abort(401); } [, $timestamp, $signature] = $matches; if (abs(time() - (int) $timestamp) > 300) { abort(401); } $expected = hash_hmac('sha256', "{$timestamp}.{$payload}", config('services.shopper.webhook_secret')); if (! hash_equals($expected, $signature)) { abort(401); } SyncShopperEvent::dispatch(json_decode($payload, true)); return response()->noContent(); } } ``` Register the controller on the URL you give the subscription: ```php title="routes/web.php" use App\Http\Controllers\ShopperWebhookController; use Illuminate\Support\Facades\Route; Route::post('/webhooks/shopper', ShopperWebhookController::class); ``` Laravel checks a CSRF token on the routes of `routes/web.php`, which Shopper cannot send. Exclude the webhook route from that check: ```php title="bootstrap/app.php" ->withMiddleware(function (Middleware $middleware): void { $middleware->validateCsrfTokens(except: [ 'webhooks/shopper', ]); }) ``` A Laravel application that has `shopper/core` installed can call `Shopper\Core\Webhooks\WebhookSignature::verify($header, $payload, $secret)` instead. It runs the same checks and reads the tolerance from `signature_tolerance` in `config/shopper/webhooks.php`, 300 seconds by default. ### Responding to a Delivery [#responding-to-a-delivery] Shopper reads the status code of the answer. A 2xx code marks the delivery succeeded. A 4xx code marks it rejected, and Shopper never retries it. Any other code, a redirect, or no answer within 10 seconds counts as a failure and schedules a retry. Do the work in a queued job, as the controller above does, so the answer comes back well within the timeout. A receiver can get the same event more than once: a retry after a timeout on a request it had processed, or a redelivery from the admin panel. Keep the `id` of the events you processed and skip the ones you have seen. Each delivery is its own queued job, so a retried `order.paid` can arrive after `order.shipped`: compare `created_at` before overwriting newer data. ### Signing Secret [#signing-secret] The secret is a random 40-character string, shown once when the subscription is created in the admin panel and never again. Regenerating it from the admin panel shows the new secret once, and the old one stops working at once, for retries too, since every attempt is signed when it is sent. Update the receiver with the new secret right away. Shopper stores the secret encrypted with your application key. ## Deliveries and Retries [#deliveries-and-retries] Each subscription gets its own delivery of an event, sent by its own job, so a failing endpoint never stops the deliveries to the others. The `status` of a delivery, a `Shopper\Core\Enum\WebhookDeliveryStatus` case, records how it went: | Status | Meaning | |--------|---------| | `pending` | Queued, not sent yet | | `succeeded` | The endpoint answered with a 2xx code | | `failed` | The endpoint answered with another code or did not answer in time. Retried until the attempts run out | | `rejected` | The endpoint answered with a 4xx code, or its URL no longer passes the [endpoint checks](#endpoint-restrictions). Never retried | | `dispatch_failed` | The delivery could not be pushed to the queue. The [redispatch command](#redispatching) queues it again | A failed delivery is retried after the delays of the `backoff` key: 10 seconds, 30 seconds, 1 minute, 5 minutes, 30 minutes, then 1, 2, 4, 8 and 12 hours. That makes 11 attempts over about 28 hours. While attempts remain, the delivery keeps the `failed` status with no `completed_at`. The last attempt sets `completed_at`. Shopper does not follow redirects: point the subscription at the final URL of the endpoint, since a 3xx answer counts as a failure. When a delivery runs out of attempts and the 15 most recent succeeded or failed deliveries of its subscription have all failed, Shopper deactivates the subscription. Change the threshold with `disable_after_failures`. Shopper creates no delivery for an inactive subscription: switch it back on in the admin panel once the endpoint works again. ## Redispatching [#redispatching] A delivery can miss the queue. The queue connection may be down when the event fires, which leaves the delivery `dispatch_failed`, or a worker may stop in the middle of a job and lose it, which leaves the delivery `pending`. The `shopper:webhooks:redispatch` command queues again every `dispatch_failed` delivery, and every `pending` delivery created more than 15 minutes ago. Shopper schedules it every 15 minutes (see [Scheduler](/3.x/installation#scheduler)). Run it by hand after a queue outage: ```bash php artisan shopper:webhooks:redispatch ``` The command prints how many deliveries it queued again. It leaves `failed` deliveries alone: their retries are already scheduled, or they have used all their attempts. ### Pruning [#pruning] The `model:prune` command, which Shopper schedules daily, deletes the succeeded deliveries after 7 days and the other deliveries after 90 days. It then deletes the events older than 90 days that have no delivery left. The `prune.succeeded_after_days` and `prune.failed_after_days` keys change both delays. ## Configuration [#configuration] `config/shopper/webhooks.php` holds the event map and the delivery settings. Publish it with the other Shopper config files through the `shopper-config` tag: ```bash php artisan vendor:publish --tag=shopper-config ``` | Key | Environment variable | Default | Description | |-----|----------------------|---------|-------------| | `events` | | The 13 core events | Event class to public name. Remove a line to stop offering that event | | `database.connection` | `SHOPPER_WEBHOOKS_DB_CONNECTION` | Default connection | Connection of the webhook subscriptions, events and deliveries | | `allowed_hosts` | `SHOPPER_WEBHOOKS_ALLOWED_HOSTS` | Empty | Comma-separated hosts webhooks may be sent to. Empty allows any public host | | `max_subscriptions` | `SHOPPER_WEBHOOKS_MAX_SUBSCRIPTIONS` | `50` | Maximum number of subscriptions the admin panel creates. `0` removes the limit | | `queue` | `SHOPPER_WEBHOOKS_QUEUE` | `webhooks` | Queue of the delivery jobs | | `backoff` | | `[10, 30, 60, 300, 1800, 3600, 7200, 14400, 28800, 43200]` | Seconds to wait before each retry. A delivery gets one attempt more than the number of entries | | `disable_after_failures` | | `15` | Failed deliveries in a row that deactivate a subscription | | `timeout` | | `10` | Seconds Shopper waits for the endpoint to answer | | `signature_tolerance` | | `300` | Seconds `WebhookSignature::verify()` accepts between the signature timestamp and the current time | | `prune.succeeded_after_days` | | `7` | Age at which succeeded deliveries are deleted | | `prune.failed_after_days` | | `90` | Age at which the other deliveries, then the events, are deleted | A store that sends many webhooks can move the three webhook tables to a dedicated database with `SHOPPER_WEBHOOKS_DB_CONNECTION`, so their writes never compete with orders and payments. The migration creates the tables on that connection. ### Endpoint Restrictions [#endpoint-restrictions] Shopper only sends webhooks over HTTPS to public addresses. The URL is checked when a subscription is saved in the admin panel, then again before each attempt: every address the host resolves to must be public, which rules out `localhost`, private networks and link-local addresses, and the request connects to the address that passed the check. A delivery whose URL fails the check at send time is marked `rejected`. To try webhooks against an application on your machine, expose it through a public HTTPS tunnel, such as Expose or ngrok, and subscribe the tunnel URL. `allowed_hosts` limits deliveries to the integrations you know. A listed host also allows its subdomains: ```bash title=".env" SHOPPER_WEBHOOKS_ALLOWED_HOSTS=erp.example.com,hooks.example.org ``` ## Models [#models] The three webhook models live in `Shopper\Core\Models`. They have no configuration key, so they are always loaded with their own class, and they use the connection set by `database.connection`. ### Webhook Subscription [#webhook-subscription] `WebhookSubscription` is an endpoint and the events it listens to. | Column | Type | Description | |--------|------|-------------| | `url` | string | HTTPS URL of the endpoint | | `events` | json | Event names, cast to an array | | `secret` | text | Signing secret, encrypted with your application key | | `is_active` | boolean | Whether the subscription receives deliveries, `true` by default | | `description` | text | Free note, such as the name of the integration | `WebhookSubscription::active()` returns the active subscriptions, cached for an hour so that dispatching an event adds no query to the checkout. Saving or deleting a subscription through Eloquent clears the cache. `listensTo('order.paid')` tells whether the subscription takes an event, and `deliveries()` returns its deliveries. Deleting a subscription deletes its deliveries. ### Webhook Event [#webhook-event] `WebhookEvent` is one occurrence of an event, shared by all its deliveries. | Column | Type | Description | |--------|------|-------------| | `public_id` | string | ULID, sent as the `id` of the payload | | `name` | string | Event name, such as `order.paid` | | `resource_type` | string | Sent as `resource.type` | | `resource_id` | string | Sent as `resource.id` | | `payload` | longText | The `data` object, encrypted with your application key and cast to an array | `deliveries()` returns the deliveries of the event. ### Webhook Delivery [#webhook-delivery] `WebhookDelivery` is the sending of an event to one subscription. | Column | Type | Description | |--------|------|-------------| | `public_id` | string | ULID, sent in the `X-Shopper-Delivery-Id` header | | `webhook_event_id` | foreign key | The event | | `webhook_subscription_id` | foreign key | The subscription | | `attempt_number` | integer | Number of the last attempt | | `status` | string | A `WebhookDeliveryStatus` case | | `response_code` | integer | Status code of the last answer, `null` when the endpoint did not answer | | `response_body` | text | First 1,000 characters of the last failed or rejected answer, or the reason of the failure | | `completed_at` | timestamp | When the delivery reached a final outcome | `event()` and `subscription()` return the event and the subscription. ## Usage [#usage] The admin panel is the usual place to manage subscriptions. Code can create them too, from a seeder or a deploy script. The model checks nothing by itself: validate the URL with `WebhookUrl::isSafe()`, which runs the [endpoint checks](#endpoint-restrictions), and set the secret the receiver expects. The `max_subscriptions` limit applies to the admin panel only. ```php title="database/seeders/WebhookSubscriptionSeeder.php" namespace Database\Seeders; use Illuminate\Database\Seeder; use InvalidArgumentException; use Shopper\Core\Models\WebhookSubscription; use Shopper\Core\Webhooks\WebhookUrl; class WebhookSubscriptionSeeder extends Seeder { public function run(): void { $url = 'https://erp.example.com/webhooks/shopper'; if (! WebhookUrl::isSafe($url)) { throw new InvalidArgumentException("The webhook url [{$url}] must use https and resolve to a public address."); } WebhookSubscription::query()->create([ 'url' => $url, 'events' => ['order.paid', 'order.cancelled', 'shipment.delivered'], 'secret' => config('services.erp.webhook_secret'), 'description' => 'ERP order sync', ]); } } ``` To list the events a subscription can take, call `Webhooks::events()`. It returns the public names keyed by event class, the core events, `cart.completed` and yours: ```php use Shopper\Core\Webhooks\Facades\Webhooks; $names = array_values(Webhooks::events()); ``` Deliveries are plain Eloquent models. This query returns the deliveries that ended in a failure, with the answer of the endpoint: ```php use Shopper\Core\Enum\WebhookDeliveryStatus; use Shopper\Core\Models\WebhookDelivery; $failures = WebhookDelivery::query() ->with(['event', 'subscription']) ->whereIn('status', [WebhookDeliveryStatus::Failed, WebhookDeliveryStatus::Rejected]) ->whereNotNull('completed_at') ->latest() ->get(); ``` ## Registering Custom Events [#registering-custom-events] Any Laravel event can become a webhook. Register it in the `boot` method of a service provider with the `Shopper\Core\Webhooks\Facades\Webhooks` facade, giving the event class and its public name: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Core\Events\Orders\OrderArchived; use Shopper\Core\Webhooks\Facades\Webhooks; public function boot(): void { Webhooks::register(OrderArchived::class, 'order.archived'); } ``` The name then appears in the event list of the admin form. Without a serializer, Shopper looks for a public `shipment`, `order`, `product`, `customer` or `cart` property on the event, in this order, and sends the data of the first one it finds. `OrderArchived` carries `$order`, so `order.archived` sends the [order data](#order-data). An event with none of these properties sends an empty `data` and logs a warning. A public name belongs to one event. Registering a name another event already uses is ignored, with a warning in the log, and registering the same class twice under two names throws a `LogicException`. The entries of the `events` config key are defaults: `register()` can rename one of them or give it a serializer. Webhooks are built as soon as the event is dispatched. Events that implement `ShouldDispatchAfterCommit` are dispatched once the database transaction commits, so a checkout that rolls back sends nothing. Give your own events this contract, as Shopper's are. ### Custom Payloads [#custom-payloads] The third argument of `register()` is the serializer. A closure receives the event and returns the `resource_type`, `resource_id` and `data` keys. This one turns failed payments into a `payment.failed` webhook: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Core\Webhooks\Facades\Webhooks; use Shopper\Payment\Events\PaymentFailed; public function boot(): void { Webhooks::register(PaymentFailed::class, 'payment.failed', fn (PaymentFailed $event): array => [ 'resource_type' => $event->order->getMorphClass(), 'resource_id' => $event->order->public_id, 'data' => [ 'order_number' => $event->order->number, 'transaction_type' => $event->type->value, 'reason' => $event->reason, ], ]); } ``` A serializer class implements `Shopper\Core\Contracts\WebhookPayloadSerializer`. Shopper resolves it from the container, so it can wrap `DefaultWebhookPayloadSerializer`, a final class, to add fields to the default data. This one adds the order lines to `order.paid`: ```php title="app/Webhooks/OrderPaidPayload.php" namespace App\Webhooks; use Shopper\Core\Contracts\WebhookPayloadSerializer; use Shopper\Core\Models\OrderItem; use Shopper\Core\Webhooks\DefaultWebhookPayloadSerializer; class OrderPaidPayload implements WebhookPayloadSerializer { public function __construct( private DefaultWebhookPayloadSerializer $default, ) {} public function serialize(object $event): array { $payload = $this->default->serialize($event); $payload['data']['items'] = $event->order->items ->map(fn (OrderItem $item): array => [ 'sku' => $item->sku, 'name' => $item->name, 'quantity' => $item->quantity, 'unit_price_amount' => $item->unit_price_amount, ]) ->all(); return $payload; } } ``` This `boot` method gives the `order.paid` webhook that serializer: ```php title="app/Providers/AppServiceProvider.php" use App\Webhooks\OrderPaidPayload; use Shopper\Core\Events\Orders\OrderPaid; use Shopper\Core\Webhooks\Facades\Webhooks; public function boot(): void { Webhooks::register(OrderPaid::class, 'order.paid', OrderPaidPayload::class); } ``` The payload leaves your store and stays in the database until it is pruned. Name each field you send, as the default serializer does, so that a column added later never reaches a third party, and never send secrets, tokens or card data. To change the data of every event that has no serializer of its own, bind your class to the `WebhookPayloadSerializer` contract in the `register` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Webhooks\StorePayloadSerializer; use Shopper\Core\Contracts\WebhookPayloadSerializer; public function register(): void { $this->app->singleton(WebhookPayloadSerializer::class, StorePayloadSerializer::class); } ``` ## Permissions [#permissions] The webhooks page of the admin panel and each of its actions check the `system.settings` permission, described in [System Permissions](/3.x/acl#system-permissions). ## In the Admin [#in-the-admin] Webhooks sit under Settings, in the Store group. The page lists the subscriptions with their URL, their events, an active toggle and the date of the last change. Add webhook opens a form with the URL, the events and a description, and shows the signing secret once after saving; the button is disabled when the store reaches `max_subscriptions`. The actions of a row show its last 25 deliveries with their event, date, attempt, response code and status, redeliver its latest event as a new delivery, regenerate its secret, edit it or delete it. Redelivery is refused when the resource of the event no longer exists. To hide the page, remove it from `config/shopper/settings.php` as [Settings](/3.x/configuration#settings) describes. The [User Guide](/3.x/user-guide) walks through the screen. ## From a Storefront [#from-a-storefront] The Store API does not expose webhook subscriptions or deliveries: you manage them from the admin panel or from your code. Its `/store/webhooks/...` routes receive the events of payment providers and carriers, which are incoming webhooks. The Store API [Checkout](/3.x/store-api/checkout#payment-webhooks) guide covers these incoming webhooks. # What's New in 3.0 (/3.x/whats-new) Shopper 3.0 turns the admin panel into a full commerce backend: a storefront can now run on any stack through the Store API, and the cart, payment and shipping flows handle the cases a live store meets (prices that change during checkout, payments confirmed after a timeout, parcels tracked by the carrier). This page lists what is new by area. To move an existing store, follow the [upgrade guide](/3.x/upgrade). ## Store API and JavaScript SDK [#store-api-and-javascript-sdk] A JSON:API under `/store` serves the catalog, customer accounts, carts and their discount codes, shipping options, checkout, payment and orders. Listings support filters and cursor pagination, and reviews, store settings and legal pages have their own endpoints. The `X-Shopper-Channel` and `X-Shopper-Zone` headers set the sales channel of a request and the zone that sets its currency and prices, and every error carries a stable `code` that a storefront can test. The `@shopperlabs/shopper-sdk` package wraps the API in typed methods for JavaScript and TypeScript storefronts, with the types from `@shopperlabs/shopper-types`. See [Storefront](/3.x/storefront). ## Cart and Checkout [#cart-and-checkout] A guest cart merges into the customer's cart at login. Cart totals are stored and recomputed after `shopper.cart.totals_ttl_minutes` (15 by default), so a cart page does not recompute every line on each request. When a price changes after the customer opened the cart, checkout stops with a `price_changed` error instead of charging the old price. Once a payment session starts, a change that moves the total first releases that session at the provider. The cart answers `409` only when the payment is already collected, or while another request is creating the session. The cart pipeline accepts steps inserted before or after an existing one, to add a calculation without copying the whole pipeline. ## Promotions [#promotions] Campaigns group discounts under a name, a period and a budget, behind the `campaign` feature flag. Discounts can apply automatically without a code, and priority and combination rules decide which discounts stack on the same cart, up to `shopper.cart.max_promotions` (5 by default). A custom eligibility rule implements `DiscountEligibilityRule`. ## Pricing [#pricing] Product prices come from a `PriceResolver`, swappable in a service provider. The default `CatalogPriceResolver` reads the catalog prices; a resolver for customer group prices, B2B price lists or quantity tiers replaces it without changing the cart. ## Payments [#payments] Payment providers post to an inbox at `POST /store/webhooks/{driver}`, which stores each event once: a provider retry is applied once, and an event that arrives before its order exists is applied later by `php artisan shopper:payments:reconcile`. With `--pull`, the command also asks the provider for the status of payments still pending. A payment authorized or captured without an order after 30 minutes dispatches `PaymentOrphaned`: the Store API completes the cart it paid for when it can. Otherwise, a payment that matches one of the store's carts is reported to your exception handler, then refunded when the `reconciliation.orphans` option of the payment config is `refund`. Payment status changes follow allowed transitions only. A refund request sent again with the same idempotency key is applied once, and a refund the provider settles later stays pending until its webhook or `--pull` reports the outcome. ## Shipping [#shipping] Shipment status now follows the carrier, through the carrier's webhooks at `POST /store/webhooks/shipping/{driver}` or with `php artisan shopper:shipments:sync-tracking` (every 30 minutes while `shopper.shipping.tracking.sync` is on), and each change dispatches the shipment events. The customer can follow a parcel through a public tracking endpoint. UPS, FedEx and USPS are separate packages that you install only for the carriers you use: see [Carriers](/3.x/carriers). ## Orders [#orders] Order statuses follow a state machine: an order moves only to the statuses allowed from its current one, and completes once it is delivered and paid. `php artisan shopper:orders:reclaim` runs every hour and cancels orders left unpaid for 24 hours (`shopper.orders.reclaim_pending_after_hours`): it releases their payment at the provider and returns their stock. Orders paid offline are skipped. ## Catalog [#catalog] - A CSV import wizard creates and updates products from a file, with a progress view and a notification at the end. Custom import sources register with `resolve(ImportManager::class)->extend()`. - Product search runs on Laravel Scout. The default `collection` driver needs no search server, and a store moves to Meilisearch, Typesense or Algolia through configuration. See [Search](/3.x/search). - Sales channels have drivers and a settings page. See [Channels](/3.x/channels). - A product's attribute values can carry a swatch image, uploaded from the product's Attributes page and exposed in the Store API as `swatch_url`. See [Attributes](/3.x/attributes). - Stock levels are stored per inventory location, and `php artisan shopper:stock:reconcile` checks them against the stock movements. - Store API resources use a public ULID (`public_id`) as their id instead of the numeric key. See [Public IDs](/3.x/models#public-ids). ## Admin Panel [#admin-panel] The panel ships three themes, Default, Midnight and Evergreen, and its colors come from CSS tokens a store can override (see [Themes](/3.x/configuration#themes)). The new shell has breadcrumbs, settings grouped by area, product edit pages instead of tabs, and a customer page shell. An expired session opens a modal to confirm the password instead of losing the form, and in-app notifications can be stored in the database once `notifications.database.enabled` is turned on in `config/shopper/admin.php`. The panel is translated into English, French, Spanish, Turkish and Swedish. ## Team and Security [#team-and-security] Team members can sign in with a passkey once `SHOPPER_ENABLED_PASSKEYS` is set to `true`. Permissions use dot notation, such as `system.settings`. Every admin action and Livewire mutation checks its permission, and admin authentication runs again on each Livewire request. ## Extending [#extending] - Outbound webhooks send signed requests to your endpoints on order, shipment, product and customer events. Each request carries an `X-Shopper-Signature` header, private and local addresses are refused, and `Webhooks::register()` adds your own events. `php artisan shopper:webhooks:redispatch`, scheduled every 15 minutes, requeues deliveries that never reached the queue or were left pending by a dead worker; failed deliveries retry on their own backoff. - Add-ons add sections to the product edit page with `$panel->addonProductSections()` in their `register()` method. - The payment, shipping, import and sales channel managers extend Laravel's `Illuminate\Support\Manager`, so a custom driver registers with `extend()` like any Laravel driver. The [Webhooks](/3.x/webhooks), [Product Sections](/3.x/addons/admin-panel#product-sections), [Custom Drivers](/3.x/payments#custom-drivers) and [Custom Import Sources](/3.x/import#custom-import-sources) sections cover these, and the [Extending](/3.x/extending/overview) tab covers admin pages, render hooks, the sidebar and the Blade components. ## Requirements [#requirements] Shopper 3.0 requires PHP 8.3, Laravel 12.68 or 13.27, Filament 5.11 and Livewire 4.1 at least. Laravel 11 is no longer supported. Spatie Permission moves to version 7, and Shopper now installs Laravel Scout, Laravel Sanctum, Laravel Passkeys, `league/csv` and `spatie/laravel-query-builder`. See [Requirements](/3.x/requirements). ## Upgrading [#upgrading] Shopper 3.0 has breaking changes in the config files, the `ShopperUser`, `Cart`, `CartLine`, `PaymentDriver` and `Order` contracts, the product edit screen and the settings namespace. The `shopper/upgrade` package applies most of them: `php artisan shopper:upgrade` runs the migrations, renames classes with Rector, moves permissions to dot notation, fixes zero-decimal currency amounts, reconciles the stock snapshot with the inventory ledger, recreates the storage and panel asset links and moves the files of virtual products to a private disk, and its [Laravel Boost skills](/3.x/ai-tools#upgrade-skills) guide a coding agent through the changes that need a decision. The [upgrade guide](/3.x/upgrade) lists every change with the code before and after. # Zones (/3.x/zones) A zone is a market your store sells to: a group of countries with one currency, the carriers that deliver there and the payment methods customers can use there. A store that ships across Europe and West Africa can have a "Europe" zone in EUR with Colissimo and Stripe, and a "West Africa" zone in XOF with a local courier and cash on delivery. The Store API reads the zone of each request from the `X-Shopper-Zone` header, which carries a zone code. The zone sets the currency of new carts and of the prices the API returns, the shipping options and payment methods a cart offers, and the discounts that apply to it. Taxes do not use these zones: they have their own tax zones, described in [Taxes](/3.x/taxes). ## Model [#model] The model is `Shopper\Core\Models\Zone`, which implements the `Shopper\Core\Models\Contracts\Zone` contract. The contract declares `isEnabled()` and the `currency`, `countries`, `paymentMethods`, `carriers` and `shippingOptions` relations. Zones and countries (`Shopper\Core\Models\Country`) cannot be swapped through `config/shopper/models.php`; [Models You Cannot Swap](/3.x/models#models-you-cannot-swap) shows how to add a relation to them with `resolveRelationUsing()`. The model uses two traits. `HasPublicId` fills the `public_id` column with a ULID, as described in [Public IDs](/3.x/models#public-ids). `HasSlug` makes the slug you set unique, appending `-1`, `-2` and so on when it is taken, and adds a `findBySlug()` method. It does not build a slug from the name: a zone created without a slug has none. ## Database Schema [#database-schema] Zones are stored in the `sh_zones` table (`sh_` is the default [table prefix](/3.x/configuration#database-table-prefix)): | Column | Type | Nullable | Default | Description | |--------|------|----------|---------|-------------| | `id` | bigint | no | auto | Primary key | | `public_id` | ulid | yes | generated | Public identifier, unique | | `name` | string | no | - | Zone name, unique | | `slug` | string | yes | null | URL identifier, unique | | `code` | string | yes | null | Code the Store API matches against the `X-Shopper-Zone` header, unique | | `is_enabled` | boolean | no | false | Whether the zone is active. The Store API ignores disabled zones | | `currency_id` | bigint | no | - | Foreign key to `sh_currencies` | | `metadata` | jsonb | yes | null | Your own data, cast to an array | | `created_at` | timestamp | yes | null | Creation timestamp | | `updated_at` | timestamp | yes | null | Last update timestamp | Every zone needs a currency, and the `currency_id` foreign key cascades: deleting a currency deletes the zones that use it. ### Pivot Table [#pivot-table] The `sh_zone_has_relations` table links a zone to its countries, carriers, payment methods and collections through a polymorphic relation: | Column | Type | Description | |--------|------|-------------| | `zone_id` | bigint | Foreign key to `sh_zones`, deleted with the zone | | `zonable_type` | string | Morph alias of the related model: `country`, `carrier`, `payment_method` or `collection` | | `zonable_id` | bigint | ID of the related row | The table has no unique index, so `attach()` stores a second row when a country is already in the zone. Use `sync()` or `syncWithoutDetaching()`, as the admin panel does. ## Relationships [#relationships] The relations below are defined on the zone. Countries, carriers and payment methods define the inverse `zones()` relation with the [HasZones Trait](#haszones-trait). ### Currency [#currency] A zone belongs to one currency through `currency_id`. That currency is the default currency of the carts created in the zone, of the product prices the Store API returns for it, and of the shipping options and fixed-amount discounts of the zone, as described in [Money](/3.x/money). `currency_code` returns its ISO code, such as `EUR`: ```php $zone->currency; $zone->currency_code; ``` The `Currency` model has a global scope that hides disabled currencies. When the currency of a zone is disabled, `$zone->currency` is `null` and reading `currency_code` throws an error. ### Countries [#countries] Countries come from the `sh_countries` table, which the Shopper installer seeds with every country and its ISO codes (`cca2`, `cca3`). Look them up by code and attach them by ID: ```php use Shopper\Core\Models\Country; use Shopper\Core\Models\Zone; $europe = Zone::findBySlug('europe'); $europe->countries()->syncWithoutDetaching( Country::query()->whereIn('cca2', ['FR', 'DE', 'BE'])->pluck('id') ); ``` The database lets a country belong to several zones. The admin panel does not: its zone form disables the countries that already belong to another zone. A country model has `translated_name`, its name in the application locale (Shopper ships English, French and Swedish names), and `svg_flag`, the URL of its flag. ### Carriers [#carriers] A carrier delivers in the zones it is attached to. When a cart asks for shipping options, Shopper collects the rates of the enabled carriers of the cart zone and of no other carrier. [Carriers](/3.x/carriers#calculating-shipping-rates) describes how rates are calculated. ```php $europe->carriers()->sync([$colissimo->id, $dhl->id]); ``` ### Payment Methods [#payment-methods] A cart in a zone offers only the enabled payment methods attached to that zone. [Payment Methods](/3.x/payment-methods#zones) describes the rules. ```php $europe->paymentMethods()->sync([$creditCard->id, $bankTransfer->id]); ``` ### Shipping Options [#shipping-options] `shippingOptions()` is a `HasMany` relation to `Shopper\Core\Models\CarrierOption`: the flat rates the merchant sets for a carrier in this zone, priced in cents in the zone currency. For a carrier without a live-rate driver, a cart lists the enabled options of its zone before the customer enters an address, because they need nothing but the zone: ```php $europe->shippingOptions()->where('is_enabled', true)->get(); ``` ### Collections [#collections] Collections can be attached to zones. Shopper stores the link, but neither the models nor the Store API filter collections by zone, as described in [Collections](/3.x/collections#zones). ```php $europe->collections; ``` ## Query Scopes [#query-scopes] The `enabled` scope keeps the zones whose `is_enabled` flag is set: ```php use Shopper\Core\Models\Zone; $zones = Zone::query()->enabled()->get(); ``` ## Computed Attributes [#computed-attributes] Three accessors join the names of related rows with commas, capitalize each word, and return `N/A` when there is none: `countries_name` (the translated country names), `carriers_name` and `payments_name` (the payment method titles). Each one loads its relation, so eager load the relations before reading them in a loop: ```php use Shopper\Core\Models\Zone; $zones = Zone::query() ->with(['currency', 'countries', 'carriers', 'paymentMethods']) ->get(); $summary = $zones->map(fn (Zone $zone): string => "{$zone->name} ({$zone->currency_code}): {$zone->countries_name}"); ``` ## HasZones Trait [#haszones-trait] The `Shopper\Core\Models\Traits\HasZones` trait adds the inverse relation, `zones()`, a `MorphToMany` on the pivot table. `Country`, `Carrier` and `PaymentMethod` use it, and `Collection` defines the same relation itself. Add it to a model of your own to scope it to zones, for example the promotional banners of a storefront: ```php title="app/Models/Banner.php" namespace App\Models; use Illuminate\Database\Eloquent\Model; use Shopper\Core\Models\Traits\HasZones; class Banner extends Model { use HasZones; } ``` This code attaches a banner to the Europe zone, then lists the banners of the zone `EU`: ```php use App\Models\Banner; use Illuminate\Database\Eloquent\Builder; $banner->zones()->sync([$europe->id]); $banners = Banner::query() ->whereHas('zones', fn (Builder $query) => $query->where('code', 'EU')) ->get(); ``` ## Resolving a Zone [#resolving-a-zone] The Store API sets the zone of a request from the `X-Shopper-Zone` header, which carries the `code` of a zone. The example below uses `store`, the default prefix of the Store API routes, set by `SHOPPER_API_PREFIX`: ```bash curl https://example.com/store/products \ -H "X-Shopper-Zone: EU" ``` The `Shopper\Http\Middleware\ResolveZone` middleware runs on every route of the `shopper:store` and `shopper:store-auth` groups. It resolves the zone in this order: 1. The enabled zone whose code matches the header. 2. When the header is missing, unknown, longer than 64 characters or names a disabled zone: the enabled zone whose code is set in `SHOPPER_API_DEFAULT_ZONE`. 3. Otherwise no zone. The request goes on without one and the API returns no error. The default resolver never looks at the customer's address. A cart whose shipping address is outside its zone gets no shipping option and a warning that asks the customer to choose the zone of their country. Set `SHOPPER_API_DEFAULT_ZONE` before you open the Store API. A cart created without a zone uses the store default currency, offers every enabled payment method of the store whose driver is configured, and gets a `422` error when it asks for shipping options. The settings live in `config/shopper/http.php`: ```php title="config/shopper/http.php" 'zone' => [ 'resolver' => Shopper\Http\Zone\DefaultZoneResolver::class, 'header' => 'X-Shopper-Zone', 'default_code' => env('SHOPPER_API_DEFAULT_ZONE'), 'cache_ttl' => 60, ], ``` The resolver caches each zone it finds, with its currency, for `cache_ttl` seconds, and forgets it when the zone is saved or deleted. Set `cache_ttl` to `0` to query the database on every request. Every response adds the header name to `Vary`, so a shared cache keeps one copy per zone. ### What the Zone Changes [#what-the-zone-changes] When a zone is resolved: - `POST /store/carts` records it on the new cart and, when the request sends no `currency_code`, gives the cart the zone currency. The order placed from the cart keeps the zone. - The product endpoints return prices in the zone currency when the request has no `filter[currency]`, as described in [Pricing](/3.x/pricing). - The pricing context passed to the price resolver carries its ID in `Shopper\Core\Pricing\PricingContext::$zoneId`. The default resolver ignores it; a custom one can set prices per zone. The zone recorded on the cart, not the header, drives the rest of the checkout: - `GET /store/carts/{cartId}/shipping-options` returns the rates of the zone's carriers, and answers `422` for a cart without a zone. - `GET /store/carts/{cartId}/payment-methods` returns the payment methods of the zone. - A discount limited to a zone applies only to carts in that zone. A fixed-amount discount of a zone is in the zone currency and does not apply to a cart in another currency. To move a cart to another zone, send the new code in `zone_code`: ```bash curl -X PATCH "https://example.com/store/carts/01JD8Z3K4M5N6P7Q8R9S0T1V2W" \ -H "Content-Type: application/json" \ -d '{"zone_code": "WA"}' ``` The code must belong to an enabled zone. Shopper prices the lines again for the new zone, removes the shipping option and the payment method of the cart, and checks its discount codes again. The cart keeps its currency: send `currency_code` in the same request to change it as well. ### Reading the Zone in Your Own Endpoints [#reading-the-zone-in-your-own-endpoints] The middleware stores the zone in the `shopper_zone` request attribute, as an instance of the zone contract or `null`. A route registered inside `Shopper\Http\Facades\ShopperApi::store()` runs the same middleware and can read it with `$request->attributes->get('shopper_zone')`. [Channels](/3.x/channels#reading-the-channel-in-your-own-endpoints) shows a complete endpoint and its route. ### Custom Resolver [#custom-resolver] To find the zone another way, from the country of the visitor or a domain per market, implement `Shopper\Http\Contracts\ZoneResolver` and set it as the `resolver`. This resolver keeps the header when the storefront sends one, and otherwise picks the zone of the country Cloudflare detected in the `CF-IPCountry` header: ```php title="app/Http/CountryZoneResolver.php" namespace App\Http; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; use Shopper\Core\Models\Contracts\Zone as ZoneContract; use Shopper\Core\Models\Zone; use Shopper\Http\Contracts\ZoneResolver; use Shopper\Http\Zone\DefaultZoneResolver; final class CountryZoneResolver implements ZoneResolver { public function __construct(private readonly DefaultZoneResolver $codeResolver) {} public function resolve(Request $request): ?ZoneContract { $country = $request->headers->get('CF-IPCountry'); if ($request->headers->has(config('shopper.http.zone.header')) || blank($country)) { return $this->codeResolver->resolve($request); } return Zone::query() ->enabled() ->with('currency') ->whereHas('countries', fn (Builder $query) => $query->where('cca2', $country)) ->first() ?? $this->codeResolver->resolve($request); } } ``` Set `App\Http\CountryZoneResolver::class` as the `resolver` key of the `zone` array in `config/shopper/http.php`. The cache and the `Vary` header of the default resolver cover the zone header only. Responses that depend on `CF-IPCountry` need that header in `Vary` too when a shared cache sits in front of the API. ## Configuration [#configuration] Zones have no feature flag and no key in `config/shopper/models.php`. The Store API settings are described in [Resolving a Zone](#resolving-a-zone). ### Components [#components] The zones page of the admin panel is part of the settings components. To replace one of them with your own Livewire component, publish the settings component file: ```bash php artisan shopper:component:publish setting ``` The command creates `config/shopper/components/setting.php`. These entries belong to zones: ```php title="config/shopper/components/setting.php" use Shopper\Livewire; return [ 'pages' => [ 'zones' => Livewire\Pages\Settings\Zones::class, ], 'components' => [ 'settings.zones.detail' => Livewire\Components\Settings\Zones\Detail::class, 'settings.zones.shipping-options' => Livewire\Components\Settings\Zones\ZoneShippingOptions::class, 'slide-overs.zone-form' => Livewire\SlideOvers\ZoneForm::class, 'slide-overs.shipping-option-form' => Livewire\SlideOvers\ShippingOptionForm::class, ], ]; ``` The [Configuration](/3.x/configuration#components) page explains how component overriding works. ## Usage [#usage] The examples below set up the zones of a store that sells in Europe and West Africa. ### Creating Zones [#creating-zones] A zone needs a name and a currency. Give it a code as well: the Store API finds zones by code only, so a zone without one can be reached by a custom resolver alone. To create a zone for the European market: ```php use Shopper\Core\Models\Carrier; use Shopper\Core\Models\Country; use Shopper\Core\Models\Currency; use Shopper\Core\Models\PaymentMethod; use Shopper\Core\Models\Zone; $europe = Zone::query()->create([ 'name' => 'Europe', 'slug' => 'europe', 'code' => 'EU', 'is_enabled' => true, 'currency_id' => Currency::query()->where('code', 'EUR')->value('id'), ]); $europe->countries()->sync( Country::query()->whereIn('cca2', ['FR', 'DE', 'BE', 'NL', 'ES', 'IT'])->pluck('id') ); $europe->carriers()->sync(Carrier::query()->whereIn('slug', ['colissimo', 'dhl'])->pluck('id')); $europe->paymentMethods()->sync(PaymentMethod::query()->where('slug', 'credit-card')->pluck('id')); ``` The admin form requires a code of 10 characters at most, at least one country, one carrier and one payment method. The model checks none of these. ### Retrieving Zones [#retrieving-zones] To find the zone of a shipping address, match its country: ```php use Illuminate\Database\Eloquent\Builder; use Shopper\Core\Models\Zone; $zone = Zone::query() ->enabled() ->whereHas('countries', fn (Builder $query) => $query->where('cca2', 'FR')) ->first(); ``` To find a zone by the code a storefront sends, and to list the enabled zones with their currency: ```php $zone = Zone::query()->enabled()->where('code', 'EU')->first(); $zones = Zone::query()->enabled()->with('currency')->get(); ``` ### Updating Zones [#updating-zones] Update a zone like any Eloquent model, and sync its relations to replace them: ```php $europe->update(['name' => 'European Union']); $europe->paymentMethods()->sync([$creditCard->id, $paypal->id]); ``` Saving the zone clears the resolver cache for its code, and for its previous code when the code changed. Carts already in the zone see the new payment methods and carriers the next time they ask for them. A disabled zone is no longer resolved from the header and `PATCH /store/carts/{cartId}` refuses its code, but the carts already in it keep it. ### Deleting Zones [#deleting-zones] Deleting a zone sets `zone_id` to `null` on its carts, orders and discounts. A discount limited to the zone then applies in every zone, so disable a zone that customers have used instead of deleting it. The database refuses to delete a zone that still has shipping options: delete them first. ## Events [#events] Shopper dispatches no zone event of its own and registers no observer on zones or countries. `shopper/http` listens to the Eloquent `saved` and `deleted` events of zones to clear the resolver cache. Listen to the same Eloquent events for your own code: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Cache; use Shopper\Core\Models\Zone; public function boot(): void { Zone::saved(fn () => Cache::forget('storefront.markets')); Zone::deleted(fn () => Cache::forget('storefront.markets')); } ``` Moving a cart to another zone can dispatch `CartLinesRepriced` and `CouponRemoved`, described in [Cart and Discount Events](/3.x/events#cart-and-discount-events). ## Permissions [#permissions] The zones page checks one permission, `system.settings`, when it opens and on every action: creating, editing and deleting a zone, and adding, editing and deleting a shipping option. The [Access Control](/3.x/acl#system-permissions) page lists the system permissions. ## In the Admin [#in-the-admin] Merchants manage zones under Settings, Zones. The page lists the zones with their status and number of countries, with a search field that matches a zone name or a country name. Selecting a zone shows its countries, currency, payment methods, carriers and metadata, and its shipping options, which are added, edited and deleted there. The zone form opens in a slide-over: name, slug, code, countries, a currency picked from the currencies enabled in the store settings, the enabled toggle, payment methods, carriers and metadata. The setup guide of the dashboard marks its zones step as done once an enabled zone exists. The [User Guide](/3.x/user-guide) walks through these screens. ## From a Storefront [#from-a-storefront] The Store API exposes the enabled zones and the countries under the `store` prefix, set by `SHOPPER_API_PREFIX`: | Endpoint | Returns | |----------|---------| | `GET /store/zones` | The enabled zones, paginated. Filter with `filter[name]` (partial match) and `filter[code]`, sort with `sort=name` | | `GET /store/zones/{code}` | One enabled zone, by code | | `GET /store/countries` | The countries, paginated. Filter with `filter[name]`, `filter[cca2]`, `filter[cca3]`, `filter[region]` and `filter[zone]` (a zone code) | | `GET /store/countries/{code}` | One country, by `cca2` or `cca3` code | A zone resource has the type `zones` and carries `name`, `slug`, `code`, `currency_code`, `metadata`, `created_at` and `updated_at`, with `include=currency,countries` for its relations. A storefront lists the zones to build a market or country picker, then sends the chosen code in the `X-Shopper-Zone` header of every request: ```bash curl "https://example.com/store/zones?include=countries" ``` When the customer picks another market during checkout, move the cart with `PATCH /store/carts/{cartId}` and `zone_code`, as described in [What the Zone Changes](#what-the-zone-changes). The Store API [Store and Regions](/3.x/store-api/store#picking-a-zone-and-a-currency) guide shows how a storefront picks a zone. # Alert (/3.x/extending/components/alert) The alert displays a colored message box: information, a success, a warning or an error. The admin panel uses it for notices inside forms and slide-overs, like the warning the variant slide-overs show when a variant with the same options already exists. ## Preview [#preview] The preview shows a warning alert with a title and an icon. ## Usage [#usage] Pass the message, and optionally a color, a title and an icon: ```blade ``` ## Props [#props] Only the message is required. The alert has no slot: everything it shows comes from its props. The text of the alert. The color of the background, ring, icon and text: `info`, `success`, `warning` or `danger`. A title displayed above the message. The name of an icon from an installed Blade Icons set, like `untitledui-alert-triangle` or `heroicon-o-information-circle`, rendered with Filament's icon component. Without it, the alert shows no icon. The size of the icon: `Filament\Support\Enums\IconSize::Small`, `Medium` or `Large`, or their values `sm`, `md` and `lg`. Pass it as the `icon-size` attribute. ## Color Variants [#color-variants] Each color sets the background, the ring, the icon color and the text color of the alert, in light and dark mode. ### Info [#info] Use `info` for neutral guidance. This Blade sets the `info` color and the `untitledui-info-circle` icon: ```blade ``` ### Success [#success] Use `success` to confirm that something worked. This Blade sets the `success` color and the `untitledui-check-circle` icon: ```blade ``` ### Warning [#warning] Use `warning`, the default color, for a situation that needs attention. This Blade sets the `warning` color and the `untitledui-alert-triangle` icon: ```blade ``` ### Danger [#danger] Use `danger` for an error or an action that cannot be undone. This Blade sets the `danger` color and the `untitledui-x-circle` icon: ```blade ``` ## Examples [#examples] The examples below leave out the title or the icon, and place an alert inside a form. ### Alert Without Title [#alert-without-title] Without a title, the message sits next to the icon. This Blade passes the `message` and the `icon`, with no `title`: ```blade ``` ### Alert Without Icon [#alert-without-icon] Leave out the `icon` prop to display the text only. This Blade passes the `title` and the `message`, with no `icon`: ```blade ``` ### Using in Forms [#using-in-forms] Alerts often sit above the fields they warn about. The `class` attribute is merged into the alert's classes, so you can add spacing: ```blade ``` ### Icon Size [#icon-size] Pass `icon-size` to change the size of the icon: ```blade ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/alert.blade.php` in the `shopper/framework` package: ```blade @php use Filament\Support\Enums\IconSize; @endphp @props([ 'message', 'color' => 'warning', 'title' => null, 'icon' => null, 'iconSize' => IconSize::Medium, ]) @php if (! $iconSize instanceof IconSize) { $iconSize = filled($iconSize) ? IconSize::tryFrom($iconSize) ?? $iconSize : null; } $containerClass = \Illuminate\Support\Arr::toCssClasses([ 'rounded-lg p-4 ring-1', match ($color) { 'info' => 'bg-info-50 ring-info-200 dark:ring-info-400/20 dark:bg-info-800/30', 'danger' => 'bg-danger-50 ring-danger-200 dark:ring-danger-400/20 dark:bg-danger-800/30', 'success' => 'bg-success-50 ring-success-200 dark:ring-success-400/20 dark:bg-success-800/30', 'warning' => 'bg-warning-50 ring-warning-200 dark:ring-warning-400/20 dark:bg-warning-800/30', default => 'bg-custom-50 ring-custom-200 dark:ring-custom-400/20 dark:bg-custom-800/30', }, ]); $iconClasses = \Illuminate\Support\Arr::toCssClasses([ 'sh-icon size-4', match ($iconSize) { IconSize::Small => 'size-4', IconSize::Medium => 'size-5', IconSize::Large => 'size-6', default => $iconSize, }, match ($color) { 'info' => 'text-info-400 dark:text-info-500', 'danger' => 'text-danger-400 dark:text-danger-500', 'success' => 'text-success-400 dark:text-success-500', 'warning' => 'text-warning-400 dark:text-warning-500', default => 'text-custom-400 dark:text-custom-500', }, ]); $titleClasses = \Illuminate\Support\Arr::toCssClasses([ 'text-sm/5 font-medium', match ($color) { 'info' => 'text-info-600 dark:text-info-500', 'danger' => 'text-danger-600 dark:text-danger-500', 'success' => 'text-success-600 dark:text-success-500', 'warning' => 'text-warning-600 dark:text-warning-500', default => 'text-custom-600 dark:text-custom-500', }, ]); $messageClasses = \Illuminate\Support\Arr::toCssClasses([ 'text-sm/5', 'mt-2' => $title, match ($color) { 'info' => 'text-info-500 dark:text-info-400', 'danger' => 'text-danger-500 dark:text-danger-400', 'success' => 'text-success-500 dark:text-success-400', 'warning' => 'text-warning-500 dark:text-warning-400', default => 'text-custom-500 dark:text-custom-400', }, ]); @endphp
    twMerge(['class' => $containerClass]) }}>
    @if ($icon)
    @endif
    @if ($title)

    {{ $title }}

    @endif

    {{ $message }}

    ``` # Card (/3.x/extending/components/card) The card is the main container of the admin panel: product forms, order details and settings pages group their content in cards. It draws an outer frame for the header and footer, and an inner panel for the content. ## Preview [#preview] The preview shows a card with a title, a description and some content.

    The product has 42 units in stock in the Paris warehouse.

    ## Usage [#usage] Pass the title and description as attributes, and the content as the default slot: ```blade

    The product has 42 units in stock in the Paris warehouse.

    ``` ## Props [#props] The card takes three props. The header only renders when the title is not empty. The header title. A string is rendered with the [section heading](/3.x/extending/components/section-heading) component, along with the description. A slot is printed as is, so it brings its own markup. Text displayed below a string title. It is ignored when the title is a slot. Content displayed below the inner panel. The card prints it without a wrapper, so give it its own padding. ## Examples [#examples] The examples below cover the title variants, form content and the footer slot. ### Basic Card [#basic-card] Without a title, the card only renders the inner panel.

    Free shipping applies to orders over $50.

    This Blade puts a paragraph in a card without a `title`: ```blade

    Free shipping applies to orders over $50.

    ``` ### Card with Title Only [#card-with-title-only] The description is optional.

    Display product details in an organized manner.

    This Blade gives the card a `title` and no `description`: ```blade

    Display product details in an organized manner.

    ``` ### Card with Custom Title Slot [#card-with-custom-title-slot] Pass a `title` slot to add elements next to the title, like a link or a button. The slot replaces the section heading, so style the title yourself: ```blade

    Recent Orders

    View all

    Orders placed in the last 24 hours.

    ``` ### Card with Form Content [#card-with-form-content] Cards hold the fields of most admin forms. The [label](/3.x/extending/components/label) and `x-shopper::forms.input` components match the admin panel's field styles:
    This Blade puts two fields in the card, each made of a label and an input: ```blade
    Contact name
    Email
    ``` ### Card with Footer [#card-with-footer] The `footer` slot renders in the outer frame, below the inner panel. Add the padding the content needs: ```blade

    Remaining balance: $75.00

    Disable
    ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/card.blade.php` in the `shopper/framework` package: ```blade @blaze @props([ 'title' => null, 'description' => null, 'footer' => null, ])
    twMerge(['class' => 'sh-card flex flex-col justify-bewteen bg-sh-card ring-sh-border overflow-hidden rounded-xl p-0.5 ring-1']) }} > @if (mb_trim((string) $title) !== '')
    @if ($title instanceof \Illuminate\View\ComponentSlot) {{ $title }} @else @endif
    @endif
    {{ $slot }}
    @if ($footer) {{ $footer }} @endif
    ``` # Empty Card (/3.x/extending/components/empty-card) The empty card fills a card or a panel that has nothing to show yet. It is more compact than the [empty state](/3.x/extending/components/empty-state) of a table: an icon in a circle, a heading, a description and an optional action. The admin panel uses it for a customer without addresses, a zone without shipping options or a product without related products. ## Preview [#preview] The preview shows the icon, the heading and the description, centered. ## Usage [#usage] Pass the heading, the description and the name of a Blade icon: ```blade ``` ## Props [#props] Only the heading is required. Other attributes go to the wrapping `div`. The heading of the empty card. The text below the heading. The name of a Blade icon, displayed in a circle above the heading. Without it, the card shows no circle. A button or a link displayed below the text. Pass it as a named slot. ## Examples [#examples] The examples below add an action and leave out the icon. ### With Action Button [#with-action-button] Pass a button in the `action` slot. This one sits in the points card of a loyalty member and opens the `shopper-loyalty.form` slide-over of the add-on built in [Extending the Admin Panel](/3.x/addons/admin-panel), with the member as argument: Adjust Points} /> This Blade puts a Filament button in the `action` slot. A click dispatches `openPanel` with the name of the slide-over and the ID of the member: ```blade Adjust Points ``` ### Without Icon [#without-icon] Leave out `icon` to display the text only. This Blade passes the `heading` and the `description`, with no `icon`: ```blade ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/empty-card.blade.php` in the `shopper/framework` package: ```blade @blaze @props([ 'heading', 'description' => null, 'icon' => null, 'action' => null, ])
    twMerge(['class' => 'flex flex-col items-center justify-center px-8 py-10 text-center']) }} > @if ($icon)
    @svg($icon, 'size-5', ['aria-hidden' => 'true'])
    @endif

    $icon])> {{ $heading }}

    @if ($description)

    {{ $description }}

    @endif @if ($action)
    {{ $action }}
    @endif
    ``` # Empty State (/3.x/extending/components/empty-state) The empty state is what a table shows before it holds any record: an illustration, a title, a short explanation and a button to create the first record. Shopper's main tables each have one, from products to webhooks. ## Preview [#preview] The component stacks its content in a centered column, at most `max-w-md` wide: the illustration, the title, the text, then the button. Open an empty list in your admin panel, the suppliers page for instance, to see it. ## Usage [#usage] Pass the title, the text and the button, and put the illustration in the default slot. The suppliers table passes the same props: ```blade ``` ## Props [#props] The title and the content are required. The four other props build the button. The heading of the empty state. The text below the title: what the list holds and how to add the first record. The label of the button. The button only shows when `permission` is set, the user has that permission, and `url` or `panel` is set. The permission the user needs to see the button, like `suppliers.create`. It is checked with `@can`. The URL the button links to, opened with `wire:navigate`. When both are set, `url` wins over `panel`. The arguments of the `openPanel` event that opens a slide-over, written as a JavaScript object such as `{ component: 'shopper-slide-overs.supplier-form' }`. The default slot holds the illustration, centered above the title. A named `action` slot replaces the button: when you pass it, the component ignores `button`, `permission`, `url` and `panel`. ## Examples [#examples] The examples below cover the two kinds of button, no button, and custom content in the slots. ### Basic Empty State [#basic-empty-state] Without a button, the empty state only informs. The orders table uses one, since orders come from the storefront: ```blade ``` ### With URL Action [#with-url-action] Pass `url` when the record is created on its own page. The customers table links to the customer form: ```blade ``` ### With Panel Action [#with-panel-action] Pass `panel` to open a slide-over instead of leaving the page. The value is printed inside the `$dispatch('openPanel', ...)` call, so write it as a JavaScript object: ```blade ``` ### Without Button [#without-button] Leave out `permission` and the button props when the records come from somewhere else, like reviews written by customers: ```blade ``` ### Custom Slot Content [#custom-slot-content] The default slot takes any markup, like an inline SVG that uses the theme colors. The `action` slot takes your own button, for instance one that mounts a Filament action of the Livewire component. The slot skips the permission check, so add `@can` yourself: ```blade @can('loyalty.create') Enroll Customer @endcan ``` ## Usage in Livewire Components [#usage-in-livewire-components] A Filament table shows its empty state when its query returns no record. Render the component from a view and pass it to the table's `emptyState()` method, as Shopper's tables do: ```php title="app/Livewire/GiftCards.php" use App\Models\GiftCard; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; public function table(Table $table): Table { return $table ->query(GiftCard::query()->latest()) ->columns([ TextColumn::make('code') ->searchable(), TextColumn::make('expires_at') ->date(), ]) ->emptyState(view('livewire.empty-states.gift-cards')); } ``` The view holds the `x-shopper::empty-state` component, as in the examples above. Outside a table, render it yourself when the collection is empty: ```blade @if ($giftCards->isEmpty()) @else
      @foreach ($giftCards as $giftCard)
    • {{ $giftCard->code }}
    • @endforeach
    @endif ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/empty-state.blade.php` in the `shopper/framework` package: ```blade @props([ 'title', 'content', 'button' => false, 'permission' => false, 'url' => false, 'panel' => null, ])
    twMerge(['class' => 'relative mx-auto flex w-full max-w-md flex-col items-center py-12 text-center']) }} >
    {{ $slot }}

    {{ $title }}

    {{ $content }}

    @if (isset($action))
    {{ $action }}
    @elseif ($permission) @can($permission) @if ($url) {{ $button }} @elseif ($panel) {{ $button }} @endif @endcan @endif
    ``` # Filament Components (/3.x/extending/components/filament) The admin panel builds its forms and tables with Filament, plus a few components of its own: fields for channels, countries, phone numbers, slugs, prices and social links, a header for form sections, and columns for ratings and users. They live in the `shopper/framework` package under the `Shopper\Components` namespace. Use them in the schemas and tables of the Livewire components you add to the admin panel; their views use the admin's `sh-*` classes, so they render as expected only there. ## Section Header [#section-header] `Shopper\Components\SectionHeader` is a heading with an optional description and icon, placed among the fields of a schema. It looks like the header of a Filament section, without the box and without children. The product form opens with one, showing the product type with its icon: ```php use Filament\Forms\Components\TextInput; use Filament\Support\Enums\IconSize; use Shopper\Components\SectionHeader; SectionHeader::make('Gift card') ->description('The code and the balance customers spend at checkout.') ->icon('untitledui-gift') ->iconSize(IconSize::Large) ->columnSpanFull(), TextInput::make('code') ->required() ``` `make()` takes the heading. `description()`, `icon()`, `iconColor()` and `iconSize()` are optional; the icon is large unless you set another size. ## Form Fields [#form-fields] Each field below extends a Filament field, so it accepts that field's methods: `label()`, `required()`, `helperText()`, `relationship()` and the others. ### Channel Toggles [#channel-toggles] `Shopper\Components\Form\ChannelToggles` extends `CheckboxList`. It lists every sales channel with its logo and a switch, enabled channels first, and counts the selected ones below the list. A disabled channel shows a Disabled badge and its switch is locked, but it stays valid on save, so a record keeps the disabled channels it already had. The product form uses it for the Sales channels group: ```php use Shopper\Components\Form\ChannelToggles; ChannelToggles::make('channels') ->hiddenLabel() ->relationship('channels', 'name') ``` The field reads the channels itself, so it needs no `options()`. Save the selection through a relationship or as a list of channel IDs. ### Country Field [#country-field] `Shopper\Components\Form\CountryField` extends `Select`. It lists the countries of the `countries` table with their flag, grouped by region, and searches their names in the current locale. Its label is Country and its value is the ID of the country. The address forms, the shipping and tax zones, the general settings and the setup wizard use it. `only()` and `except()` take ISO 3166-1 alpha-2 codes, and `groupedByRegion(false)` lists the countries without regions. A pickup point form limited to four countries: ```php use Shopper\Components\Form\CountryField; CountryField::make('country_id') ->only(['FR', 'BE', 'CH', 'LU']) ->groupedByRegion(false) ->required() ``` The country list is cached for a day per locale. ### Image Picker [#image-picker] `Shopper\Components\Form\ImagePicker` extends `Radio` and shows its options as a grid of thumbnails, with a check mark on the selected one. Each option maps a value to an image URL. The product and variant pages use it to choose the thumbnail among the product images: ```php use Shopper\Components\Form\ImagePicker; use Spatie\MediaLibrary\MediaCollections\Models\Media; ImagePicker::make('media_id') ->label('Cover image') ->required() ->options( fn (): array => $this->product->getMedia(config('shopper.media.storage.collection_name')) ->mapWithKeys(fn (Media $media): array => [$media->id => $media->getUrl()]) ->all() ) ``` ### Number Stepper [#number-stepper] `Shopper\Components\Form\NumberStepper` extends `TextInput`. It is a numeric input with a minus and a plus button, which add or remove one `step()` (1 by default) and stop at `minValue()` and `maxValue()`. The stock adjustment and the inventory priority fields use it. For the points a customer earns per order: ```php use Shopper\Components\Form\NumberStepper; NumberStepper::make('points_per_order') ->label('Points per order') ->minValue(0) ->maxValue(1000) ->step(5) ->default(10) ->required() ``` ### Phone Input [#phone-input] `Shopper\Components\Form\PhoneInput` extends `TextInput`. It adds a country selector with flags and calling codes before the number, validates the number for the selected country with the `Shopper\Core\Rules\Phone` rule, and saves it in E.164 format, like `+33612345678`. Its label is Phone number. The address forms, the profile page and the team member form use it. The country selected by default is the store country set in the general settings. `defaultCountry()` takes another ISO 3166-1 alpha-2 code: ```php use Shopper\Components\Form\PhoneInput; PhoneInput::make('phone_number') ->defaultCountry('CA') ``` A saved number selects its own country when the form loads. ### Slug Input [#slug-input] `Shopper\Components\Form\SlugInput` extends `TextInput`. `from()` names the field the slug comes from: while you create a record, typing in that field fills the slug, until you edit the slug yourself. A button in the input generates the slug again from the source field. On save, the value goes through `Str::slug()`, and an empty slug is generated from the source field. Its label is Slug. The brand, supplier and collection forms use it: ```php use Filament\Forms\Components\TextInput; use Shopper\Components\Form\SlugInput; TextInput::make('name') ->required(), SlugInput::make('slug') ->from('name') ->prefix('/brands/') ->required() ``` When the form is bound to a record that already exists, with `$schema->model($brand)` for instance, the slug no longer follows the source field, so that a published URL does not change by accident. ### Social Links Field [#social-links-field] `Shopper\Components\Form\SocialLinksField` extends `Repeater`. Each row holds a platform and a URL, and the URL must belong to the platform, such as an `instagram.com` address for Instagram. A platform appears once at most, and the rows can be reordered. The platforms come from the `Shopper\Core\Enum\SocialPlatform` enum: Facebook, Instagram, X (Twitter), LinkedIn, YouTube, TikTok, Pinterest, Snapchat, WhatsApp, Telegram, GitHub and Website. The general settings use it for the store's social links. The field saves a list of `platform` and `url` pairs, so cast the column to an array: ```php use Shopper\Components\Form\SocialLinksField; SocialLinksField::make('social_links') ``` ### Money Input [#money-input] `Shopper\Components\Form\MoneyInput` is the field behind every price of the admin panel: it shows the stored cents as a decimal amount, saves the amount as cents and shows the currency code. [Admin Forms and Tables](/3.x/money#admin-forms-and-tables) on the Money page describes its methods. ## Table Columns [#table-columns] The two columns below extend Filament's `Column` and render their own view. ### Rating Column [#rating-column] `Shopper\Components\Tables\RatingColumn` shows a rating out of 5 as five stars, filled up to the value of the column. The reviews table uses it. ### User Column [#user-column] `Shopper\Components\Tables\UserColumn` shows a user's profile picture next to their full name. It reads the `picture` and `full_name` attributes, which the `InteractsWithShopper` trait adds to your user model, as described in [Prepare Your User Model](/3.x/installation#prepare-your-user-model) and [Computed Attributes](/3.x/customers#computed-attributes). By default the column shows the record itself. `user()` takes a closure that returns another user, like the author of a review or the customer of an order, and `currentUserBadge()` adds a Me badge on the row of the logged-in administrator. A table of reviews waiting for approval: ```php title="app/Livewire/Shopper/PendingReviews.php" use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Shopper\Components\Tables\RatingColumn; use Shopper\Components\Tables\UserColumn; use Shopper\Core\Models\Review; public function table(Table $table): Table { return $table ->query(Review::query()->where('approved', false)->latest()) ->columns([ UserColumn::make('author.full_name') ->label('Customer') ->user(fn (Review $record) => $record->author), RatingColumn::make('rating') ->label('Rating'), TextColumn::make('title') ->limit(40), ]); } ``` The column name only serves the search and the sort. `full_name` is computed, not stored: to search or sort the column, name it after a stored column, as the customers table does with `first_name`, or pass a query to `searchable()`, as the reviews table does. # Heading (/3.x/extending/components/heading) The heading displays the title at the top of a page, with an optional slot for the buttons that act on the page. Every index page of the admin panel starts with one: products, categories, customers and the others. ## Preview [#preview] The preview shows a page title with a primary button on the right. Add Product ## Usage [#usage] Pass the title as an attribute and the buttons in the `action` slot. The products page opens its creation slide-over this way: ```blade @can('products.create') Add Product @endcan ``` On small screens the title and the action stack. From the `sm` breakpoint they sit on one line, the action aligned to the right. ## Props and Slots [#slots] The heading takes one prop and one named slot. The page title. A string is rendered in an `h2` with the admin panel's title styles. A slot is printed as is, without the `h2`, so it brings its own markup. Buttons or other controls, displayed on the right of the title. ## Examples [#examples] The examples below cover a title alone, one or several actions, and a custom title. ### Simple Heading [#simple-heading] Without the `action` slot, the heading only shows the title. This Blade renders the heading with its `title` only: ```blade ``` ### Heading with Action Button [#heading-with-action-button] The categories page opens the category form in a slide-over: Add Category This Blade puts the button in the `action` slot, shows it only to users with the `categories.create` permission, and opens the `shopper-slide-overs.category-form` slide-over on click: ```blade @can('categories.create') Add Category @endcan ``` ### Heading with Multiple Actions [#heading-with-multiple-actions] Wrap several buttons in a flex container. The methods called here, `export` and `create`, belong to your Livewire component:
    Export New Gift Card
    This Blade puts the two buttons in the `action` slot, inside a `div` that lines them up with a gap: ```blade
    Export New Gift Card
    ``` ### Custom Title Slot [#custom-title-slot] Pass a `title` slot to show more than text, like a badge above the title. The slot replaces the `h2`, so add it yourself with the same classes. The product edit page does this to show the product type: ```blade
    Published

    Leather Weekender Bag

    Unpublish
    ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/heading.blade.php` in the `shopper/framework` package: ```blade @blaze @props([ 'title' => null, ])
    twMerge(['class' => 'space-y-3 sm:flex sm:items-center sm:justify-between sm:space-x-4 sm:space-y-0']) }} > @if ($title instanceof \Illuminate\View\ComponentSlot) {{ $title }} @else

    {{ $title }}

    @endif @isset($action) {{ $action }} @endisset
    ``` # Label (/3.x/extending/components/label) The label renders a `label` element with the admin panel's field label styles, and an optional red asterisk for required fields. Use it with your own inputs; Filament fields render their own labels. ## Preview [#preview] The preview shows an optional field and a required one.
    ## Usage [#usage] Pass the text to `value` and the input id to `for`: ```blade ``` ## Props [#props] Both props are optional. Other attributes, like `for`, go to the `label` element. The text of the label. Without it, the label prints its slot. Shows a red asterisk after the text. ## Examples [#examples] The examples below show a required field, the slot and a full field. ### Basic Label [#basic-label] A label with a text. This Blade sets the text with `value` and ties the label to the `supplier` field with `for`, so a click on the label focuses the field: ```blade ``` ### Required Field [#required-field] Set `isRequired` to add the asterisk. This Blade sets `isRequired` on the label of the email field: ```blade ``` ### Using Slot [#using-slot] Put the text in the slot when it holds markup or a translation: ```blade {{ __('Price') }} ``` ### With Form Input [#with-form-input] Pair the label with `x-shopper::forms.input`, which has the admin panel's input styles: ```blade
    ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/label.blade.php` in the `shopper/framework` package: ```blade @blaze @props([ 'value', 'isRequired' => false, ]) ``` # Loader (/3.x/extending/components/loader) The loader is a spinning SVG for loading states. Shopper's forms place it in their save button, where it shows while Livewire runs the save method. ## Preview [#preview] The preview shows the loader at its default size. ## Usage [#usage] The loader takes no prop. Add Livewire's `wire:loading` and `wire:target` attributes to show it only while a method runs: ```blade ``` ## Attributes [#attributes] Every attribute goes to the `svg` element. The `class` attribute is merged with the default classes, so a size you pass replaces the default one. Classes for the size and the color. The spinner is drawn with `currentColor`, so a text color class sets its color. ## Examples [#examples] The examples below change the size and the color, and place the loader in a button and a page. ### Different Sizes [#different-sizes] Pass a `size-*` class.
    This Blade renders the three loaders, from `size-4` (16 pixels) to `size-6` (24 pixels): ```blade ``` ### With Color [#with-color] Pass a text color class. The theme tokens follow dark mode: ```blade ``` ### In a Button [#in-a-button] Shopper's settings forms show the loader in the submit button while the `store` method runs, and disable the button meanwhile: ```blade Save ``` ### Loading State [#loading-state] Center a larger loader in an area while its content loads: ```blade
    ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/loader.blade.php` in the `shopper/framework` package: ```blade @blaze(memo: true) twMerge(['class' => 'size-5 animate-spin']) }} fill="none" viewBox="0 0 24 24" aria-hidden="true" > ``` # Overview (/3.x/extending/components/overview) Shopper ships Blade components for the views of the admin panel and Filament fields and columns for its forms and tables. Use them in the pages, slide-overs and add-ons you build: your screens then look like the rest of the admin panel and follow the active theme, in light and dark mode. ## Available Components [#available-components] Each page shows a component, its props and slots, and the view Shopper renders for it. Container with an optional title, description and footer. Colored message box for information, success, warnings and errors. Page title with an action slot for buttons. Section title with an optional description. Illustration, message and call to action for a list with no records. Compact empty state for a card or a panel. Stock quantity in red below 10 units, in green from 10. Spinning indicator for loading states. Form field label with a required marker. Container, link, separator, breadcrumb, validation errors, dropdown link and form slide-over. Filament fields and table columns from the `Shopper\Components` namespace. ## Usage [#usage] Blade components take the `x-shopper::` prefix and work in any view rendered inside the admin panel: ```blade ``` Each component is an anonymous Blade component: `x-shopper::card` renders the view `shopper::components.card`, the file `resources/views/components/card.blade.php` of the `shopper/framework` package. A dot in the name is a folder, so `x-shopper::breadcrumb.link` renders `components/breadcrumb/link.blade.php`. The Filament components are PHP classes, used in the `form()` or `table()` method of a Livewire component like any Filament field or column. [Filament Components](/3.x/extending/components/filament) lists them. ## Styling [#styling] The components read their colors from the active theme. Their views use Tailwind classes built on Shopper's design tokens: `bg-sh-surface`, `bg-sh-card`, `bg-sh-muted`, `text-sh-fg`, `text-sh-fg-secondary`, `text-sh-fg-muted`, `ring-sh-border` and the other `sh-*` colors, plus the `primary-50` to `primary-950` ramp. Each token reads a CSS custom property of the theme (`--color-sh-surface` reads `--theme-sh-surface`), and each theme sets these properties for light and dark mode, as described in [How a Theme Works](/3.x/themes#how-a-theme-works). Use the same classes in your own markup and it follows the theme and dark mode without `dark:` variants. Shopper's stylesheet is compiled from Shopper's own views, so it only holds the classes those views use. A class that only appears in your views is missing from it. Compile a stylesheet for your views with Tailwind CSS and map the tokens to the theme properties, as Shopper and its add-ons do: ```css title="resources/css/admin.css" @layer theme, base, components, utilities; @import 'tailwindcss/theme.css' layer(theme); @import 'tailwindcss/utilities.css' layer(utilities); @source '../views'; @variant dark (&:where(.dark, .dark *)); @theme inline { --color-sh-header: var(--theme-sh-header); --color-sh-header-border: var(--theme-sh-header-border); --color-sh-header-fg: var(--theme-sh-header-fg); --color-sh-header-fg-muted: var(--theme-sh-header-fg-muted); --color-sh-header-hover: var(--theme-sh-header-hover); --color-sh-body: var(--theme-sh-body); --color-sh-sidebar: var(--theme-sh-sidebar); --color-sh-sidebar-hover: var(--theme-sh-sidebar-hover); --color-sh-sidebar-active: var(--theme-sh-sidebar-active, var(--theme-sh-sidebar-hover)); --color-sh-settings-sidebar-hover: var(--theme-sh-settings-sidebar-hover, var(--theme-sh-sidebar-hover)); --color-sh-surface: var(--theme-sh-surface); --color-sh-muted: var(--theme-sh-muted); --color-sh-muted-strong: var(--theme-sh-muted-strong); --color-sh-border: var(--theme-sh-border); --color-sh-fg: var(--theme-sh-fg); --color-sh-fg-secondary: var(--theme-sh-fg-secondary); --color-sh-fg-muted: var(--theme-sh-fg-muted); --color-sh-accent: var(--theme-sh-accent); --color-sh-accent-fg: var(--theme-sh-accent-fg); --color-sh-card: var(--theme-sh-card); --color-sh-table-header: var(--theme-sh-table-header); --color-sh-skeleton: var(--theme-sh-skeleton); --color-primary-50: var(--primary-50); --color-primary-100: var(--primary-100); --color-primary-200: var(--primary-200); --color-primary-300: var(--primary-300); --color-primary-400: var(--primary-400); --color-primary-500: var(--primary-500); --color-primary-600: var(--primary-600); --color-primary-700: var(--primary-700); --color-primary-800: var(--primary-800); --color-primary-900: var(--primary-900); --color-primary-950: var(--primary-950); } ``` The stylesheet leaves out Tailwind's preflight, which the admin panel already loads. Compile it with the Tailwind CLI: ```bash npx @tailwindcss/cli -i resources/css/admin.css -o public/css/admin.css --minify ``` Then load the output on the admin pages: an application registers it with `Shopper::styles()`, as shown in [Adding CSS and JS Assets](/3.x/extending/control-panel#adding-css-and-js-assets), and an add-on with `addonStyles()`, as shown in [Styles and Scripts](/3.x/addons/admin-panel#styles-and-scripts). ## Customization [#customization] Most components pass the attributes you give them to their root element. The `class` attribute goes through `twMerge()`, so a class you pass replaces the default class it conflicts with: `` replaces the card's `p-0.5`. Named slots, like the `action` slot of the heading, take your own markup. To change the markup of a component everywhere in the admin panel, override its view. Shopper has no publish tag for its views: copy the view from the package to the same path under `resources/views/vendor/shopper` in your application. Laravel looks in that folder before the package's views: ```bash mkdir -p resources/views/vendor/shopper/components cp vendor/shopper/framework/resources/views/components/card.blade.php resources/views/vendor/shopper/components/card.blade.php ``` A nested component keeps its folder: `breadcrumb/link.blade.php` goes to `resources/views/vendor/shopper/components/breadcrumb/link.blade.php`. Several views start with a `@blaze` directive, sometimes with options like `@blaze(memo: true)`: it lets Blaze compile the component ahead of rendering. Keep it in your copy. Run `php artisan view:clear` after adding or removing an override, so that views compiled before it pick up the change. A copied view no longer gets the changes Shopper makes to that component in later releases. Keep the props and slots of the original: Shopper's own views pass them. # Section Heading (/3.x/extending/components/section-heading) The section heading introduces a section inside a page: a title, and an optional description that explains what the section holds. The [card](/3.x/extending/components/card) renders one for its title. ## Preview [#preview] The preview shows a title with a description. ## Usage [#usage] Pass the title and the description as attributes: ```blade ``` The title and description are rendered with Filament's section heading and description components, so they match the headings of Filament sections in the same page. ## Props [#props] The title is required. Other attributes go to the wrapping `div`. The section title. Text displayed below the title. ## Examples [#examples] The examples below show the component alone, with a description, and inside a card. ### Title Only [#title-only] Leave out the description for a short title. This Blade passes the `title` only: ```blade ``` ### With Description [#with-description] The description is limited to a readable line length. This Blade adds the `description` under the `title`: ```blade ``` ### Inside a Card [#inside-a-card] The card uses the section heading when you pass it a `title` string, and forwards its `description`:
    No media yet
    This Blade passes the `title` and the `description` to the card, and puts an [empty card](/3.x/extending/components/empty-card) in it: ```blade ``` ### Standalone Usage [#standalone-usage] Use the section heading on its own to split a long form into parts: ```blade
    ``` ## Blade Component Source [#blade-component-source] The view is `resources/views/components/section-heading.blade.php` in the `shopper/framework` package: ```blade @blaze @props([ 'title', 'description' => null, ])
    {{ $title }} @if ($description) {{ $description }} @endif
    ``` # Stock Badge (/3.x/extending/components/stock-badge) The stock badge shows a stock quantity in a small rounded badge, colored by level. The products table uses it in its stock column. ## Preview [#preview] The preview shows a low quantity and two normal ones.
    ## Usage [#usage] Pass the quantity to the `stock` prop: ```blade ``` ## Props [#props] The badge takes a single prop and no slot. It ignores other attributes. The quantity to display. ## Behavior [#behavior] The color depends on the quantity. The threshold of 10 units is fixed in the view: to change it, [override the view](/3.x/extending/components/overview#customization). | Stock value | Color | Meaning | |------------|-------|---------| | `< 10` | Red (`danger`) | Low stock | | `>= 10` | Green (`success`) | Stock OK | ## Examples [#examples] The examples below show both colors and the badge in a table column. ### Low Stock [#low-stock] A quantity under 10 renders red. This Blade passes a stock of 3: ```blade ``` ### Normal Stock [#normal-stock] A quantity of 10 or more renders green. This Blade passes a stock of 50: ```blade ``` ### In a Table [#in-a-table] In a Filament table, render the badge from a `ViewColumn`. This column renders the `stock` cell of each row with a Blade view: ```php use Filament\Tables\Columns\ViewColumn; ViewColumn::make('stock') ->label('Stock') ->view('livewire.tables.cells.stock') ``` The view reads the product of the row through `$getRecord()` and shows its stock in the badge, followed by "in stock": ```blade title="resources/views/livewire/tables/cells/stock.blade.php" @php $product = $getRecord(); @endphp
    in stock
    ``` Shopper's products table renders its stock column the same way, with the view `shopper::livewire.tables.cells.products.stock`. ## Blade Component Source [#blade-component-source] The view is `resources/views/components/stock-badge.blade.php` in the `shopper/framework` package: ```blade @blaze(memo: true) @props([ 'stock', ]) $stock < 10, 'bg-success-100 text-success-800' => $stock >= 10, ]) > {{ $stock }} ``` # Utility Components (/3.x/extending/components/utilities) These components structure a page or a form more than they display content, so they have no preview. Each one takes the classes you pass, merged with its own unless noted otherwise. ## Container [#container] The container adds the horizontal padding of the admin pages, `px-4` on small screens and `px-6` from `lg`. The product pages wrap their sections in it: ```blade {{ $this->form }} ``` The view: ```blade @blaze
    twMerge(['class' => 'px-4 lg:px-6']) }}> {{ $slot }}
    ``` ## Link [#link] The link is an `a` element with Livewire's `wire:navigate.hover`: Livewire prefetches the page when the pointer rests on the link, then swaps the page without a full reload. Use it for links between admin pages. ```blade Products ``` The view passes every attribute through, without default classes: ```blade @blaze {{ $slot }} ``` ## Separator [#separator] The separator draws a horizontal line between two sections of a page, with vertical spacing around it. The account page and the inventory section of a product use it. ```blade ``` It takes no attribute: ```blade
    ``` ## Breadcrumb [#breadcrumb] The breadcrumb renders a trail for a page: a back link on small screens, and from `sm` a dashboard icon, the links of its slot and the current page. The admin header already shows breadcrumbs built from the sidebar and from the crumbs a page declares, as shown in [Settings Items](/3.x/addons/admin-panel#settings-items), so use this component only for a page that renders its own trail. ```blade ``` ### Props [#props] The back URL is required. Other attributes go to the wrapping `div`. URL of the back link shown below `sm` Title of the current page, shown last ### Breadcrumb Link [#breadcrumb-link] A link of the trail. The `link` prop sets the URL and the `title` prop sets the text. It renders an `x-shopper::link`, so it uses `wire:navigate.hover` too. ```blade ``` ## Validation Errors [#validation-errors] The validation errors box lists every message of the `$errors` bag in a red panel, under the heading "Your submission contains errors. Please try again". Filament forms show their errors under each field, so use it for a form you build yourself: ```blade
    ``` The view renders nothing when the bag is empty: ```blade @if ($errors->count() > 0)

    {{ __('shopper::forms.error') }}

      @foreach ($errors->all() as $message)
    • {{ $message }}
    • @endforeach
    @endif ``` ## Dropdown Link [#dropdown-link] The dropdown link is a menu item, styled for dropdowns like the account menu at the top of the admin panel. It renders an `x-shopper::link`, so it takes an `href`. ```blade Profile ``` ## Form Slide-over [#form-slide-over] The form slide-over is the layout of every form slide-over in the admin panel: a header with the title, the description and a close button, a scrolling body, and a footer with a Cancel and a Save button. Shopper's slide-overs render it from the view `shopper::livewire.slide-overs.form`: ```blade {{ $this->form }} ``` A slide-over that uses the `Shopper\Traits\InteractsWithSlideOverForm` trait gets these three methods, which read its `$action`, `$title` and `$description` properties, and renders that view. In your own view, pass the values directly: ```blade {{ $this->form }} ``` ### Props [#props-1] The action and the title are required. Livewire method called when the form is submitted Title of the slide-over Text below the title ### Slots [#slots] The component has a single slot. The form content, usually `{{ $this->form }}` The footer is fixed: a Cancel button that dispatches `closePanel`, and a Save button that submits the form and shows a [loader](/3.x/extending/components/loader) while the action runs. For other buttons, write the slide-over's markup yourself. # Control Panel (/3.x/extending/control-panel) The control panel may be customized in a number of different ways. You may add new pages, menus, a stylesheet, or maybe you just want to add some arbitrary JavaScript. ## Adding CSS and JS Assets [#adding-css-and-js-assets] `Shopper::styles()` adds stylesheets to the `` of every admin page, after Shopper's stylesheet and the theme. `Shopper::scripts()` adds scripts at the end of the ``, after Filament's scripts. Call them from the `boot()` method of a service provider. Each call adds to the files already registered and returns the panel, so the calls chain: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; public function boot(): void { Shopper::styles([ 'css/admin.css', 'https://cdn.example.com/library.min.css', ])->scripts([ 'https://cdn.example.com/library.min.js', 'js/admin.js', ]); } ``` A value that starts with `http://` or `https://` is used as is. Any other value goes through `asset()`, so it is a path under the `public` directory of your application. The files load on every admin page, sign-in pages included, so scope your CSS to your own markup. Add-ons register their files with `addonStyles()` and `addonScripts()`, as described in [Styles and Scripts](/3.x/addons/admin-panel#styles-and-scripts). The admin panel outputs your files first, then those of the add-ons. ## Customize Shopper theme [#customize-shopper-theme] The admin panel ships with a compiled stylesheet and three color themes: Default, Midnight and Evergreen. The `` element of every admin page carries a `data-theme` attribute set to the ID of the active theme, and each theme sets the `--theme-sh-*` color variables for its ID. [Themes](/3.x/themes) covers how a store picks the active theme and how to add a color theme in `config/shopper/themes.php`. To change more than the colors, replace the compiled stylesheet. Call one of these methods on the `Shopper` facade from the `boot()` method of a service provider: | Method | Stylesheet | |--------|------------| | `registerViteTheme(string\|array $theme, ?string $buildDirectory = null)` | One or more Vite entries of your application, built with Tailwind CSS from Shopper's sources. The next sections set it up. | | `registerTheme(string\|Htmlable\|null $theme)` | A stylesheet you build some other way. Pass its URL, or the HTML of a `` tag when it needs more attributes. | When both are set, the Vite theme wins. Without either, the admin panel loads its compiled stylesheet. The CSS of the active color theme, when its configuration sets one, loads after the stylesheet in all three cases. ### Setting up Tailwind CSS for your project [#setting-up-tailwind-css-for-your-project] Install Tailwind CSS with its Vite plugin, and the forms and typography plugins that Shopper's styles use: ```bash npm install -D tailwindcss @tailwindcss/vite @tailwindcss/forms @tailwindcss/typography ``` Add the `@tailwindcss/vite` plugin to your `vite.config.js` file, and add the theme file you create in the next section to the inputs of the Laravel plugin: ```js title="vite.config.js" import tailwindcss from '@tailwindcss/vite'; import laravel from 'laravel-vite-plugin'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ tailwindcss(), laravel({ input: [ 'resources/css/app.css', 'resources/js/app.js', 'resources/css/shopper.css', ], refresh: true, }), ], }); ``` ### Creating the theme file [#creating-the-theme-file] Create a `resources/css/shopper.css` file that imports Shopper's `theme.css` entry point. This file imports Tailwind CSS, Filament's styles, Shopper's base styles and components, and the forms and typography plugins. It also declares the `@source` paths of the Blade views that Shopper, Filament and the slide-over panels render. `theme.css` does not import the three color themes, which the compiled stylesheet includes. Import them after it, so that the `data-theme` attribute of the page finds its colors: ```css title="resources/css/shopper.css" @import '../../vendor/shopper/framework/resources/css/theme.css'; @import '../../vendor/shopper/framework/resources/css/themes/default.css'; @import '../../vendor/shopper/framework/resources/css/themes/midnight.css'; @import '../../vendor/shopper/framework/resources/css/themes/evergreen.css'; @source '../../resources/views/**/*.blade.php'; ``` The last line adds your own views to the sources that Tailwind CSS scans, so the classes of your admin pages and components are compiled too. Add one `@source` line per folder of views, such as the views of a module, and write your own styles after them. ### Load theme [#load-theme] Register the theme file in the `boot()` method of your `AppServiceProvider` or of any other service provider: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; public function boot(): void { Shopper::registerViteTheme('resources/css/shopper.css'); } ``` The admin panel then loads the file through Laravel's `@vite` helper: from the Vite development server while `npm run dev` runs, and from the build manifest otherwise. When your build writes to a directory other than `public/build`, pass that directory as the second argument. ### Branding Logo [#branding-logo] By default, the Shopper logo is shown on the sign-in pages, in the top bar of the admin panel and on the store setup screen. You have two options to replace it with your own brand. #### Via configuration [#via-configuration] The simplest approach is to set the `brand` key of your `config/shopper/admin.php` file to the path of your logo: ```php title="config/shopper/admin.php" 'brand' => 'images/logo.svg', ``` Shopper loads the image with the `asset()` helper, so the file belongs in your `public` directory. The `favicon` key of the same file sets the favicon: its value is output as is in the `href` of the icon link, so give it a URL or an absolute path such as `/favicon.svg`. The logo then shows in the top bar, next to the name of the store: #### Via service provider [#via-service-provider] For more control, call `brandLogo()` on the `Shopper` facade. It takes an HTML string, or a closure that returns an HTML string or a view: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Contracts\View\View; use Shopper\Facades\Shopper; public function boot(): void { Shopper::brandLogo(fn (): View => view('brand.logo')); } ``` The closure runs each time the logo renders, so it can render an inline SVG, a Blade component with `Blade::render('')`, or a logo that depends on the current store. A plain string such as `'Acme Store'` is output as is. The priority order is: `Shopper::brandLogo()`, then `config('shopper.admin.brand')`, then the default Shopper logo. ## Render hooks [#render-hooks] Render hooks add HTML at named places of the admin panel, such as the end of the ``, the start of the `` or the sidebar of an order. They are the way to set up a package that needs its own Blade markup in the layout, such as [Flux UI](https://fluxui.dev), [Wire Elements Modal](https://github.com/wire-elements/modal) or [Laravel Notify](https://github.com/mckenziearts/laravel-notify). [Render Hooks](/3.x/render-hooks) lists every hook and shows how to register one. ## Adding control panel routes [#adding-control-panel-routes] Your `routes/web.php` file is not loaded inside the admin panel. To add routes that share its login, its middleware and its URL prefix, give the admin panel a route file of its own: Create a route file. Name it whatever you want, for example `routes/shopper.php`. Point the `custom_file` key of `config/shopper/routes.php` to it, so that its routes are loaded with the admin panel: ```php title="config/shopper/routes.php" 'custom_file' => base_path('routes/shopper.php'), ``` Shopper loads the file after its own routes, under the admin panel prefix, and adds `shopper.` to the name of each route: a route named `gift-cards.index` is called with `route('shopper.gift-cards.index')`. Restrict a route to the users who hold a permission with Laravel's `can` middleware: ```php title="routes/shopper.php" use App\Livewire\Shopper\GiftCards\GiftCardIndex; use Illuminate\Support\Facades\Route; Route::middleware('can:gift-cards.browse')->group(function (): void { Route::livewire('/gift-cards', GiftCardIndex::class)->name('gift-cards.index'); }); ``` [Generating Permissions](/3.x/acl#generating-permissions) shows how to create the `gift-cards.*` permissions. The `middleware` key of the same file adds middleware to every route behind the admin login, Shopper's routes included, as described in [Middleware](/3.x/configuration#middleware): ```php title="config/shopper/routes.php" 'middleware' => [ 'log-admin-activity', ], ``` [Controllers](/3.x/extending/controllers) shows how to build the pages these routes serve. # Controllers (/3.x/extending/controllers) You can add custom pages to the Shopper admin panel using either traditional Laravel controllers or Livewire components. Both approaches share the same authentication middleware and can be integrated into the admin sidebar navigation. ## Custom Routes [#custom-routes] To add custom routes inside the admin panel, set the `custom_file` key in `config/shopper/routes.php` to point to a dedicated route file: ```php title="config/shopper/routes.php" 'custom_file' => base_path('routes/shopper.php'), ``` Routes defined in this file are loaded with the admin panel's middleware stack (authentication, the admin access check and the middleware of your configuration), under the admin URL prefix. Shopper also prefixes their names with `shopper.`, so a route you name `posts.index` is called with `route('shopper.posts.index')`. The admin middleware does not check any permission: restrict a group of routes with the `can` middleware, as shown in [Adding control panel routes](/3.x/extending/control-panel#adding-control-panel-routes), or check the permission in the page itself. ## Using Controllers [#using-controllers] You can use standard Laravel controllers with Shopper. Create a controller in any namespace you prefer: ```bash php artisan make:controller Shopper/PostController ``` This creates a controller in `app/Http/Controllers/Shopper/PostController.php`: ```php title="app/Http/Controllers/Shopper/PostController.php" namespace App\Http\Controllers\Shopper; use App\Http\Controllers\Controller; use App\Models\Post; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class PostController extends Controller { public function index(): View { $posts = Post::query()->latest()->paginate(20); return view('shopper.posts.index', compact('posts')); } public function create(): View { return view('shopper.posts.create'); } public function store(Request $request): RedirectResponse { $validated = $request->validate([ 'title' => ['required', 'string', 'max:255'], 'content' => ['required', 'string'], ]); Post::query()->create($validated); return redirect()->route('shopper.posts.index'); } } ``` Register the routes in your custom route file: ```php title="routes/shopper.php" use App\Http\Controllers\Shopper\PostController; use Illuminate\Support\Facades\Route; Route::middleware('can:posts.browse')->group(function (): void { Route::get('/posts', [PostController::class, 'index'])->name('posts.index'); }); Route::middleware('can:posts.create')->group(function (): void { Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create'); Route::post('/posts', [PostController::class, 'store'])->name('posts.store'); }); ``` The views of a controller render inside the admin layout when they use the `x-shopper::layouts.app` component, which adds the header, the sidebar and the notifications around the page: ```blade title="resources/views/shopper/posts/index.blade.php"
      @foreach ($posts as $post)
    • {{ $post->title }}
    • @endforeach
    {{ $posts->links() }}
    ``` The page renders between the top bar and the sidebar of the admin panel: The admin panel loads its own compiled stylesheet, which holds only the Tailwind CSS classes of Shopper's views. To use other classes in your views, build a theme of your own as described in [Customize Shopper theme](/3.x/extending/control-panel#customize-shopper-theme). ## Using Livewire Components [#using-livewire-components] Livewire is the recommended approach since the entire Shopper admin is built with Livewire. The `pages` configuration in `config/shopper/admin.php` sets the namespace and view path used by the `make:shopper-page` command: ```php title="config/shopper/admin.php" 'pages' => [ 'namespace' => 'App\\Livewire\\Shopper', 'view_path' => resource_path('views/livewire/shopper'), ], ``` Create a page component: ```bash php artisan make:shopper-page PostIndex ``` The command creates the class and its view. The class extends `Shopper\Livewire\Pages\AbstractPageComponent`, which renders the page inside the admin panel layout: ```php title="app/Livewire/Shopper/PostIndex.php" namespace App\Livewire\Shopper; use Illuminate\Contracts\View\View; use Shopper\Livewire\Pages\AbstractPageComponent; class PostIndex extends AbstractPageComponent { public function render(): View { return view('livewire.shopper.post-index'); } } ``` The view is written to `resources/views/livewire/shopper/post-index.blade.php`, so `render()` returns `livewire.shopper.post-index`. Check that the generated `render()` method names this view, and change it if it names another. Register Livewire routes in your custom route file: ```php title="routes/shopper.php" use App\Livewire\Shopper\PostIndex; use Illuminate\Support\Facades\Route; Route::livewire('/posts', PostIndex::class)->name('posts.index'); ``` If your component extends `Livewire\Component` instead, add `#[Layout('shopper::components.layouts.app')]` to the class to inherit the admin panel layout with sidebar, header, and notification system. ### The make:shopper-page Command [#make-shopper-page] `make:shopper-page` also answers to `shopper:page`. Without a name, it asks for one. A name with slashes creates the page in a subfolder: `php artisan make:shopper-page Blog/PostIndex` creates `App\Livewire\Shopper\Blog\PostIndex` and the view `resources/views/livewire/shopper/blog/post-index.blade.php`. The view starts as an `x-shopper::container` component that holds a comment with an inspiring quote. When the class or the view already exists, the command reports it and leaves the file as it is. Pass `--force`, or `-f`, to overwrite both files. ## Breadcrumbs [#breadcrumbs] The header of the admin panel shows a breadcrumb trail. It starts with the active entry of the sidebar: an entry that links to `/cpanel/posts` stays active on every URL below it, such as `/cpanel/posts/12/edit`. A page adds its own crumbs after it with the `Shopper\Sidebar\Traits\WithBreadcrumbs` trait. Return them from `getBreadcrumbs()`: ```php title="app/Livewire/Shopper/PostEdit.php" namespace App\Livewire\Shopper; use App\Models\Post; use Illuminate\Contracts\View\View; use Livewire\Attributes\Locked; use Shopper\Livewire\Pages\AbstractPageComponent; use Shopper\Sidebar\Breadcrumbs\Breadcrumb; use Shopper\Sidebar\Traits\WithBreadcrumbs; class PostEdit extends AbstractPageComponent { use WithBreadcrumbs; #[Locked] public Post $post; public function mount(): void { $this->authorize('posts.edit'); } public function getBreadcrumbs(): array { return [ new Breadcrumb(text: $this->post->title), ]; } public function render(): View { return view('livewire.shopper.post-edit'); } } ``` Livewire fills `$post` from the `{post}` parameter of the route, `Route::livewire('/posts/{post}/edit', PostEdit::class)->name('posts.edit')`. The trait pushes the crumbs after `mount()` runs, so `getBreadcrumbs()` can read the properties that `mount()` sets. On this page, the trail reads **Posts** then the title of the post. A `Breadcrumb` takes a `text`, and optionally a `url`, an `icon` and a list of links for a dropdown. [Adding Page Breadcrumbs](/3.x/sidebar/standalone#adding-page-breadcrumbs) describes these arguments, and [Breadcrumb Registry](/3.x/sidebar/standalone#breadcrumb-registry) shows how to push crumbs from a controller. [Breadcrumbs](/3.x/sidebar/standalone#breadcrumbs) explains how the trail is built. ## Adding Navigation [#adding-navigation] To add your custom page to the admin sidebar, create a sidebar extension. See the [Navigation](/3.x/extending/navigation) page for details on adding menu items that link to your controller or Livewire routes. ## Authorization Pattern for Custom Admin Components [#authorization-pattern-for-custom-admin-components] Custom Livewire components that extend or mimic Shopper's admin surfaces (orders, products, customers, settings) follow the authorization pattern of Shopper's own components. Each rule below keeps a permission check tied to the action and the record it protects. To show a notification instead of an error page when a check fails, add the `Shopper\Traits\HandlesAuthorizationExceptions` trait to the component. A check that fails in `mount()` still sends the user to the forbidden page of the admin panel, and a check that fails in a later action shows an "Unauthorized" notification. ### Chain `authorize()` on Filament Actions [#chain-authorize-on-filament-actions] Declare the required ability on the Filament `Action` itself, not inside the closure. This hides the button when the user lacks the ability instead of throwing a 403 on click: ```php title="app/Livewire/Shopper/OrderFulfillment.php" use Filament\Actions\Action; use Shopper\Core\Enum\OrderStatus; public function cancelAction(): Action { return Action::make('cancel') ->authorize('orders.edit') ->requiresConfirmation() ->action(function (): void { $this->order->transitionTo(OrderStatus::Cancelled); }); } ``` ### Authorize Livewire Method Handlers [#authorize-livewire-method-handlers] Every public Livewire method that mutates state must call `$this->authorize()` on its first line. A public method can be called from the browser even when the button that calls it is hidden, so the check belongs in the method body, not in the view that rendered the trigger: ```php title="app/Livewire/Shopper/OrderFulfillment.php" public function leaveNotes(): void { $this->authorize('orders.edit'); $this->validate(); $this->order->update(['notes' => $this->notes]); } ``` ### Lock Public Model Properties [#lock-public-model-properties] Any `public Model $x` property on a Livewire component must be marked `#[Locked]`. The browser cannot change a locked property, so the component keeps acting on the record that its checks were made for: ```php title="app/Livewire/Shopper/OrderFulfillment.php" use Livewire\Attributes\Locked; use Shopper\Core\Models\Order; #[Locked] public Order $order; ``` ### Allow-List User Input [#allow-list-user-input] When persisting user input from the browser, use an explicit `Arr::only(...)` allow-list. With `Arr::except(...)`, any new field that lands in the payload is saved too, where an allow-list saves only the fields you name: ```php title="app/Livewire/Shopper/GiftCardEdit.php" use Illuminate\Support\Arr; public function save(): void { $this->authorize('gift-cards.edit'); $this->giftCard->update(Arr::only($this->form->getState(), [ 'amount', 'expires_at', 'is_enabled', ])); } ``` ### Guard Lookups Against Null [#guard-lookups-against-null] Livewire components that resolve a model from user input must handle the lookup failure path. Return early when the lookup finds nothing, so the rest of the method runs only on a record that exists. On a role page, granting a permission by its ID looks like this: ```php title="app/Livewire/Shopper/RolePermissions.php" use Shopper\Models\Permission; public function grantPermission(int $permissionId): void { $this->authorize('system.settings'); $permission = Permission::query()->find($permissionId); if ($permission === null) { return; } $this->role->givePermissionTo($permission->name); } ``` # Forms (/3.x/extending/forms) The forms of the admin panel are Filament schemas rendered by Livewire components. Your own pages build theirs the same way, with Filament's fields and the components Shopper adds, so they look and behave like the product or customer forms. This page builds a form on an admin page. [Slide-overs](/3.x/extending/slideover) shows the same form in a side panel. ## Form in an Admin Page [#form-in-an-admin-page] The page below issues gift cards. It follows the layout of Shopper's create pages: a section with its title and description on the left and the fields on the right, then a save button at the bottom: ```php title="app/Livewire/Shopper/GiftCards/CreateGiftCard.php" namespace App\Livewire\Shopper\GiftCards; use App\Models\GiftCard; use Filament\Actions\Concerns\InteractsWithActions; use Filament\Actions\Contracts\HasActions; use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Notifications\Notification; use Filament\Schemas\Concerns\InteractsWithSchemas; use Filament\Schemas\Contracts\HasSchemas; use Filament\Schemas\Schema; use Illuminate\Contracts\View\View; use Illuminate\Support\Arr; use Illuminate\Validation\ValidationException; use Shopper\Components\Form\MoneyInput; use Shopper\Components\Section; use Shopper\Livewire\Pages\AbstractPageComponent; use Shopper\Traits\HandlesAuthorizationExceptions; class CreateGiftCard extends AbstractPageComponent implements HasActions, HasSchemas { use HandlesAuthorizationExceptions; use InteractsWithActions; use InteractsWithSchemas; public ?array $data = []; public function mount(): void { $this->authorize('gift-cards.create'); $this->form->fill(); } public function form(Schema $schema): Schema { return $schema ->components([ Section::make(__('Gift card')) ->aside() ->compact() ->columns() ->description(__('The code customers enter at checkout and the amount it holds.')) ->extraAttributes(['class' => 'sh-section-aside']) ->schema([ TextInput::make('code') ->label(__('Code')) ->required() ->maxLength(32) ->unique(GiftCard::class, 'code'), MoneyInput::make('amount') ->label(__('Amount')) ->currency(shopper_currency()) ->amountRules() ->required(), DatePicker::make('expires_at') ->label(__('Expires on')) ->minDate(now()), Toggle::make('is_enabled') ->label(__('Enabled')) ->default(true), ]), ]) ->statePath('data') ->model(GiftCard::class); } public function store(): void { $this->authorize('gift-cards.create'); $giftCard = GiftCard::query()->create([ ...Arr::only($this->form->getState(), ['code', 'amount', 'expires_at', 'is_enabled']), 'currency_code' => shopper_currency(), ]); Notification::make() ->title(__('Gift card :code issued', ['code' => $giftCard->code])) ->success() ->send(); $this->redirectRoute(name: 'shopper.gift-cards.index', navigate: true); } protected function onValidationError(ValidationException $exception): void { Notification::make() ->title($exception->getMessage()) ->danger() ->send(); } public function render(): View { return view('livewire.shopper.gift-cards.create-gift-card') ->title(__('Issue a gift card')); } } ``` The parts that come from Shopper: | Part | Role | |------|------| | `AbstractPageComponent` | Renders the page in the admin layout. `title()` on the view sets the title of the browser tab. | | `HandlesAuthorizationExceptions` | Shows a notification instead of an error page when a permission check fails after the page has loaded. | | `Shopper\Components\Section` | A Filament section with the styles of the admin panel. `aside()` with the `sh-section-aside` class places the title and the description next to the fields. | | `MoneyInput` | Shows the amount as a decimal and saves it as cents, as described in [Admin Forms and Tables](/3.x/money#admin-forms-and-tables). | | `onValidationError()` | Filament calls it when `getState()` fails validation. Shopper's pages show the error in a notification as well as under the field. | `statePath('data')` keeps the values of the form in the `$data` property, and `model()` tells the fields which model the form creates, which relationship fields need. [Filament Components](/3.x/extending/components/filament) lists the other fields Shopper adds, such as the phone, country and slug inputs. The view renders the form and its save button: ```blade title="resources/views/livewire/shopper/gift-cards/create-gift-card.blade.php"
    {{ $this->form }}
    {{ __('shopper::forms.actions.save') }}
    ``` Register the page in your [custom route file](/3.x/extending/controllers#custom-routes): ```php title="routes/shopper.php" use App\Livewire\Shopper\GiftCards\CreateGiftCard; use Illuminate\Support\Facades\Route; Route::livewire('/gift-cards/create', CreateGiftCard::class)->name('gift-cards.create'); ``` The page shows the title and the description of the section next to its fields: ## Forms in a Modal [#forms-in-a-modal] Shopper has no modal class of its own: its pages open a short form in the modal of a Filament action. The action below, on the page of a gift card, changes its expiry date: ```php title="app/Livewire/Shopper/GiftCards/EditGiftCard.php" use Filament\Actions\Action; use Filament\Forms\Components\DatePicker; use Filament\Notifications\Notification; use Filament\Support\Enums\Width; public function extendAction(): Action { return Action::make('extend') ->authorize('gift-cards.edit') ->label(__('Extend')) ->color('gray') ->modalHeading(__('Extend the gift card')) ->modalWidth(Width::Large) ->fillForm(fn (): array => ['expires_at' => $this->giftCard->expires_at]) ->schema([ DatePicker::make('expires_at') ->label(__('Expires on')) ->required() ->minDate(now()), ]) ->action(function (array $data): void { $this->giftCard->update(['expires_at' => $data['expires_at']]); Notification::make() ->title(__('Gift card extended')) ->success() ->send(); }); } ``` The page implements `HasActions` and uses `InteractsWithActions`, like the page above. Its view renders the button and the modals of the page inside a single root element, which Livewire requires: ```blade title="resources/views/livewire/shopper/gift-cards/edit-gift-card.blade.php"
    {{ $this->extendAction }}
    ``` The **Extend** button of the heading opens the modal: An action without a schema and with `requiresConfirmation()` asks for confirmation only, as the order actions of Shopper do. `slideOver()` opens the form in a Filament side panel instead of a modal; for a form of its own with the look of Shopper's side panels, use a [slide-over](/3.x/extending/slideover). # Navigation (/3.x/extending/navigation) The Control Panel navigation is highly customizable. You can add your own groups, items, and sub-items to it. The navigation is controlled by the [shopper/sidebar](https://github.com/shopperlabs/sidebar) package. This package can be used both as a standalone sidebar builder for any Laravel application or to extend Shopper's admin panel. Learn about the sidebar package architecture and features. Add custom menu items to the Shopper admin panel. Use the sidebar package in any Laravel application. Configure caching, dimensions, and behavior. ## Quick Start [#quick-start] To add navigation items to Shopper, create a sidebar extension class. Its `extendWith()` method receives the menu, adds a group to it, and adds an entry to the group for each of your pages: ```php title="app/Sidebar/GiftCardSidebar.php" namespace App\Sidebar; use Shopper\Sidebar\AbstractAdminSidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; class GiftCardSidebar extends AbstractAdminSidebar { public function extendWith(Menu $menu): Menu { $menu->group(__('Gift Cards'), function (Group $group): void { $group->weight(5); $group->collapsible(); $group->item(__('Issued cards'), function (Item $item): void { $item->weight(1); $item->setAuthorized($this->user->can('gift-cards.browse')); $item->useSpa(); $item->route('shopper.gift-cards.index'); $item->setIcon('phosphor-gift'); }); }); return $menu; } } ``` `$this->user` is the signed-in admin user, so `setAuthorized()` hides the entry from users who do not hold the permission. The route is the one your [custom route file](/3.x/extending/controllers#custom-routes) names `gift-cards.index`. Register the class as a listener of the `SidebarBuilder` event in your `AppServiceProvider`: ```php title="app/Providers/AppServiceProvider.php" namespace App\Providers; use App\Sidebar\GiftCardSidebar; use Illuminate\Support\ServiceProvider; use Shopper\Sidebar\SidebarBuilder; class AppServiceProvider extends ServiceProvider { public function register(): void { $this->app['events']->listen(SidebarBuilder::class, GiftCardSidebar::class); } } ``` The **Gift Cards** group then shows in the sidebar, and its **Issued cards** entry is selected on the page it links to: Shopper registers its own sidebar listeners in the `register()` method of a service provider. The sidebar is built later, while the admin request runs, so a listener registered in `boot()` works too. ## API Reference [#api-reference] The sidebar is built from five objects. The methods below are the ones a sidebar extension calls most; the linked sections describe each one: | Component | Methods | Documentation | |-----------|---------|---------------| | Menu | `group()` returns the group of that name, created on the first call, and runs the closure on it | [Group API](/3.x/sidebar/standalone#group-api) | | Group | `weight()`, `hideHeading()`, `collapsible()`, `setAuthorized()`, `item()`, and the CSS class setters `setClass()`, `setHeadingClass()` and `setGroupItemsClass()` | [Group API](/3.x/sidebar/standalone#group-api) | | Item | `route()`, `setUrl()`, `isNewTab()`, `setIcon()`, `useSpa()`, `weight()`, `setAuthorized()`, `isActiveWhen()`, `toggleIcon()`, `toggleActiveIcon()`, `setItemClass()`, `setActiveClass()`, `setParentItemClass()`, `badge()`, `append()` and `item()` for a sub-item | [Menu Item API](/3.x/sidebar/standalone#menu-item-api) | | Badge | `setValue()`, `setClass()` and `color()` | [Adding Badges](/3.x/sidebar/standalone#adding-badges) | | Append | `setName()`, `route()`, `setUrl()`, `setIcon()`, `setClass()` and `setAuthorized()` | [Adding Append Elements](/3.x/sidebar/standalone#adding-append-elements) | A few of these methods change how an entry or a group behaves in the admin panel: | Method | Behavior | |--------|----------| | `Group::hideHeading(bool $hide = true)` | Hides the heading of the group. A group with an empty name has no heading either. | | `Group::collapsible(bool $collapsible = true)` | Turns the heading into a button that folds the entries. The browser remembers the folded groups. | | `Item::isActiveWhen(string $path)` | Marks the entry active for a path pattern instead of its own URL, such as `config('shopper.admin.prefix').'/gift-cards*'`. The pattern includes the admin prefix, its leading and trailing slashes are removed, and `*` matches any characters. | | `Item::getActiveWhen(): ?string` | Returns the pattern, or `null` when the entry has none. A custom item view reads it to mark the active entry. | | `Item::toggleIcon(string $icon, string $type = 'blade', string $iconClass = '')` | Replaces the chevron shown after the label of an entry that has sub-items. `toggleActiveIcon()` takes the same arguments for the chevron of the open entry. | | `Item::setParentItemClass(string $class)` | Adds a CSS class to the list element that wraps the entry, where `setItemClass()` styles the link itself. | | `Badge::color(string $color)` | Adds the `sh-sidebar-item-badge-{color}` class to the badge. The admin panel styles `primary`, `success`, `warning`, `danger`, `info` and `purple`. | Shopper places its own groups with weights from 1 to 10, as described in [Weight System](/3.x/sidebar/shopper-extension#weight-system). # Extending Shopper (/3.x/extending/overview) Although Shopper is primarily designed for e-commerce sites and has many associated features, you are free to add or modify existing ones. ## Why extend Shopper [#why-extends-shopper] One might ask, knowing that the purpose of setting up an e-commerce site is simply to make the whole system work without always wanting to add to it. For example if you want a blog on your store, a section for a KYC, or maybe a forum, instead of creating another project to manage this you can directly extend Shopper to manage all this in the same administration area. ## How to extend Shopper [#how-to-extend-shopper] A screen of your own in the admin panel takes three pieces, each set up once in your application: 1. A route file for your admin pages. Point the `custom_file` key of `config/shopper/routes.php` to it: its routes share the login, the middleware and the URL prefix of the admin panel. [Controllers](/3.x/extending/controllers#custom-routes) shows the setup. 2. The pages. `php artisan make:shopper-page` creates a Livewire page in the namespace and the view path set by the `pages` key of `config/shopper/admin.php`. 3. A sidebar entry that links to the pages. A sidebar class listens to the `Shopper\Sidebar\SidebarBuilder` event from the `register()` method of a service provider, as [Navigation](/3.x/extending/navigation) shows. The `config/shopper/admin.php` file also holds the URL prefix, the domain, the brand logo and the primary color of the admin panel, described in [Configuration](/3.x/configuration#admin-panel). ## Extension Points [#extension-points] Each extension point is documented on the page of the feature it changes. The pages of this group cover the admin panel of your application: | Page | What it covers | |------|----------------| | [Control Panel](/3.x/extending/control-panel) | Extra stylesheets and scripts, a Tailwind theme of your own, the brand logo, and admin routes | | [Navigation](/3.x/extending/navigation) | Groups and entries added to the admin sidebar | | [Controllers](/3.x/extending/controllers) | Admin pages built with Livewire or with controllers, their breadcrumbs and their authorization | | [Forms](/3.x/extending/forms) | Filament forms in an admin page | | [Slide-overs](/3.x/extending/slideover) | Forms opened in a side panel | | [Render Hooks](/3.x/render-hooks) | HTML added at named places of the admin views | | [Sidebar](/3.x/sidebar/overview) | The sidebar package, in Shopper or in any Laravel application | | [Components](/3.x/extending/components/overview) | The Blade and Filament components of the admin panel, for your own screens | A package that extends the admin panel for several stores is an add-on: [Extending the Admin Panel](/3.x/addons/admin-panel) lists what an add-on can register. The pages below replace or extend a part of Shopper itself: | Extension point | Page | |-----------------|------| | Your own class for a Shopper model | [Swapping a Model](/3.x/models#swapping-a-model) | | A payment provider | [Custom Drivers](/3.x/payments#custom-drivers) | | A shipping carrier | [Custom Shipping Drivers](/3.x/carriers#custom-shipping-drivers) | | A step of the cart calculation | [Custom Pipeline](/3.x/cart#custom-pipeline) | | A tax provider | [Custom Tax Providers](/3.x/taxes#custom-tax-providers) | | A discount condition | [Custom Eligibility Rules](/3.x/discounts#custom-eligibility-rules) | | Price resolution, quantity rules and the price index | [Custom Price Resolver](/3.x/pricing#custom-price-resolver), [Quantity Rules](/3.x/pricing#quantity-rules), [Price Index](/3.x/pricing#price-index) | | Stock resolution and allocation | [Custom Inventory Resolver](/3.x/locations#custom-inventory-resolver), [Allocating Stock Across Locations](/3.x/locations#allocating-stock-across-locations) | | Webhook payloads and events | [Custom Payloads](/3.x/webhooks#custom-payloads), [Registering Custom Events](/3.x/webhooks#registering-custom-events) | | An import source | [Custom Import Sources](/3.x/import#custom-import-sources) | | A sales channel driver and the channel and zone resolvers | [Registering a Driver](/3.x/channels#registering-a-driver), [Channel Resolver](/3.x/channels#custom-resolver), [Zone Resolver](/3.x/zones#custom-resolver) | | A search indexer | [Custom Indexers](/3.x/search#custom-indexers) | | A Livewire component of the admin panel | [Components](/3.x/configuration#components), [Replacing the Dashboard](/3.x/dashboard#replacing-the-page), [Replacing a Widget](/3.x/dashboard#replacing-a-widget), [Replacing the General Page](/3.x/setup-store#replacing-the-general-page) | | A settings page | [Adding a Settings Page](/3.x/configuration#adding-a-settings-page) | | A color theme of the admin panel | [Creating a Theme](/3.x/themes#creating-a-theme) | | A permission | [Creating Custom Permissions](/3.x/acl#creating-custom-permissions) | | A notification sent by Shopper | [Replacing a Notification](/3.x/notifications#replacing-a-notification) | | The two-factor code provider | [Code Provider](/3.x/two-factor#code-provider) | | Payment method logos | [Logo Handling](/3.x/payment-methods#logo-handling) | | The order number format | [Orders](/3.x/configuration#orders) | ## How not to extend Shopper [#how-not-to-extend-shopper] It should go without saying, but we'll say it anyway just in case... Don't ever, for any reason, ever, no matter what, no matter where, or who, or who you are with, or where you are going or... or where you've been... ever, for any reason, whatsoever, edit the files inside `/vendor/shopper`. Or any other Composer package. Anything you do will get blown away and you'll lose those changes forever and ever amen. You should instead build addons, extensions, and submit pull requests to [admin](https://github.com/shopperlabs/shopper) (after checking with the team first if we'll accept them). Thanks! # Slide-overs (/3.x/extending/slideover) The admin panel opens most short forms in a panel that slides in from the side of the screen: brands, attributes, shipping options and team members, among others. Each panel is a Livewire component that extends `Laravelcm\LivewireSlideOvers\SlideOverComponent`, and the admin layout renders the panels that are open. Your own panels work the same way, with a [form](/3.x/extending/forms) inside. ## Creating a Slide-over [#creating-a-slide-over] The panel below issues a gift card, or edits one when it receives a gift card: ```php title="app/Livewire/SlideOvers/GiftCardForm.php" namespace App\Livewire\SlideOvers; use App\Models\GiftCard; use Filament\Actions\Concerns\InteractsWithActions; use Filament\Actions\Contracts\HasActions; use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Notifications\Notification; use Filament\Schemas\Concerns\InteractsWithSchemas; use Filament\Schemas\Contracts\HasSchemas; use Filament\Schemas\Schema; use Illuminate\Support\Arr; use Laravelcm\LivewireSlideOvers\SlideOverComponent; use Livewire\Attributes\Locked; use Shopper\Components\Form\MoneyInput; use Shopper\Components\Section; use Shopper\Contracts\SlideOverForm; use Shopper\Traits\HandlesAuthorizationExceptions; use Shopper\Traits\InteractsWithSlideOverForm; class GiftCardForm extends SlideOverComponent implements HasActions, HasSchemas, SlideOverForm { use HandlesAuthorizationExceptions; use InteractsWithActions; use InteractsWithSchemas; use InteractsWithSlideOverForm; #[Locked] public GiftCard $giftCard; public string $action = 'save'; public ?string $title = null; public ?string $description = null; public ?array $data = []; public function mount(?GiftCard $giftCard = null): void { $this->giftCard = $giftCard ?? new GiftCard; $this->authorize($this->giftCard->exists ? 'gift-cards.edit' : 'gift-cards.create'); $this->title = $this->giftCard->exists ? __('Gift card :code', ['code' => $this->giftCard->code]) : __('Issue a gift card'); $this->description = __('Customers enter the code at checkout.'); $this->form->fill($this->giftCard->toArray()); } public function form(Schema $schema): Schema { return $schema ->components([ Section::make(__('Gift card')) ->collapsible() ->compact() ->schema([ TextInput::make('code') ->label(__('Code')) ->required() ->maxLength(32) ->unique(GiftCard::class, 'code', ignoreRecord: true), MoneyInput::make('amount') ->label(__('Amount')) ->currency(shopper_currency()) ->amountRules() ->required(), DatePicker::make('expires_at') ->label(__('Expires on')) ->minDate(now()), Toggle::make('is_enabled') ->label(__('Enabled')) ->default(true), ]), ]) ->statePath('data') ->model($this->giftCard); } public function save(): void { $this->authorize($this->giftCard->exists ? 'gift-cards.edit' : 'gift-cards.create'); $values = Arr::only($this->form->getState(), ['code', 'amount', 'expires_at', 'is_enabled']); if ($this->giftCard->exists) { $this->giftCard->update($values); } else { GiftCard::query()->create([...$values, 'currency_code' => shopper_currency()]); } Notification::make() ->title(__('Gift card saved')) ->success() ->send(); $this->dispatch('gift-card.saved'); $this->closePanel(); } } ``` The component has no view of its own. The parts that give it the layout of Shopper's panels: | Part | Role | |------|------| | `Shopper\Contracts\SlideOverForm` | Declares `getFormAction()`, `getTitle()` and `getDescription()`, read by the view of the panel. | | `Shopper\Traits\InteractsWithSlideOverForm` | Implements the three methods from the `$action`, `$title` and `$description` properties, and adds a `render()` method that returns Shopper's panel view. | | `$action` | The method the save button calls, `save` here. | | `$title`, `$description` | The heading of the panel and the text below it. Set them in `mount()`, where the record is known. `$description` is optional. | | `closePanel()` | Closes the panel once the gift card is saved. [Closing a Slide-over](#closing-a-slide-over) describes the other ways. | `mount()` and `save()` check the permission themselves, following the [authorization pattern](/3.x/extending/controllers#authorization-pattern-for-custom-admin-components) of the admin panel: the event that opens a panel can be dispatched from any page, whatever buttons it shows. The `#[Locked]` attribute keeps the browser from swapping the gift card for another one between two requests. ### Panel View [#panel-view] The view that `InteractsWithSlideOverForm` returns wraps the form in the `x-shopper::form-slider-over` component: ```blade title="vendor/shopper/framework/resources/views/livewire/slide-overs/form.blade.php" {{ $this->form }} ``` The component renders the title and a close button at the top, the description below them, the form in a body that scrolls, and a footer with a **Cancel** button that closes the panel and a **Save** button that submits the form to the action. To show more than the form, such as the balance left on a gift card, add a `render()` method to your class and return a view of your own that uses the same component. The Livewire method called when the form is submitted. The **Save** button shows a loader while it runs. The heading of the panel. Text shown below the heading. Nothing is rendered when it is empty. A panel without a form, such as the one that reorders categories, uses `x-shopper::slideover-card` directly and writes its own header and footer: the card gives the background, border and rounded corners of the panels. ## Registering a Slide-over [#registering-a-slide-over] A panel of your application needs no registration. Livewire finds it from its name, the path of the class below `App\Livewire` in kebab case: `App\Livewire\SlideOvers\GiftCardForm` is `slide-overs.gift-card-form`. An add-on registers its panels with `addonLivewireComponents()`, which prefixes their names with `shopper-`, as described in [Livewire Components](/3.x/addons/admin-panel#livewire-components). ## Opening a Slide-over [#opening-a-slide-over] A button opens a panel by dispatching the `openPanel` event with the name of the component. The `arguments` key passes values to the component: ```blade title="resources/views/livewire/shopper/gift-cards/index.blade.php" {{ __('Issue a gift card') }} {{ __('Edit') }} ``` Clicking **Edit** on a gift card opens the panel with the gift card loaded: From PHP, such as the action of a table row, pass the name and the arguments to `dispatch()`: ```php title="app/Livewire/Shopper/GiftCards/Index.php" use App\Models\GiftCard; use Filament\Actions\Action; Action::make('edit') ->authorize('gift-cards.edit') ->action(fn (GiftCard $record) => $this->dispatch( 'openPanel', 'slide-overs.gift-card-form', ['giftCard' => $record->id], )); ``` The panel passes on the arguments named after a public property or a parameter of `mount()`, and drops the others. A name in kebab case, such as `gift-card`, matches the `giftCard` property. When the property is typed with a model, the argument is the key of the record: the panel loads it with `resolveRouteBinding()` and throws a `ModelNotFoundException` when it does not exist. A property typed with a backed enum takes the value of a case. A panel opened from another panel stacks on top of it. Closing the top panel shows the previous one again. ## Closing a Slide-over [#closing-a-slide-over] The user closes a panel with the **Cancel** button or the close button of `x-shopper::form-slider-over`, the `Escape` key, or a click outside the panel. Your component closes it from PHP with these methods: | Method | Effect | |--------|--------| | `closePanel()` | Closes the active panel and shows the previous one, if the panel was opened from another panel. | | `forceClose()` | Chained before `closePanel()`, closes every open panel. | | `skipPreviousPanels(int $count = 1, bool $destroy = false)` | Chained before `closePanel()`, also closes that number of previous panels. With `$destroy`, their components are removed. | | `closePanelWithEvents(array $events)` | Dispatches the events, then closes the panel. A key that is a component name sends the event to that component only, and an array value is the event name followed by its parameters. | `GiftCardForm` dispatches `gift-card.saved` before it closes. The page that lists the gift cards listens to it to render again, with the new card: ```php title="app/Livewire/Shopper/GiftCards/Index.php" use Illuminate\Contracts\View\View; use Livewire\Attributes\On; #[On('gift-card.saved')] public function render(): View { return view('livewire.shopper.gift-cards.index'); } ``` ## Panel Options [#panel-options] Static methods of `SlideOverComponent` set the behavior of a panel. Override them in your component: ```php title="app/Livewire/SlideOvers/GiftCardForm.php" public static function panelMaxWidth(): string { return '2xl'; } ``` | Method | Default | Effect | |--------|---------|--------| | `panelMaxWidth()` | `'xl'` | The maximum width of the panel: `md`, `lg`, `xl`, `2xl`, `3xl`, `4xl`, `5xl`, `6xl` or `7xl`. The attribute form of Shopper uses `lg`, the shipment details use `2xl` and the shipping label form `5xl`. | | `closePanelOnClickAway()` | `true` | Closes every open panel on a click outside them. | | `closePanelOnEscape()` | `true` | Closes the active panel on the `Escape` key. | | `dispatchCloseEvent()` | `false` | Dispatches a `panelClosed` event with the `name` of the component when the panel closes. | | `destroyOnClose()` | `false` | Removes the component when the panel closes, so the next opening mounts it again. | The defaults come from the `component_defaults` key of `config/livewire-slide-over.php`. To change them for every panel, Shopper's included, publish the file with `php artisan vendor:publish --tag=livewire-slide-over-config`. The `panelAttributes` key of the `openPanel` event overrides these options for one opening. Its keys are `maxWidthClass` (a Tailwind CSS class such as `max-w-3xl`), `closeOnClickAway`, `closeOnEscape`, `dispatchCloseEvent` and `destroyOnClose`: ```blade title="resources/views/livewire/shopper/gift-cards/index.blade.php" {{ __('Issue a gift card') }} ``` To change the width of a panel while it is open, such as when a step shows a wide table, call `$this->resizePanel('max-w-5xl')` from the component. The stylesheet of the admin panel holds the classes from `max-w-md` to `max-w-7xl`. # Render Hooks (/3.x/render-hooks) Render hooks give you named injection points inside Shopper's admin views. Instead of overriding templates, you register a callback on a hook name and Shopper renders your content in the right place at the right time. This is the recommended way to add content to an admin page: a banner in the sidebar of the order page, a widget above the product list, or a tracking script in the page head. ## Registering a Hook [#registering-a-hook] Your application registers hooks on the admin panel through the `Shopper` facade, in the `boot()` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; use Shopper\View\OrderRenderHook; public function boot(): void { Shopper::renderHook( OrderRenderHook::DETAIL_SIDEBAR_AFTER, fn (): string => '

    Ships from the Lyon warehouse.

    ', ); } ``` The text shows at the end of the sidebar of the order page, below the billing address: The callback receives no arguments. Shopper casts what it returns to a string and outputs it as HTML without compiling it with Blade, so return plain HTML, a view, or a Livewire component rendered with `Blade::render()`. The HTML is not escaped: pass any value that comes from a record or a request through `e()`, or render it in a view with `{{ }}`. An add-on registers its hooks with `$panel->renderHook()` in the `register()` method of its add-on class, as described in [Render Hooks](/3.x/addons/admin-panel#render-hooks) of the add-on guide. ### Returning a Blade View [#returning-a-blade-view] A view is rendered when Shopper casts it to a string, so the callback can return it as is: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Contracts\View\View; use Shopper\Facades\Shopper; use Shopper\View\ProductRenderHook; Shopper::renderHook( ProductRenderHook::EDIT_CONTENT_AFTER, fn (): View => view('shopper.products.seo-checklist'), ); ``` ### Returning a Livewire Component [#returning-a-livewire-component] Because Shopper does not compile the output with Blade, a `` tag returned as a string is printed as is. Render the tag with `Blade::render()`: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\CustomerRenderHook; Shopper::renderHook( CustomerRenderHook::SHOW_SIDEBAR_AFTER, fn (): string => Blade::render(''), ); ``` The callback cannot pass the customer to the component. The [example below](#example-injecting-an-external-status-badge-on-order-detail) shows how a component reads the record of the page from the route. ### Registering Multiple Hooks [#registering-multiple-hooks] `renderHook()` returns the panel, so you can chain several calls: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; use Shopper\View\LayoutRenderHook; Shopper::renderHook( LayoutRenderHook::HEAD_END, fn (): string => '', )->renderHook( LayoutRenderHook::BODY_START, fn (): string => view('analytics.noscript-tag')->render(), ); ``` Multiple callbacks registered on the same hook are rendered in the order they were registered, concatenated together. ## Disabling a Hook [#disabling-a-hook] Hooks registered by an add-on follow the add-on's enabled state: a [disabled add-on](/3.x/addons#disabling-an-addon) registers none. For the hooks of your application, register them under a condition: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; use Shopper\View\OrderRenderHook; if (config('features.custom_order_widget')) { Shopper::renderHook( OrderRenderHook::DETAIL_MAIN_AFTER, fn (): string => view('orders.external-status')->render(), ); } ``` ## Available Hooks [#available-hooks] Each hook is a constant of a class in the `Shopper\View` namespace. The tables give the hook name behind each constant and the place where it renders. The callbacks of a hook run each time the view that holds it renders. Hooks inside a Livewire page, such as the dashboard or the order page, run again when the page re-renders after an action, so keep their queries short. ### Layout Hooks [#layout-hooks] `LayoutRenderHook` covers the global admin layout present on every page. | Constant | Hook Name | Position | |----------|-----------|----------| | `HEAD_START` | `shopper::head.start` | In ``, after the meta tags and fonts, before the Filament styles and the Shopper theme | | `HEAD_END` | `shopper::head.end` | In ``, after the Shopper theme, scripts and extra stylesheets | | `BODY_START` | `shopper::body.start` | Right after `` | | `BODY_END` | `shopper::body.end` | Right before ``, after the slide-over panels and the scripts | | `BEFORE_HEADER` | `shopper::header.before` | Above the top bar | | `AFTER_HEADER` | `shopper::header.after` | Below the top bar | | `HEADER_START` | `shopper::header.start` | In the top bar, before the notifications, the site link and the account menu | | `HEADER_END` | `shopper::header.end` | In the top bar, after `HEADER_START` and before the notifications | | `SIDEBAR_START` | `shopper::sidebar.start` | At the top of the sidebar navigation | | `SIDEBAR_END` | `shopper::sidebar.end` | At the bottom of the sidebar navigation | | `CONTENT_START` | `shopper::content.start` | Above the content of the page | | `CONTENT_END` | `shopper::content.end` | Below the content of the page | | `CONTENT_ASIDE` | `shopper::content.aside` | Next to the content of the page, for a side panel | | `DASHBOARD_START` | `shopper::dashboard.start` | Top of the dashboard page | | `DASHBOARD_END` | `shopper::dashboard.end` | Bottom of the dashboard page | | `ACCOUNT_START` | `shopper::account.start` | Top of the account page | | `ACCOUNT_END` | `shopper::account.end` | Bottom of the account page | The `HEAD` and `BODY` hooks also render on the sign-in pages. Check `shopper()->auth()->check()` in the callback before rendering content meant for signed-in users. The settings index page has no hooks: `SETTINGS_INDEX_START` and `SETTINGS_INDEX_END` do not exist in 3.x. ### Product Hooks [#product-hooks] `ProductRenderHook` targets the product list, product edit and variant pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::products.index.table.before` | Above the products table | | `INDEX_TABLE_AFTER` | `shopper::products.index.table.after` | Below the products table | | `EDIT_HEADER_AFTER` | `shopper::product.edit.header.after` | Below the product page header | | `EDIT_TABS_BEFORE` | `shopper::product.edit.tabs.before` | Above the section menu of the product page | | `EDIT_TABS_END` | `shopper::product.edit.tabs.end` | In the section menu, after its last group | | `EDIT_CONTENT_BEFORE` | `shopper::product.edit.content.before` | Above the content of the active section | | `EDIT_CONTENT_AFTER` | `shopper::product.edit.content.after` | Below the content of the active section | | `VARIANT_HEADER_AFTER` | `shopper::product.variant.header.after` | Below the variant page header | | `VARIANT_MAIN_AFTER` | `shopper::product.variant.main.after` | At the bottom of the main column of the variant page | | `VARIANT_SIDEBAR_AFTER` | `shopper::product.variant.sidebar.after` | At the bottom of the sidebar of the variant page | To add a section with its own page to the product menu, register a [product section](/3.x/addons/admin-panel#product-sections) instead of a link in `EDIT_TABS_END`. ### Order Hooks [#order-hooks] `OrderRenderHook` targets the order list, order detail, shipments, and abandoned carts pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::orders.index.table.before` | Above the orders table | | `INDEX_TABLE_AFTER` | `shopper::orders.index.table.after` | Below the orders table | | `DETAIL_HEADER_AFTER` | `shopper::order.detail.header.after` | Below the order detail page header | | `DETAIL_CONTENT_BEFORE` | `shopper::order.detail.content.before` | At the top of the order content, above both columns | | `DETAIL_MAIN_BEFORE` | `shopper::order.detail.main.before` | Above the two columns, after `DETAIL_CONTENT_BEFORE` | | `DETAIL_MAIN_AFTER` | `shopper::order.detail.main.after` | At the bottom of the main column, below the order summary | | `DETAIL_SIDEBAR_BEFORE` | `shopper::order.detail.sidebar.before` | At the top of the sidebar, above the customer card | | `DETAIL_SIDEBAR_AFTER` | `shopper::order.detail.sidebar.after` | At the bottom of the sidebar, below the customer card | | `DETAIL_CONTENT_AFTER` | `shopper::order.detail.content.after` | At the bottom of the order content, below both columns | | `SHIPMENTS_TABLE_BEFORE` | `shopper::shipments.index.table.before` | Above the shipments table | | `SHIPMENTS_TABLE_AFTER` | `shopper::shipments.index.table.after` | Below the shipments table | | `ABANDONED_CARTS_TABLE_BEFORE` | `shopper::abandoned-carts.table.before` | Above the abandoned carts table | | `ABANDONED_CARTS_TABLE_AFTER` | `shopper::abandoned-carts.table.after` | Below the abandoned carts table | ### Customer Hooks [#customer-hooks] `CustomerRenderHook` targets the customer list, customer creation and customer detail pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::customers.index.table.before` | Above the customers table | | `INDEX_TABLE_AFTER` | `shopper::customers.index.table.after` | Below the customers table | | `CREATE_FORM_BEFORE` | `shopper::customer.create.form.before` | Before the new customer form | | `CREATE_FORM_AFTER` | `shopper::customer.create.form.after` | After the new customer form | | `SHOW_HEADER_AFTER` | `shopper::customer.show.header.after` | Below the customer detail header | | `SHOW_TABS_BEFORE` | `shopper::customer.show.tabs.before` | Above the customer detail tabs | | `SHOW_TABS_END` | `shopper::customer.show.tabs.end` | In the tab bar, after the last tab | | `SHOW_CONTENT_BEFORE` | `shopper::customer.show.content.before` | Above the content of the active tab | | `SHOW_CONTENT_AFTER` | `shopper::customer.show.content.after` | Below the content of the active tab | | `SHOW_SIDEBAR_BEFORE` | `shopper::customer.show.sidebar.before` | At the top of the sidebar of the customer page | | `SHOW_SIDEBAR_AFTER` | `shopper::customer.show.sidebar.after` | At the bottom of the sidebar of the customer page | ### Collection Hooks [#collection-hooks] `CollectionRenderHook` targets the collection list and collection edit pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `INDEX_TABLE_BEFORE` | `shopper::collections.index.table.before` | Above the collections table | | `INDEX_TABLE_AFTER` | `shopper::collections.index.table.after` | Below the collections table | | `EDIT_FORM_BEFORE` | `shopper::collection.edit.form.before` | Before the collection edit form | | `EDIT_FORM_AFTER` | `shopper::collection.edit.form.after` | After the collection edit form | ### Catalog Hooks [#catalog-hooks] `CatalogRenderHook` covers the catalog support pages: categories, brands, tags, attributes, and reviews. | Constant | Hook Name | Position | |----------|-----------|----------| | `CATEGORIES_TABLE_BEFORE` | `shopper::categories.index.table.before` | Above the categories table | | `CATEGORIES_TABLE_AFTER` | `shopper::categories.index.table.after` | Below the categories table | | `BRANDS_TABLE_BEFORE` | `shopper::brands.index.table.before` | Above the brands table | | `BRANDS_TABLE_AFTER` | `shopper::brands.index.table.after` | Below the brands table | | `TAGS_TABLE_BEFORE` | `shopper::tags.index.table.before` | Above the tags table | | `TAGS_TABLE_AFTER` | `shopper::tags.index.table.after` | Below the tags table | | `ATTRIBUTES_TABLE_BEFORE` | `shopper::attributes.index.table.before` | Above the attributes table | | `ATTRIBUTES_TABLE_AFTER` | `shopper::attributes.index.table.after` | Below the attributes table | | `REVIEWS_TABLE_BEFORE` | `shopper::reviews.index.table.before` | Above the reviews table | | `REVIEWS_TABLE_AFTER` | `shopper::reviews.index.table.after` | Below the reviews table | ### Sales Hooks [#sales-hooks] `SalesRenderHook` covers the discounts and suppliers pages. | Constant | Hook Name | Position | |----------|-----------|----------| | `DISCOUNTS_TABLE_BEFORE` | `shopper::discounts.index.table.before` | Above the discounts table | | `DISCOUNTS_TABLE_AFTER` | `shopper::discounts.index.table.after` | Below the discounts table | | `DISCOUNT_CREATE_FORM_BEFORE` | `shopper::discounts.create.form.before` | Before the form of the slide-over that creates a discount | | `DISCOUNT_CREATE_FORM_AFTER` | `shopper::discounts.create.form.after` | After the form of the slide-over that creates a discount | | `DISCOUNT_EDIT_FORM_BEFORE` | `shopper::discounts.edit.form.before` | Before the discount edit form | | `DISCOUNT_EDIT_FORM_AFTER` | `shopper::discounts.edit.form.after` | After the discount edit form | | `SUPPLIERS_TABLE_BEFORE` | `shopper::suppliers.index.table.before` | Above the suppliers table | | `SUPPLIERS_TABLE_AFTER` | `shopper::suppliers.index.table.after` | Below the suppliers table | ## Example: Injecting an External Status Badge on Order Detail [#example-injecting-an-external-status-badge-on-order-detail] A real-world scenario: your store syncs orders to a fulfillment service (ShipStation, ShipBob, etc.) and you want to display the external status directly on the order detail page, without modifying any Shopper files. The hook callback receives no arguments, so it cannot pass the order to your component. Instead, the hook renders a Livewire component that reads the order from the current route in its `mount()` method. The order detail route is `{order}/detail`, and the order detail page resolves `{order}` to the `Order` model. Livewire keeps the component's state on later requests, so `mount()` only runs on the page load. Create the Livewire component: ```php title="app/Livewire/ExternalOrderStatus.php" namespace App\Livewire; use App\Services\ExternalFulfillmentService; use Illuminate\Contracts\View\View; use Livewire\Attributes\Locked; use Livewire\Component; class ExternalOrderStatus extends Component { #[Locked] public int $orderId; public function mount(): void { $this->orderId = request()->route('order')->id; } public function render(): View { $status = ExternalFulfillmentService::getStatus($this->orderId); return view('livewire.external-order-status', ['status' => $status]); } } ``` Register the hook in your service provider: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Support\Facades\Blade; use Shopper\Facades\Shopper; use Shopper\View\OrderRenderHook; public function boot(): void { Shopper::renderHook( OrderRenderHook::DETAIL_SIDEBAR_AFTER, fn (): string => Blade::render(''), ); } ``` ## Using Hook Constants vs. Raw Strings [#using-hook-constants-vs-raw-strings] Always use the class constants instead of raw hook name strings. They are checked by static analysis, will trigger IDE autocompletion, and won't silently break if a hook name changes in a future release. Both calls below register on the same hook: ```php title="app/Providers/AppServiceProvider.php" use Shopper\Facades\Shopper; use Shopper\View\ProductRenderHook; Shopper::renderHook(ProductRenderHook::EDIT_CONTENT_AFTER, fn (): string => '

    Reviewed by the catalog team

    '); Shopper::renderHook('shopper::product.edit.content.after', fn (): string => '

    Reviewed by the catalog team

    '); ``` # Configuration (/3.x/sidebar/configuration) The sidebar package reads its options from `config/sidebar.php`. Publish the file to change them: ```bash php artisan vendor:publish --tag="sidebar-config" ``` ## Configuration Options [#configuration-options] The file has five options: the cache, the two widths, the mobile breakpoint, collapsing, and the breadcrumb view. ### Caching [#caching] Building a sidebar runs every listener, permission check and badge query on each request. The `cache` option stores the built sidebar instead: ```php 'cache' => [ 'method' => null, 'duration' => 1440, ], ``` | Option | Values | Description | |--------|--------|-------------| | `method` | `null`, `static`, `user-based` | The caching method. Any other value throws a `SidebarResolverNotSupported` exception. | | `duration` | Integer | How long a cached sidebar is kept, in minutes. The default, `1440`, is one day. | Each method stores the sidebar differently: - `null` builds the sidebar on every request. This is the default. - `static` stores one copy of each sidebar for each locale, shared by every user, under the `shopper.sidebar.` key followed by an md5 hash of the sidebar class name. - `user-based` stores one copy for each user and locale, tagged with that key. It needs a cache store that supports tags, such as Redis or Memcached. With a store that does not, such as `file` or `database`, the sidebar is built on every request, as with `null`. With `static`, the first user who loads the sidebar decides what everyone sees: entries hidden by permissions stay hidden or visible for every user, and badge counts stay at their first value until the cache expires. The Shopper admin hides entries by permission, so keep `null` or use `user-based` there. With `user-based`, badge counts are also cached: flush the cache when they must change, as described in [Clearing the Cache](#clearing-the-cache). ### Dimensions [#dimensions] The two widths of the sidebar, expanded and collapsed: ```php 'width' => '15rem', 'collapsed_width' => '4.5rem', ``` | Option | Default | Description | |--------|---------|-------------| | `width` | `15rem` | The width of the expanded sidebar. | | `collapsed_width` | `4.5rem` | The width of the collapsed sidebar. | Your layout passes these values to the CSS variables `--sidebar-width` and `--sidebar-collapsed-width`, as described in [Injecting CSS Variables](#injecting-css-variables). ### Responsive Breakpoint [#responsive-breakpoint] The width in pixels below which the sidebar works as a mobile drawer: ```php 'breakpoint' => 1024, ``` Below this width, the sidebar stays hidden until it is opened, `toggle()` opens and closes it instead of collapsing it, and a click on an entry closes it, as does the Escape key in the Livewire component. The store reads the value from the `data-sidebar-breakpoint` attribute of the ``. ### Collapsible [#collapsible] Whether the sidebar can collapse to icons from the breakpoint up: ```php 'collapsible' => true, ``` With `false`, the store's `collapse()` and `toggleCollapse()` methods do nothing, and the default wrapper view hides its collapse button. The store reads the value from the `data-sidebar-collapsible` attribute of the ``. ### Breadcrumbs [#breadcrumbs] The Blade view that renders the breadcrumb trail: ```php 'breadcrumbs' => [ 'view' => 'sidebar::breadcrumbs', ], ``` The package does not render this view by itself: your layout includes it, as described in [Displaying the Breadcrumbs](/3.x/sidebar/standalone#displaying-the-breadcrumbs). In a Shopper application, Shopper sets this option to `shopper::components.breadcrumbs` when it registers, after the published file is loaded. To use another view there, set the option from the `boot()` method of a service provider: ```php config(['sidebar.breadcrumbs.view' => 'partials.breadcrumbs']); ``` ## Full Configuration Example [#full-configuration-example] The published file with its default values: ```php title="config/sidebar.php" return [ 'cache' => [ 'method' => null, 'duration' => 1440, ], 'width' => '15rem', 'collapsed_width' => '4.5rem', 'breakpoint' => 1024, 'collapsible' => true, 'breadcrumbs' => [ 'view' => 'sidebar::breadcrumbs', ], ]; ``` ## Environment Variables [#environment-variables] The package reads no environment variable. To change an option per environment, such as the cache method in production, call `env()` in your published `config/sidebar.php` with variable names of your choice: ```php 'cache' => [ 'method' => env('SIDEBAR_CACHE_METHOD'), 'duration' => (int) env('SIDEBAR_CACHE_DURATION', 1440), ], ``` Then set the variables in the `.env` file of each environment: ```dotenv SIDEBAR_CACHE_METHOD=user-based SIDEBAR_CACHE_DURATION=60 ``` ## Accessing Configuration [#accessing-configuration] The helper functions of the `Shopper\Sidebar` namespace read the options: ```php use function Shopper\Sidebar\sidebar_breakpoint; use function Shopper\Sidebar\sidebar_collapsed_width; use function Shopper\Sidebar\sidebar_config; use function Shopper\Sidebar\sidebar_is_collapsible; use function Shopper\Sidebar\sidebar_width; $cacheMethod = sidebar_config('cache.method'); $width = sidebar_width(); $collapsedWidth = sidebar_collapsed_width(); $breakpoint = sidebar_breakpoint(); $collapsible = sidebar_is_collapsible(); ``` With the default configuration, they return `null`, `15rem`, `4.5rem`, `1024` and `true`. [Helper Functions](/3.x/sidebar/standalone#helper-functions) lists every helper. ## Injecting CSS Variables [#injecting-css-variables] The views size the sidebar with CSS variables, and the store reads its breakpoint and collapsing options from the ``. Set both in your layout: ```blade title="resources/views/layouts/app.blade.php" {{ $slot }} ``` The store's `init()` method reads the two `data-*` attributes when Alpine.js registers the store. ## Customizing Views [#customizing-views] Publish the views to change their markup: ```bash php artisan vendor:publish --tag="sidebar-views" ``` The views are copied to `resources/views/vendor/sidebar/`, and Laravel uses your copies instead of the package views: | View | Renders | Variables | |------|---------|-----------| | `menu.blade.php` | The list of groups | `$groups`, the rendered groups | | `group.blade.php` | A group, with its heading | `$group`, `$items` (the rendered entries) | | `item.blade.php` | An entry, with its badges, quick actions and sub-items | `$item`, `$items`, `$badges`, `$appends`, `$active` | | `badge.blade.php` | A badge | `$badge` | | `append.blade.php` | A quick action link | `$append` | | `breadcrumbs.blade.php` | The breadcrumb trail | None, it calls `sidebar_breadcrumbs()` | | `livewire/sidebar.blade.php` | The wrapper of the Livewire component | `$sidebar`, `$renderedSidebar`, `$class`, `$collapsible` | ### Example: Customizing the Item View [#example-customizing-the-item-view] In the item view, `$item` is the entry builder, while `$items`, `$badges` and `$appends` hold the sub-items, badges and quick actions already rendered as HTML. `$active` tells whether the entry or one of its sub-items matched the request on the server. This version uses Tailwind classes and keeps the `x-data` and `$store.sidebar` bindings, so the active state still follows `wire:navigate` visits: ```blade title="resources/views/vendor/sidebar/item.blade.php"
  • $active]) x-data="{ url: @js($item->getUrl()), activeWhen: @js($item->getActiveWhen()) }" > withSpa()) wire:navigate @endif @if ($item->getNewTab()) target="_blank" @endif > @if ($item->iconSvg()) {!! $item->getIcon() !!} @elseif ($item->getIcon() !== null) @svg($item->getIcon(), 'size-5 ' . $item->getIconClass(), $item->getIconAttributes()) @endif {{ $item->getName() }} @foreach ($badges as $badge) {!! $badge !!} @endforeach @foreach ($appends as $append) {!! $append !!} @endforeach @if (count($items) > 0)
      @foreach ($items as $subItem) {!! $subItem !!} @endforeach
    @endif
  • ``` ## Clearing the Cache [#clearing-the-cache] `php artisan cache:clear` empties the whole application cache, the sidebars included. The cache keys are hashed, so use the `Shopper\Sidebar\Infrastructure\SidebarFlusher` service rather than `cache:forget` to flush one sidebar. The container binds it to the flusher of the configured method: ```php use App\Sidebar\StoreSidebar; use Shopper\Sidebar\Infrastructure\SidebarFlusher; app(SidebarFlusher::class)->flush(StoreSidebar::class); ``` The static flusher deletes the shared copy, the user-based flusher deletes the copies of every user through the tag, and with `null` there is nothing to flush. The `SidebarManager` flushes every registered sidebar at once: ```php use Shopper\Sidebar\Infrastructure\SidebarFlusher; use Shopper\Sidebar\SidebarManager; app(SidebarManager::class)->flush(app(SidebarFlusher::class)); ``` Flush after a change that a cached sidebar shows, such as new permissions for a role. In a Shopper application, the admin sidebar class is `Shopper\Sidebar\AdminSidebar`. # Sidebar Package (/3.x/sidebar/overview) The `shopper/sidebar` package builds sidebars for Laravel applications. You describe groups and entries in PHP, the package renders them with Blade views that you can publish and restyle, and an Alpine.js store keeps the open, collapsed and active states in the browser. The Shopper admin panel draws its own sidebar with it. The package started as a fork of [SpartnerNL/Laravel-Sidebar](https://github.com/SpartnerNL/Laravel-Sidebar) and was rewritten for Livewire and Alpine.js. ## Features [#features] The package covers the server side and the browser side of a sidebar: - Blade views for the menu, groups, entries, badges, quick actions and breadcrumbs, which you publish and restyle. - A `sidebar` Livewire component that renders a registered sidebar and renders it again on the `sidebar:refresh` event. - An Alpine.js store for the mobile, collapsed and folded-group states, saved in `localStorage`. - Extension through Laravel events: the Shopper admin fires one event, and each listener adds its groups and entries. - Authorization on groups, entries, badges and quick actions. - Breadcrumbs built from the active entry of the sidebar, plus the crumbs a page adds. - Optional caching, shared by every user or kept per user. ## Architecture [#architecture] A sidebar is a class that implements the `Shopper\Sidebar\Contracts\Sidebar` contract and fills a menu in its `build()` method. The menu holds groups, and each group holds entries. ### Menu [#menu] The menu is the root of a sidebar. `$menu->group()` creates a group, or returns the group that already has that name, so several classes can add entries to the same group. Groups are sorted by weight, lowest first. ### Group [#group] A group is a set of entries under an optional heading. It has a weight, can hide its heading with `hideHeading()`, and can be made collapsible with `collapsible()`: its heading then becomes a button that folds the entries, and the store remembers the folded groups. ### Item [#item] An item is a single entry of the sidebar. Its builder methods cover the link, the display and the behavior of the entry: | Method | Description | |--------|-------------| | `route($name, $parameters)`, `setUrl($url)` | The link of the entry, from a route name or a URL. | | `setIcon($icon, $type, $iconClass, $attributes)` | A Blade Icons name (`blade`, the default) or raw SVG markup (`svg`). | | `weight($weight)` | The position among the other entries of the group, lowest first. | | `setAuthorized($authorized)` | Hides the entry and its sub-items when `false`. | | `badge($value, $class)` | Adds a badge, such as a count of new orders. | | `append($route, $icon, $name)` | Adds a quick action link after the entry, such as a button that opens a creation form. | | `item($name, $callback)` | Adds a sub-item. | | `isActiveWhen($pattern)` | Marks the entry active for a path pattern instead of its own URL. | | `isNewTab()` | Opens the link in a new tab. | | `useSpa()` | Opens the link with Livewire's `wire:navigate`, without a full page reload. | | `setItemClass()`, `setActiveClass()`, `setParentItemClass()` | CSS classes for the link, the link while active, and the list element. | | `toggleIcon()`, `toggleActiveIcon()` | The chevron of an entry that has sub-items, closed and open. | [Menu Item API](/3.x/sidebar/standalone#menu-item-api) shows each method in use. ### Contracts [#contracts] Every part of the sidebar is a contract. The service provider binds each builder contract to a class of the `Shopper\Sidebar\Domain` namespace, so binding your own class to a contract in a service provider replaces the default one everywhere: | Contract | Role | Default class | |----------|------|---------------| | `Shopper\Sidebar\Contracts\Sidebar` | A sidebar: `build()` and `getMenu()` | None, you write it | | `Shopper\Sidebar\Contracts\Builder\Menu` | The root of a sidebar | `DefaultMenu` | | `Shopper\Sidebar\Contracts\Builder\Group` | A group of entries | `DefaultGroup` | | `Shopper\Sidebar\Contracts\Builder\Item` | An entry | `DefaultItem` | | `Shopper\Sidebar\Contracts\Builder\Badge` | A badge on an entry | `DefaultBadge` | | `Shopper\Sidebar\Contracts\Builder\Append` | A quick action after an entry | `DefaultAppend` | ## Use Cases [#use-cases] The package works in two kinds of projects: a Laravel application that builds its own sidebar, and a Shopper store that adds entries to the admin sidebar. ### Standalone Laravel Applications [#standalone-laravel-applications] Any Laravel application that runs Livewire can build sidebars with the package, for a back office or a customer account area. See the [Standalone Installation](/3.x/sidebar/standalone) guide. ### Extending Shopper [#extending-shopper] The Shopper admin builds its sidebar from an event. Your application adds groups and entries with a listener, as described in [Extending Shopper](/3.x/sidebar/shopper-extension). An add-on registers its sidebar class with `addonSidebar()` instead, as described in [Sidebar Navigation](/3.x/addons/admin-panel#sidebar-navigation). ## Requirements [#requirements] The package needs the PHP, Laravel and Livewire versions that Shopper needs, listed in [Laravel and Package Versions](/3.x/requirements#laravel-and-package-versions). Alpine.js, which runs the sidebar store, ships with Livewire. # Extending Shopper (/3.x/sidebar/shopper-extension) This guide adds entries to the Shopper admin sidebar from your application. An add-on registers its sidebar class with `addonSidebar()` instead of a listener, as described in [Sidebar Navigation](/3.x/addons/admin-panel#sidebar-navigation). The class itself is written the same way in both cases. ## Overview [#overview] The admin panel registers one sidebar, `Shopper\Sidebar\AdminSidebar`. The `ResolveSidebars` middleware of the admin routes builds it on each admin request, and building it fires the `Shopper\Sidebar\SidebarBuilder` event with the menu. Shopper's own groups are listeners of this event, and your extension is one more listener. ## Creating a Sidebar Extension [#creating-a-sidebar-extension] An extension is a class that adds groups and entries to the menu, registered as a listener of `SidebarBuilder`. ### 1. Create an Extension Class [#1-create-an-extension-class] Extend `Shopper\Sidebar\AbstractAdminSidebar` and add your groups in `extendWith()`. The parent class receives the event, passes the menu to `extendWith()` and merges the menu you return. This class adds a **Gift Cards** group: ```php title="app/Sidebar/GiftCardSidebar.php" namespace App\Sidebar; use Shopper\Sidebar\AbstractAdminSidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; final class GiftCardSidebar extends AbstractAdminSidebar { public function extendWith(Menu $menu): Menu { $menu->group(__('Gift Cards'), function (Group $group): void { $group->weight(5); $group->collapsible(); $group->item(__('Issued cards'), function (Item $item): void { $item->weight(1); $item->useSpa(); $item->route('shopper.gift-cards.index'); $item->setIcon('phosphor-gift'); }); $group->item(__('Redemptions'), function (Item $item): void { $item->weight(2); $item->useSpa(); $item->route('shopper.gift-cards.redemptions'); $item->setIcon('phosphor-receipt'); }); }); return $menu; } } ``` The `$this->user` property holds the signed-in user, so your extension can check permissions and roles, as shown in [Authorization](#authorization). Shopper draws its own entries with Phosphor icons (`phosphor-*`), and the admin panel styles fill every sidebar icon with the text color. Use Phosphor, or another Blade Icons set drawn with filled shapes: an outline icon, such as the Untitled UI icons that the sidebar package installs (`untitledui-*`), gets its outline filled in and shows as a solid shape. ### 2. Register the Extension [#2-register-the-extension] Register the class as a listener of `SidebarBuilder` in a service provider: ```php title="app/Providers/AppServiceProvider.php" namespace App\Providers; use App\Sidebar\GiftCardSidebar; use Illuminate\Support\ServiceProvider; use Shopper\Sidebar\SidebarBuilder; class AppServiceProvider extends ServiceProvider { public function register(): void { $this->app['events']->listen(SidebarBuilder::class, GiftCardSidebar::class); } } ``` Shopper registers its own sidebar listeners in the `register()` method of a service provider. The sidebar is built later, while the admin request runs, so a listener registered in `boot()` works too. ## Weight System [#weight-system] `weight()` orders the groups of the menu and the entries of a group, lowest first. Shopper gives its groups these weights: | Group | Label | Weight | |-------|-------|--------| | Dashboard | None, the group has no heading | 1 | | Catalog | `shopper::layout.sidebar.catalog` | 2 | | Sales | `shopper::layout.sidebar.sales` | 3 | | Customers | `shopper::pages/customers.menu` | 3 | | Settings | `shopper::pages/settings/global.menu` | 10 | Sales and Customers share the weight 3 and keep the order in which Shopper adds them, Sales first. A weight from 4 to 9 places your group between Customers and Settings, and a weight above 10 places it after Settings. To add an entry to one of Shopper's groups instead of a group of your own, call `$menu->group()` with the translated label from this table, as shown in [Sidebar Navigation](/3.x/addons/admin-panel#sidebar-navigation). ## Adding Sub-Items [#adding-sub-items] `$item->item()` adds a sub-item to an entry. Sub-items are sorted by their own weight and rendered as a nested list under the entry: ```php $group->item(__('Issued cards'), function (Item $item): void { $item->weight(1); $item->route('shopper.gift-cards.index'); $item->setIcon('phosphor-gift'); $item->item(__('All cards'), function (Item $subItem): void { $subItem->weight(1); $subItem->useSpa(); $subItem->route('shopper.gift-cards.index'); }); $item->item(__('New gift card'), function (Item $subItem): void { $subItem->weight(2); $subItem->useSpa(); $subItem->route('shopper.gift-cards.create'); }); }); ``` The item view adds the `sh-items-has-child` class to an entry that has sub-items and shows a chevron after its label: `untitledui-chevron-down`, or `untitledui-chevron-up` while the entry or one of its sub-items is active. Change them with `toggleIcon()` and `toggleActiveIcon()`. A sub-item without an icon shows a dot. ## Authorization [#authorization] Groups, entries, badges and quick actions are visible by default. `setAuthorized()` takes a boolean: with `false`, the sidebar skips the element and everything inside it. ### Permission-Based Authorization [#permission-based-authorization] Check a permission with `can()` on `$this->user`: ```php $group->item(__('Issued cards'), function (Item $item): void { $item->setAuthorized($this->user->can('gift-cards.browse')); $item->route('shopper.gift-cards.index'); $item->setIcon('phosphor-gift'); }); ``` Create the permissions before you check them: `Permission::generate('gift-cards', 'sales')` creates `gift-cards.browse`, `gift-cards.read`, `gift-cards.edit`, `gift-cards.create` and `gift-cards.delete`, as described in [Generating Permissions](/3.x/acl#generating-permissions). Use `can()` rather than `hasPermissionTo()`: `can()` returns `false` for a permission that does not exist yet, while `hasPermissionTo()` throws an exception, which breaks every admin page. ### Role-Based Authorization [#role-based-authorization] The roles of the [ACL](/3.x/acl#checking-roles) work the same way. This entry shows to administrators and to members of a `marketing` role: ```php $group->item(__('Gift card designs'), function (Item $item): void { $item->setAuthorized($this->user->isAdmin() || $this->user->hasRole('marketing')); $item->route('shopper.gift-cards.designs'); $item->setIcon('phosphor-palette'); }); ``` ## Adding Badges [#adding-badges] `badge()` adds a badge after the label of an entry and returns it. `color()` gives the badge the `sh-sidebar-item-badge-{color}` class, which the admin styles for `primary`, `success`, `warning`, `danger`, `info` and `purple`. Each call adds a new badge, so add one only when there is something to show: ```php use App\Models\GiftCard; $group->item(__('Issued cards'), function (Item $item): void { $item->route('shopper.gift-cards.index'); $item->setIcon('phosphor-gift'); $pending = GiftCard::query()->whereNull('activated_at')->count(); if ($pending > 0) { $item->badge($pending)->color('warning'); } }); ``` Shopper's **Orders** entry works this way: it shows the number of new orders in a `warning` badge. The second argument of `badge()` adds CSS classes of your own, and a closure gives access to the `Shopper\Sidebar\Contracts\Builder\Badge` instance. ## Adding Quick Actions (Append) [#adding-quick-actions-append] `append()` adds a small link after an entry, such as a button that opens a creation form. With a string, the first argument is a route name, the second the icon (`untitledui-plus` when you pass none) and the third the name, which the link shows as its title. Always pass a name: ```php $item->append('shopper.gift-cards.create', 'phosphor-plus', __('New gift card')) ->setAuthorized($this->user->can('gift-cards.create')); ``` The closure form sets the same values on the `Append` instance, and accepts route parameters, CSS classes, or a full URL with `setUrl()`: ```php use Shopper\Sidebar\Contracts\Builder\Append; $item->append(function (Append $append): void { $append->route('shopper.gift-cards.create', ['type' => 'digital']); $append->setIcon('phosphor-plus'); $append->setName(__('New digital gift card')); $append->setAuthorized($this->user->can('gift-cards.create')); }); ``` ## Complete Example [#complete-example] This extension adds a **Gift Cards** group with a badge, a quick action and sub-items, each entry checked against the `gift-cards.*` permissions: ```php title="app/Sidebar/GiftCardSidebar.php" namespace App\Sidebar; use App\Models\GiftCard; use Shopper\Sidebar\AbstractAdminSidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; final class GiftCardSidebar extends AbstractAdminSidebar { public function extendWith(Menu $menu): Menu { $menu->group(__('Gift Cards'), function (Group $group): void { $group->weight(5); $group->collapsible(); $group->item(__('Issued cards'), function (Item $item): void { $item->weight(1); $item->setAuthorized($this->user->can('gift-cards.browse')); $item->route('shopper.gift-cards.index'); $item->setIcon('phosphor-gift'); $pending = GiftCard::query()->whereNull('activated_at')->count(); if ($pending > 0) { $item->badge($pending)->color('warning'); } $item->append('shopper.gift-cards.create', 'phosphor-plus', __('New gift card')) ->setAuthorized($this->user->can('gift-cards.create')); $item->item(__('All cards'), function (Item $subItem): void { $subItem->weight(1); $subItem->useSpa(); $subItem->route('shopper.gift-cards.index'); }); $item->item(__('Expired cards'), function (Item $subItem): void { $subItem->weight(2); $subItem->useSpa(); $subItem->route('shopper.gift-cards.expired'); }); }); $group->item(__('Redemptions'), function (Item $item): void { $item->weight(2); $item->setAuthorized($this->user->can('gift-cards.read')); $item->useSpa(); $item->route('shopper.gift-cards.redemptions'); $item->setIcon('phosphor-receipt'); }); }); return $menu; } } ``` ## Using Closures for Dynamic Sidebars [#using-closures-for-dynamic-sidebars] For a few entries, a closure listener is enough. `getMenu()` on the event returns the admin menu itself, so the closure adds its group to it directly: ```php use Illuminate\Support\Facades\Event; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\SidebarBuilder; Event::listen(SidebarBuilder::class, function (SidebarBuilder $sidebar): void { $sidebar->getMenu()->group(__('Payments'), function (Group $group): void { $group->weight(20); $group->item(__('Stripe dashboard')) ->setUrl('https://dashboard.stripe.com') ->isNewTab() ->setIcon('phosphor-credit-card'); }); }); ``` ## Routes Configuration [#routes-configuration] `route()` resolves the URL while the sidebar is built, so the route must exist: a route name that does not exist throws an exception on every admin page. Put the admin routes of your application in a file of your own and set it as `custom_file` in `config/shopper/routes.php`, as described in [Custom Routes](/3.x/configuration#custom-routes): ```php title="routes/shopper.php" use App\Livewire\Shopper\GiftCards\CreateGiftCard; use App\Livewire\Shopper\GiftCards\Designs; use App\Livewire\Shopper\GiftCards\ExpiredGiftCards; use App\Livewire\Shopper\GiftCards\GiftCardIndex; use App\Livewire\Shopper\GiftCards\Redemptions; use Illuminate\Support\Facades\Route; Route::prefix('gift-cards')->name('gift-cards.')->group(function (): void { Route::livewire('/', GiftCardIndex::class)->name('index'); Route::livewire('/create', CreateGiftCard::class)->name('create'); Route::livewire('/expired', ExpiredGiftCards::class)->name('expired'); Route::livewire('/redemptions', Redemptions::class)->name('redemptions'); Route::livewire('/designs', Designs::class)->name('designs'); }); ``` Shopper loads this file inside its admin route group: the routes get the admin URL prefix, the admin middleware and the `shopper.` name prefix. The `gift-cards.index` route above is named `shopper.gift-cards.index`, and that full name is the one `route()` takes in the sidebar. # Standalone Installation (/3.x/sidebar/standalone) This guide installs the sidebar package in a Laravel application that does not run Shopper, such as a back office or a customer account area. The examples build the sidebar of a store back office. ## Installation [#installation] The package needs Livewire, as listed in [Requirements](/3.x/sidebar/overview#requirements). Install it with Composer: ```bash composer require shopper/sidebar ``` Publish the configuration file: ```bash php artisan vendor:publish --tag="sidebar-config" ``` Publish the views when you want to change their markup, as described in [Customizing Views](/3.x/sidebar/configuration#customizing-views): ```bash php artisan vendor:publish --tag="sidebar-views" ``` ## Setting Up the Middleware [#setting-up-the-middleware] The `ResolveSidebars` middleware builds the registered sidebars at the start of each request. Add it to the routes that show a sidebar: ```php use App\Livewire\Dashboard; use App\Livewire\Orders\OrderIndex; use Illuminate\Support\Facades\Route; use Shopper\Sidebar\Middleware\ResolveSidebars; Route::middleware(['auth', ResolveSidebars::class])->group(function (): void { Route::livewire('/dashboard', Dashboard::class)->name('dashboard'); Route::livewire('/orders', OrderIndex::class)->name('orders.index'); }); ``` You can also append it to the `web` middleware group in `bootstrap/app.php`. The sidebars are then built on every web request, storefront pages included: ```php use Illuminate\Foundation\Configuration\Middleware; use Shopper\Sidebar\Middleware\ResolveSidebars; ->withMiddleware(function (Middleware $middleware): void { $middleware->appendToGroup('web', [ ResolveSidebars::class, ]); }) ``` ## Creating a Sidebar [#creating-a-sidebar] A sidebar is a class that you write and register once. The middleware builds it, and the views render it. ### 1. Create a Sidebar Class [#1-create-a-sidebar-class] Implement the `Shopper\Sidebar\Contracts\Sidebar` contract. The container injects an empty menu, `build()` fills it, and `getMenu()` returns it: ```php title="app/Sidebar/StoreSidebar.php" namespace App\Sidebar; use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; use Shopper\Sidebar\Contracts\Builder\Menu; use Shopper\Sidebar\Contracts\Sidebar; final class StoreSidebar implements Sidebar { public function __construct(private Menu $menu) {} public function build(): void { $this->menu->group(__('Store'), function (Group $group): void { $group->weight(1); $group->hideHeading(); $group->item(__('Dashboard'), function (Item $item): void { $item->weight(1); $item->route('dashboard'); $item->setIcon('untitledui-home-line'); }); $group->item(__('Orders'), function (Item $item): void { $item->weight(2); $item->route('orders.index'); $item->setIcon('untitledui-shopping-bag'); $item->item(__('Returns'), function (Item $subItem): void { $subItem->weight(1); $subItem->route('returns.index'); }); $item->item(__('Abandoned carts'), function (Item $subItem): void { $subItem->weight(2); $subItem->route('carts.abandoned'); }); }); $group->item(__('Products'), function (Item $item): void { $item->weight(3); $item->route('products.index'); $item->setIcon('untitledui-package'); }); }); $this->menu->group(__('Settings'), function (Group $group): void { $group->weight(10); $group->item(__('General'), function (Item $item): void { $item->route('settings.general'); $item->setIcon('untitledui-settings-02'); }); }); } public function getMenu(): Menu { return $this->menu; } } ``` ### 2. Register the Sidebar [#2-register-the-sidebar] Register the class with the `SidebarManager` in the `boot()` method of a service provider. `register()` throws a `LogicException` when the class does not exist: ```php title="app/Providers/AppServiceProvider.php" namespace App\Providers; use App\Sidebar\StoreSidebar; use Illuminate\Support\ServiceProvider; use Shopper\Sidebar\SidebarManager; class AppServiceProvider extends ServiceProvider { public function boot(SidebarManager $manager): void { $manager->register(StoreSidebar::class); } } ``` ## Using the Sidebar [#using-the-sidebar] Render the sidebar with the Livewire component that the package registers, or pass it to the renderer in a Blade layout of your own. Both read the Alpine.js store described in [Alpine.js Store Setup](#alpinejs-store-setup). ### Option 1: Livewire Component [#option-1-livewire-component] The `sidebar` component renders a registered sidebar inside a wrapper view with a collapse button: ```blade @livewire('sidebar', [ 'sidebarClass' => \App\Sidebar\StoreSidebar::class, 'class' => 'store-sidebar', 'collapsible' => true, ]) ``` The component takes these parameters, all locked after mount: | Parameter | Default | Description | |-----------|---------|-------------| | `sidebarClass` | Required | The sidebar class registered with the `SidebarManager`. | | `class` | `''` | CSS classes on the root element of the wrapper view. | | `collapsible` | `true` | Shows the collapse button of the default wrapper view. | | `view` | `sidebar::livewire.sidebar` | The wrapper view. It receives `$sidebar`, `$renderedSidebar`, `$class` and `$collapsible`. | Pass `view` to wrap the menu in your own markup, with a logo or a store switcher, without publishing the package views: ```blade @livewire('sidebar', [ 'sidebarClass' => \App\Sidebar\StoreSidebar::class, 'view' => 'layouts.partials.sidebar', ]) ``` The item view shows the label of each entry in an `x-tooltip` while the sidebar is collapsed. Alpine.js ships no tooltip directive: the attribute does nothing until your application registers one, as Filament does. ### Refreshing the Sidebar [#refreshing-the-sidebar] The component renders the sidebar again when it receives the `sidebar:refresh` event, so a badge count can follow a change on the page. Dispatch it from a Livewire action: ```php public function markAsShipped(): void { $this->order->update(['shipped_at' => now()]); $this->dispatch('sidebar:refresh'); } ``` From Alpine.js, `$store.sidebar.refresh()` dispatches the same event: ```blade ``` The refresh runs as a Livewire update request, and Livewire applies only its persistent middleware to those requests. Add `ResolveSidebars` to them in the `boot()` method of a service provider, or the refreshed component renders an empty menu. Livewire applies it only when the route of the page has it: ```php use Livewire\Livewire; use Shopper\Sidebar\Middleware\ResolveSidebars; Livewire::addPersistentMiddleware([ResolveSidebars::class]); ``` With a cache method set, the refresh renders the cached sidebar. Flush it first, as described in [Clearing the Cache](/3.x/sidebar/configuration#clearing-the-cache). ### Option 2: Custom Blade Implementation [#option-2-custom-blade-implementation] For full control of the markup around the menu, pass the sidebar to the `Shopper\Sidebar\Presentation\SidebarRenderer` contract. The middleware has already built the sidebar, so resolve it from the container and do not call `build()` again, or every badge and quick action is added a second time: ```blade @php $renderedSidebar = app(\Shopper\Sidebar\Presentation\SidebarRenderer::class) ->render(app(\App\Sidebar\StoreSidebar::class)); @endphp ``` ## Alpine.js Store Setup [#alpinejs-store-setup] The views read the open, collapsed and active states from an Alpine.js store named `sidebar`. Livewire ships Alpine.js, and the store must be registered before Alpine starts. With Vite, publish the JavaScript sources to `resources/js/vendor/sidebar/`: ```bash php artisan vendor:publish --tag="sidebar-js" ``` Then register the store from `resources/js/app.js` when Alpine initializes: ```js title="resources/js/app.js" import { sidebarStore } from './vendor/sidebar/index.js' document.addEventListener('alpine:init', () => { window.Alpine.store('sidebar', sidebarStore()) }) ``` Without a build step, publish the compiled script to `public/vendor/sidebar/sidebar.js`: ```bash php artisan vendor:publish --tag="sidebar-assets" ``` The script exposes the same functions on `window.SidebarStore`. Load it in the `` of your layout and register the store the same way: ```blade ``` The `sidebarStore()` factory takes two options. `breakpoint` sets the width in pixels below which the sidebar works as a mobile drawer (`1024` by default). `persistKeys` renames the `localStorage` keys, so two sidebars on the same domain keep separate states. Each key you leave out keeps its default: ```js sidebarStore({ breakpoint: 1280, persistKeys: { isOpen: 'account-sidebar-is-open', isCollapsed: 'account-sidebar-is-collapsed', collapsedGroups: 'account-sidebar-collapsed-groups', }, }) ``` Alpine.js calls the store's `init()` method when the store is registered. `init()` reads the `data-sidebar-breakpoint` and `data-sidebar-collapsible` attributes of the `` set in [CSS Variables](#css-variables), and the breakpoint attribute wins over the `breakpoint` option. Do not call `init()` yourself: it adds its resize and navigation listeners again. The script exports these functions, also available on `window.SidebarStore`: | Export | Global | Description | |--------|--------|-------------| | `sidebarStore(config)` | `window.SidebarStore.store` | The store factory, also the default export. | | `registerSidebarStore(config)` | `window.SidebarStore.register` | Registers the store on `alpine:init`. Alpine.js must be loaded when you call it. | | `initSidebarStore(config)` | `window.SidebarStore.init` | Registers the store at once, for code that already runs inside an `alpine:init` listener. | | `getSidebarStore()` | `window.SidebarStore.get` | Returns the registered store, for JavaScript outside Alpine.js templates. | The three functions log an error and stop when `window.Alpine` does not exist. ### Store API [#store-api] The store keeps its state in these properties. The three states marked as saved are written to `localStorage`: | Property | Description | |----------|-------------| | `$store.sidebar.isOpen` | Whether the sidebar is open below the breakpoint. Saved. | | `$store.sidebar.isCollapsed` | Whether the sidebar is collapsed from the breakpoint up. Saved. | | `$store.sidebar.collapsedGroups` | The names of the folded groups. Saved. | | `$store.sidebar.collapsible` | Whether the sidebar can collapse, from `data-sidebar-collapsible`. | | `$store.sidebar.currentPath` | The path of the page, updated after each `wire:navigate` visit. | | `$store.sidebar.breakpoint` | The mobile breakpoint in pixels. | | `$store.sidebar.persistKeys` | The `localStorage` keys. | Its methods change the state and save it: | Method | Description | |--------|-------------| | `open()`, `close()` | Opens or closes the sidebar below the breakpoint. | | `toggle()` | Opens or closes the sidebar below the breakpoint, collapses or expands it from the breakpoint up. | | `collapse()`, `expand()`, `toggleCollapse()` | Collapses or expands the sidebar. `collapse()` adds the `sidebar-collapsed` class to the `` element and `expand()` removes it. `collapse()` and `toggleCollapse()` do nothing when `collapsible` is `false`. | | `isGroupCollapsed(label)`, `collapseGroup(label)`, `expandGroup(label)`, `toggleGroup(label)` | Reads or changes the folded state of a group, by group name. | | `refresh()` | Dispatches the `sidebar:refresh` Livewire event. | | `isActive(url, activeWhen)` | Whether the current page matches a link. | The item view calls `isActive()` with the URL of each entry and its `isActiveWhen()` pattern, so the active entry follows `wire:navigate` visits without a new render. Without a pattern, a link is active when the current path equals its path or starts with it, and the root path `/` only matches itself. A pattern is compared to the current path without its leading slash, and `*` matches any characters: ```js $store.sidebar.isActive('/orders') $store.sidebar.isActive(null, 'orders/*') ``` ## CSS Variables [#css-variables] The default wrapper view sets the sidebar width from the `--sidebar-width` and `--sidebar-collapsed-width` CSS variables. Define them from the configuration in your layout, and pass the breakpoint and the collapsible setting to the store on the ``: ```blade ``` The package ships no stylesheet. Style the `sh-*` classes of the views, such as `sh-sidebar-item`, `sh-sidebar-item-active` and `sh-si-collapsed`, in your own CSS. ## Menu Item API [#menu-item-api] The item builder sets the link, the icon, the order, the visibility and the classes of an entry. The [Item](/3.x/sidebar/overview#item) table of the overview lists every method. ### Basic Item Options [#basic-item-options] This entry sets each option: ```php use Shopper\Sidebar\Contracts\Builder\Item; $group->item(__('Orders'), function (Item $item): void { $item->route('orders.index'); $item->setIcon('untitledui-shopping-bag', iconClass: 'size-5', attributes: ['stroke-width' => '1.5']); $item->weight(2); $item->setAuthorized(auth()->user()->can('orders.browse')); $item->isActiveWhen('orders/*'); $item->useSpa(); $item->setItemClass('store-sidebar-link'); $item->setActiveClass('store-sidebar-link-active'); $item->setParentItemClass('store-sidebar-entry'); }); ``` `route()` takes a route name and its parameters, and resolves the URL while the sidebar is built: a route name that does not exist throws an exception. `setUrl()` takes any URL, such as an external link opened with `isNewTab()`. `setIcon()` takes a Blade Icons name, or raw SVG markup with `svg` as the second argument; an entry without an icon shows a dot. `isActiveWhen()` replaces the URL match with a path pattern, so Orders stays active on every order page. The store adds the active class (`sh-active` by default) to the link and `sh-sidebar-item-active` to the list element in the browser. The examples use the Untitled UI icons (`untitledui-*`) that the package installs. Any Blade Icons set works once installed: Heroicons (`heroicon-o-*`) come from the `blade-ui-kit/blade-heroicons` package, which Filament installs. ### Adding Badges [#adding-badges] `badge()` takes a value and optional CSS classes, and returns the `Shopper\Sidebar\Contracts\Builder\Badge` instance. `color()` adds the `sh-sidebar-item-badge-{color}` class, for your stylesheet to color. Each call adds a badge, and a badge without a value still renders, so add one only when there is something to show: ```php use App\Models\ProductReview; use Shopper\Sidebar\Contracts\Builder\Badge; $pendingReviews = ProductReview::query()->where('is_approved', false)->count(); if ($pendingReviews > 0) { $item->badge($pendingReviews)->color('warning'); } $item->badge(function (Badge $badge): void { $badge->setValue(__('New')); $badge->setClass('store-badge-new'); $badge->color('info'); }); ``` ### Adding Append Elements [#adding-append-elements] `append()` adds a quick action link after an entry. With a string, the first argument is a route name, the second the icon (`untitledui-plus` when you pass none) and the third the name, which the link shows as its title. Always pass a name: ```php $item->append('products.create', 'untitledui-plus', __('New product')); ``` The closure form sets the same values on the `Shopper\Sidebar\Contracts\Builder\Append` instance, and accepts route parameters, icon classes, CSS classes, authorization, or a full URL with `setUrl()`: ```php use Shopper\Sidebar\Contracts\Builder\Append; $item->append(function (Append $append): void { $append->route('products.create', ['type' => 'variant']); $append->setIcon('untitledui-plus', iconClass: 'size-4'); $append->setName(__('New product with variants')); $append->setClass('store-sidebar-append'); $append->setAuthorized(auth()->user()->can('products.create')); }); ``` The link renders with the `sh-sidebar-item-append` class and hides while the sidebar is collapsed. ### Sub-Items [#sub-items] `$item->item()` adds a sub-item, with the same builder as an entry: ```php $group->item(__('Orders'), function (Item $item): void { $item->route('orders.index'); $item->setIcon('untitledui-shopping-bag'); $item->item(__('Returns'), function (Item $subItem): void { $subItem->weight(1); $subItem->route('returns.index'); }); $item->item(__('Abandoned carts'), function (Item $subItem): void { $subItem->weight(2); $subItem->route('carts.abandoned'); }); }); ``` Sub-items render in a `ul.sh-sidebar-list-items.sh-submenu` list. The parent entry gets the `sh-items-has-child` class and a chevron, and stays active while one of its sub-items is active. ## Group API [#group-api] `$menu->group()` creates a group, or returns the group that already has that name. The group builder sets its order, its visibility and its classes: ```php use Shopper\Sidebar\Contracts\Builder\Group; use Shopper\Sidebar\Contracts\Builder\Item; $menu->group(__('Catalog'), function (Group $group): void { $group->weight(2); $group->setAuthorized(auth()->user()->can('products.browse')); $group->collapsible(); $group->setClass('store-sidebar-group'); $group->setHeadingClass('store-sidebar-heading'); $group->setGroupItemsClass('space-y-1'); $group->item(__('Products'), function (Item $item): void { $item->route('products.index'); $item->setIcon('untitledui-package'); }); }); ``` | Method | Description | |--------|-------------| | `weight($weight)` | The position of the group in the menu, lowest first. Defaults to `0`. | | `setAuthorized($authorized)` | Hides the group and its entries when `false`. | | `hideHeading()` | Hides the heading. A group with an empty name has no heading either. | | `collapsible()` | Turns the heading into a button that folds the entries. The store remembers folded groups by name. | | `setClass()`, `setHeadingClass()`, `setGroupItemsClass()` | CSS classes for the group, its heading and its list of entries. | ## Helper Functions [#helper-functions] The package defines its helpers in the `Shopper\Sidebar` namespace. Import them with `use function`: ```php use function Shopper\Sidebar\sidebar_breadcrumbs; use function Shopper\Sidebar\sidebar_breakpoint; use function Shopper\Sidebar\sidebar_collapsed_width; use function Shopper\Sidebar\sidebar_config; use function Shopper\Sidebar\sidebar_is_collapsible; use function Shopper\Sidebar\sidebar_width; $cacheMethod = sidebar_config('cache.method'); $width = sidebar_width(); $collapsedWidth = sidebar_collapsed_width(); $breakpoint = sidebar_breakpoint(); $collapsible = sidebar_is_collapsible(); $breadcrumbs = sidebar_breadcrumbs(); ``` | Function | Returns | |----------|---------| | `sidebar_config($key, $default)` | A value of `config/sidebar.php`, or the whole array without a key. | | `sidebar_width()` | The `width` option. | | `sidebar_collapsed_width()` | The `collapsed_width` option. | | `sidebar_breakpoint()` | The `breakpoint` option, as an integer. | | `sidebar_is_collapsible()` | The `collapsible` option. | | `sidebar_breadcrumbs()` | The breadcrumb trail of the current page, as a list of `Breadcrumb` objects. | ## Breadcrumbs [#breadcrumbs] The package builds a breadcrumb trail from the active entry of your sidebar, then adds the crumbs that the page pushes, such as the number of the order on screen. ### Displaying the Breadcrumbs [#displaying-the-breadcrumbs] Include the breadcrumb view in your layout, where the trail should appear: ```blade
    @include(config('sidebar.breadcrumbs.view'))
    ``` The view calls `sidebar_breadcrumbs()`, which looks for the active entry in each registered sidebar, in registration order. The trail starts with that entry and its active sub-items. The first crumb opens a dropdown with the other authorized entries of its group, and the last crumb shows as the current page. The view name comes from the `breadcrumbs.view` option, so a themed view replaces the default by configuration: the Shopper admin points it to `shopper::components.breadcrumbs`. ### Adding Page Breadcrumbs [#adding-page-breadcrumbs] A Livewire page adds its own crumbs with the `Shopper\Sidebar\Traits\WithBreadcrumbs` trait. Return them from `getBreadcrumbs()`, and the trait pushes them when the component mounts: ```php title="app/Livewire/Orders/ShowOrder.php" namespace App\Livewire\Orders; use App\Models\Order; use Illuminate\Contracts\View\View; use Livewire\Component; use Shopper\Sidebar\Breadcrumbs\Breadcrumb; use Shopper\Sidebar\Traits\WithBreadcrumbs; class ShowOrder extends Component { use WithBreadcrumbs; public Order $order; public function getBreadcrumbs(): array { return [ new Breadcrumb(text: __('Order :number', ['number' => $this->order->number])), ]; } public function render(): View { return view('livewire.orders.show-order'); } } ``` On `/orders/1042`, the trail reads **Orders** (the active entry, with its dropdown) then **Order 1042**. A pushed crumb that has the same URL as an entry of the trail replaces that entry. ### Breadcrumb Registry [#breadcrumb-registry] Outside Livewire, push crumbs to the `Shopper\Sidebar\Breadcrumbs\Breadcrumbs` registry. The container creates one registry per request: ```php use Shopper\Sidebar\Breadcrumbs\Breadcrumb; use Shopper\Sidebar\Breadcrumbs\BreadcrumbLink; use Shopper\Sidebar\Breadcrumbs\Breadcrumbs; app(Breadcrumbs::class)->push(new Breadcrumb( text: __('Reports'), url: route('reports.index'), links: [ new BreadcrumbLink(text: __('Sales'), url: route('reports.sales')), new BreadcrumbLink(text: __('Inventory'), url: route('reports.inventory')), ], )); ``` | Method | Description | |--------|-------------| | `push(Breadcrumb $crumb)` | Adds a crumb at the end of the pushed crumbs. | | `prepend(Breadcrumb $crumb)` | Adds a crumb before the pushed crumbs. | | `all()` | Returns the pushed crumbs. | | `reset()` | Removes the pushed crumbs. | | `build(Menu $menu)` | Returns the trail of a menu: its active entries, then the pushed crumbs. | A `Breadcrumb` takes a `text`, and optionally a `url`, an `icon`, a list of `BreadcrumbLink` objects for its dropdown in `links`, and `spa` (`true` by default, for `wire:navigate`). A `BreadcrumbLink` takes a `text`, a `url`, an `icon` and `spa`. A URL must start with `/`, `#`, `?`, `http://` or `https://`: any other value is dropped, so the crumb shows as text and the link points to `#`. # Livewire Starter Kit (/3.x/livewire-starter-kit) The Livewire Starter Kit is a storefront for Shopper built with [Livewire 4](https://livewire.laravel.com/) and Blade. Each page is a Livewire component that queries the Shopper models directly, so the kit does not go through the [Store API](/3.x/store-api) and there is no separate API layer to maintain. The interface uses [Flux UI](https://fluxui.dev) components and [Tailwind CSS v4](https://tailwindcss.com/), and [Laravel Fortify](https://laravel.com/docs/fortify) handles authentication. Because the Shopper admin panel is also built with Livewire, you can reuse the same patterns in your admin and your storefront. The kit is installed once, with the [starter kit installer](/3.x/starter-kits#how-it-works). Every file it copies belongs to your project afterwards. ## Prerequisites [#prerequisites] The installer checks the PHP, Laravel and Shopper versions of the kit's manifest before it copies anything, and the Vite version of the Laravel skeleton needs the Node.js versions below. Shopper must already be [installed](/3.x/installation) in the application. | Requirement | Version | |-------------|---------| | PHP | 8.3+ | | Laravel | 12.68+ or 13.27+ | | Shopper | 3.0+ | | Node.js | 20.19+ or 22.12+ | ## Installation [#installation] Run the installer in a new Laravel application where Shopper is installed, as described in [Installing a Starter Kit](/3.x/starter-kits#installing-a-starter-kit), with the package name of the kit: ```bash php artisan shopper:kit:install shopperlabs/livewire-starter-kit ``` The installer downloads the kit, reads its [manifest](/3.x/starter-kits/creating#the-manifest) and copies the storefront files into your project. On a new Laravel application, the kit replaces 13 files of the skeleton, such as `routes/web.php`, `bootstrap/app.php`, `app/Models/User.php`, `resources/css/app.css` and `config/shopper/models.php`, and the installer asks before overwriting each of them. It then installs these Composer packages: | Package | Purpose | |---------|---------| | `livewire/livewire` | Reactive server-driven components | | `livewire/flux` | UI component library (buttons, inputs, modals, cards) | | `livewire/blaze` | Folds Blade components into their parent templates for faster rendering | | `laravel/fortify` | Authentication backend (login, register, password reset, email verification, two-factor authentication) | | `danharrin/livewire-rate-limiting` | Rate limits on Livewire actions, such as adding to the cart or placing an order | | `shopper/stripe` | Stripe payment driver | It also installs `laravel/boost` as a development dependency. Once you confirm them, the installer runs the kit's post-install commands: `php artisan migrate`, which adds the two-factor authentication columns to the `users` table, and `php artisan storage:link`. It then writes a `.shopper-kit` file that lists every copied file and removes the kit package from your `composer.json`. ## First Run [#first-run] The kit ships Blade views and a stylesheet, and it uses the `vite.config.js` and `resources/js/app.js` files of the Laravel skeleton. The post-install commands do not touch npm, so run these steps from the root of your project. Install the npm packages and build the assets: ```bash npm install npm run build ``` Start the development server: ```bash php artisan serve ``` The home page, the catalog, the categories, the search, the cart and the login and register pages now answer at `http://localhost:8000`. The checkout, account and settings pages send guests to the login page. ### Store Data [#store-data] A new store has no products, so every listing renders empty until you add a catalog. Sign in to the [admin panel](/3.x/installation#access-the-admin-panel), complete the [setup wizard](/3.x/setup-store#setup-wizard), then create the data a purchase goes through: 1. A [zone](/3.x/zones) with the countries you sell to and their [currency](/3.x/currencies), such as a United States zone in USD. Enable a payment method on it, such as the cash on delivery method that Shopper seeds, and a [carrier](/3.x/carriers) with at least one shipping option, such as "Standard" at `500` cents. 2. A default [inventory location](/3.x/locations). Carrier rates are quoted from its address, and without one the checkout offers flat rates only. 3. A [category](/3.x/categories) for the storefront navigation and the "Shop by category" section of the home page. 4. A [product](/3.x/products) that is visible and published, with a price in the zone's currency and stock in the inventory location. A canvas tote bag at `2500` cents ($25.00) works. Mark it as featured to show it on the home page. With this data, the storefront selects the United States on the first visit, since it is the only country of the enabled zones. A customer adds the tote bag to the cart, registers, confirms their email address, and checks out with cash on delivery: the bag and the standard shipping make an order of `3000` cents. With the `log` mailer of a new Laravel application, the verification email is written to `storage/logs/laravel.log`. ## Project Structure [#project-structure] The starter kit publishes files into standard Laravel directories. Here is the structure it adds to your project. ```text app/ ├── Actions/ │ ├── Cart/ │ │ └── AddToCart.php │ ├── Checkout/ │ │ ├── BuildShippingPackages.php │ │ ├── CompleteCheckout.php │ │ ├── CreatePaymentSession.php │ │ ├── FetchDeliveryRates.php │ │ ├── FetchPaymentMethods.php │ │ └── RefreshShipping.php │ ├── Fortify/ │ │ ├── CreateNewUser.php │ │ └── ResetUserPassword.php │ ├── Product/ │ │ ├── BuildVariantOptions.php │ │ └── ResolveVariantAvailability.php │ ├── GetCountriesByZone.php │ └── ZoneSessionManager.php ├── Concerns/ │ ├── HandlesCartConflicts.php │ ├── PasswordValidationRules.php │ └── ProfileValidationRules.php ├── DTO/ │ ├── CountryByZoneData.php │ └── PriceData.php ├── Exceptions/ │ └── CheckoutException.php ├── Http/Controllers/ │ ├── PaymentWebhookController.php │ └── StripeReturnController.php ├── Livewire/ │ ├── Account/ │ │ ├── AddressForm.php │ │ └── Addresses.php │ ├── Actions/ │ │ └── Logout.php │ ├── Home/ │ │ ├── FeaturedCollections.php │ │ ├── FeaturedProducts.php │ │ └── ShopByCategory.php │ ├── Pages/ │ │ ├── Cart.php │ │ ├── CategoryIndex.php │ │ ├── CategoryShow.php │ │ ├── Checkout.php │ │ ├── CollectionShow.php │ │ ├── Home.php │ │ ├── ProductIndex.php │ │ ├── ProductShow.php │ │ ├── SearchProducts.php │ │ └── StripePayment.php │ ├── CartCount.php │ ├── StoreFooter.php │ ├── StoreHeader.php │ └── ZoneSelector.php ├── Models/ │ ├── Category.php │ ├── Channel.php │ ├── Product.php │ ├── ProductVariant.php │ └── User.php ├── Providers/ │ ├── AppServiceProvider.php │ └── FortifyServiceProvider.php ├── Traits/ │ └── HasProductPricing.php └── helpers.php resources/ ├── css/ │ └── app.css └── views/ ├── components/ ├── layouts/ │ ├── account.blade.php │ ├── auth.blade.php │ └── store.blade.php ├── livewire/ ├── pages/ │ ├── account/ │ ├── auth/ │ ├── home/ │ ├── settings/ │ ├── shop/ │ └── home.blade.php ├── partials/ └── dashboard.blade.php config/ ├── fortify.php ├── livewire.php └── shopper/ ├── features.php └── models.php routes/ ├── settings.php ├── web.php └── webhooks.php tests/ ├── Feature/ │ ├── Auth/ │ ├── Settings/ │ ├── Shop/ │ ├── DashboardTest.php │ └── ExampleTest.php ├── Unit/ ├── Pest.php └── TestCase.php ``` The classes of `app/Livewire/Pages` render the views of `resources/views/pages/shop` and `resources/views/pages/home.blade.php`. The `components` folder holds the Blade components shared by the pages, such as the product card, the price display, the address form fields and the order summary. The `pages/auth` folder holds the Fortify views, and `pages/account` and `pages/settings` hold single-file Livewire components. ## Routing [#routing] The starter kit defines the storefront routes in `routes/web.php`, the account settings routes in `routes/settings.php` and the payment webhook route in `routes/webhooks.php`. Every route is named, so your views can link to them with `route()`. ### Public Routes [#public-routes] These routes are open to guests. | Route | Component | Description | |-------|-----------|-------------| | `GET /` | `Pages\Home` | Homepage with featured collections, featured products and categories | | `GET /shop` | `Pages\ProductIndex` | Product catalog with search, a category filter and sorting | | `GET /shop/{product:slug}` | `Pages\ProductShow` | Product detail with variant selection | | `GET /categories` | `Pages\CategoryIndex` | All categories | | `GET /categories/{category:slug}` | `Pages\CategoryShow` | Products in a category | | `GET /collections/{collection:slug}` | `Pages\CollectionShow` | Products in a collection | | `GET /search` | `Pages\SearchProducts` | Search products, from 2 characters | | `GET /cart` | `Pages\Cart` | Shopping cart with discount codes | The cart changes run as Livewire actions on these pages, with their own limits: a customer can add a product to the cart 30 times per minute and try 5 discount codes per minute, and `GET /search` answers 30 requests per minute. Fortify registers the authentication routes, such as `/login`, `/register` and `/forgot-password`, and renders them with the views of `resources/views/pages/auth`. ### Authenticated Routes [#authenticated-routes] These routes require the user to be logged in with a verified email address. The kit's `User` model implements `MustVerifyEmail`, so a new customer confirms their email address before the checkout opens. The profile settings page requires the login only, and `/profile` redirects to it. | Route | Component | Description | |-------|-----------|-------------| | `GET /checkout` | `Pages\Checkout` | Multi-step checkout flow | | `GET /checkout/payment` | `Pages\StripePayment` | Stripe Payment Element | | `GET /checkout/payment/return` | `StripeReturnController` | Return URL of a Stripe payment, creates the order | | `GET /checkout/success/{order}` | `pages::shop.checkout-success` | Order confirmation | | `GET /account/orders` | `pages::account.orders` | Order history | | `GET /account/orders/{order}` | `pages::account.order-show` | Order detail | | `GET /account/addresses` | `Account\Addresses` | Address management | | `GET /dashboard` | `dashboard` view | Account overview, where Fortify redirects after a login or a registration | | `GET /profile/edit` | `pages::settings.profile` | Profile settings | | `GET /profile/appearance` | `pages::settings.appearance` | Light, dark or system appearance | | `GET /profile/security` | `pages::settings.security` | Password and two-factor authentication, after the password confirmation | Payment providers send their webhooks to `POST /webhooks/{driver}`, such as `/webhooks/stripe`, limited to 300 requests per minute. `bootstrap/app.php` loads this route outside the `web` middleware group, so it has no session and no CSRF check. ## Architecture [#architecture] The starter kit separates business logic in Action classes, data structures in DTOs, and the interface in Livewire components and Blade views. You can change one part of the storefront without touching the others. ### Actions [#actions] Actions are single-responsibility classes that hold the business logic. They are resolved from the container, so you can swap an implementation or add dependencies to it. Each one receives the product, the cart or the zone it works on: ```php use App\Actions\Cart\AddToCart; use App\Actions\Checkout\CompleteCheckout; use App\Actions\Checkout\FetchDeliveryRates; resolve(AddToCart::class)->handle($product, $variant, quantity: 2); resolve(FetchDeliveryRates::class)->handle($cart); resolve(CompleteCheckout::class)->handle($cart); ``` The checkout uses six actions. | Action | Responsibility | |--------|---------------| | `BuildShippingPackages` | Packs the cart lines into one package, with their total weight and the largest dimensions, for carrier rate requests | | `FetchDeliveryRates` | Quotes the carriers of the cart's zone and keeps the options in the cart's currency, with a warning for each carrier that fails | | `RefreshShipping` | Quotes the chosen delivery option again before the order is created | | `FetchPaymentMethods` | Lists the payment methods enabled on a zone that the storefront can check out with: manual methods and Stripe | | `CreatePaymentSession` | Opens a payment with the provider for the cart total, or resumes the open one when nothing changed | | `CompleteCheckout` | Turns the cart into an order | `CompleteCheckout` checks that the payment method is still available on the zone, quotes the delivery option again through `RefreshShipping`, and refuses the order when the option is gone or its price went up. It then converts the cart into an order and records the initiated payment. Called again on the same cart, it returns the order it already created, so a double submit or a refreshed Stripe return never creates two orders. On the product page, `BuildVariantOptions` lists the attributes of a product with their values and maps each variant to its values and stock. `ResolveVariantAvailability` then tells, for the options the customer selected, which values still lead to a variant in stock or open to backorders. ### DTOs [#dtos] Data Transfer Objects give a typed shape to the data passed between actions, components and views. | DTO | Purpose | |-----|---------| | `CountryByZoneData` | Selected zone and country (zone ID, code and name, country ID, name, code and flag, currency code) | | `PriceData` | Price with its comparison price and discount percentage | ### Livewire Components [#livewire-components] Each storefront page is a full-page Livewire component in `app/Livewire/Pages/`. `config/livewire.php` sets `layouts::store` as the default layout, so every page renders inside `resources/views/layouts/store.blade.php`, with the `StoreHeader` and `StoreFooter` components. The order confirmation, order history and settings pages are single-file components in `resources/views/pages/`, registered with `Route::livewire()`. The order history and settings pages, like the `Account\Addresses` component, set the `layouts.account` layout with the `#[Layout]` attribute. Components that change the cart dispatch a `cart-updated` event, which the `CartCount` component in the header listens to. The `addToCart` action of the product page shows the pattern: ```php title="app/Livewire/Pages/ProductShow.php" public function addToCart(): void { try { $this->rateLimit(30); } catch (TooManyRequestsException) { $this->dispatch('notify', type: 'error', message: __('Too many attempts. Please slow down.')); return; } $this->quantity = max(1, min($this->quantity, 10)); if ($this->product->canUseVariants() && $this->product->variants->isNotEmpty() && ! $this->selectedVariant) { $this->dispatch('notify', type: 'error', message: __('Please select all options.')); return; } try { resolve(AddToCart::class)->handle($this->product, $this->selectedVariant, $this->quantity); $this->dispatch('cart-updated'); $this->dispatch('notify', type: 'success', message: __('Product added to cart!')); } catch (InsufficientStockException) { $this->dispatch('notify', type: 'error', message: __('Insufficient stock available.')); } catch (MissingPriceException) { $this->dispatch('notify', type: 'error', message: __('This product is not available in your currency.')); } catch (QuantityRuleViolationException $exception) { $this->dispatch('notify', type: 'error', message: $exception->getMessage()); } } ``` The `notify` event shows a toast. The `HandlesCartConflicts` trait, used by the cart, product, checkout and zone components, turns a cart that another request is updating, or a payment provider that does not answer, into the same toast instead of an error page. ### Models [#models] The starter kit publishes models that extend the Shopper models. `Category`, `Channel`, `Product` and `ProductVariant` are registered in `config/shopper/models.php`, so that Shopper and its admin panel use them too. The kit also ships its own `User` model, with Fortify's `TwoFactorAuthenticatable` trait and Shopper's `InteractsWithShopper` trait. ```php title="app/Models/Product.php" namespace App\Models; use App\Traits\HasProductPricing; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; #[Scope] protected function withCurrentPrices(Builder $query): Builder { return $query->with([ 'prices' => fn ($q) => $q->whereRelation('currency', 'code', current_currency())->with('currency'), ]); } } ``` `HasProductPricing`, used by `Product` and `ProductVariant`, resolves the price of a product or variant in the current currency, for the logged-in customer and the selected zone, and returns a `PriceData` DTO. The `withCurrentPrices` scope loads only the prices in the current currency, for the listings. ### Helpers [#helpers] The `app/helpers.php` file defines three global functions used across the storefront. | Function | Purpose | |----------|---------| | `cartSession()` | Returns the current cart or creates one with the active currency, the default channel and the selected zone | | `current_currency()` | Returns the currency code for the selected zone, or the store default from `shopper_currency()` | | `current_tax_label()` | Returns the tax label ("TTC" or "HT") from the tax zone of the selected country, or an empty string when no country is selected | ## Checkout Flow [#checkout-flow] The checkout is a multi-step process handled by the `Checkout` component. Each step validates its data and saves it on the cart through Shopper's `CartManager`, so a customer who comes back to the checkout finds their address, delivery option and payment method already filled in. **Step 1 - Shipping Address.** The customer enters a new address or selects one of their saved addresses in the countries of their zone. The address is saved on the cart as the shipping and the billing address, with the country selected in the storefront. **Step 2 - Delivery Options.** `FetchDeliveryRates` builds the package with `BuildShippingPackages` and quotes the [carriers](/3.x/carriers) of the cart's zone for that address, from the default inventory location. The customer selects a delivery option. **Step 3 - Payment.** `FetchPaymentMethods` lists the [payment methods](/3.x/payments) enabled on the cart's zone. For a manual method, such as cash on delivery, placing the order runs `CompleteCheckout`, then starts the payment through Shopper's `PaymentProcessingService` and shows the confirmation page. For Stripe payments, placing the order sends the customer to `/checkout/payment`. The `StripePayment` component runs `CreatePaymentSession`, which opens a Stripe PaymentIntent for the cart total without creating an order, and renders the Stripe Payment Element. Once Stripe confirms the payment, it sends the customer back to `/checkout/payment/return`. The `StripeReturnController` retrieves the PaymentIntent and runs `CompleteCheckout` when the payment is authorized, captured or processing. When the order cannot be created, it refunds the payment and sends the customer back to the cart. The Stripe driver reads its keys from your `.env` file. The [Stripe](/3.x/payments/stripe#configuration) page describes each of them and the capture method: ```bash title=".env" STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... ``` Customers see Stripe at the checkout once a payment method with the `stripe` driver is enabled on their zone, as described in [Payment Method Setup](/3.x/payments/stripe#payment-method-setup), and once the secret key and the webhook secret are set. The payment status of the order comes from the provider's webhooks, which `PaymentWebhookController` hands to Shopper. The route answers `404` until the Stripe driver is configured. In the Stripe Dashboard, create a webhook endpoint with the URL `https://your-store.test/webhooks/stripe` and select the [events](/3.x/payments/stripe#handled-events) the driver handles. Keep the scheduler and a queue worker running, as described in [Run the Scheduler and a Queue Worker](/3.x/installation#run-the-scheduler-and-a-queue-worker): Shopper reconciles the payments it missed on a schedule. ## Zones and Currency [#zones-and-currency] The starter kit uses Shopper's [zones](/3.x/zones) for multi-currency and regional pricing. The `ZoneSelector` component in the footer lets customers pick their country among the countries of the enabled zones. On the first visit, it opens a country dialog when the zones hold more than one country, and selects the country by itself when they hold only one. The `ZoneSessionManager` then stores a `CountryByZoneData` DTO in the session, with the zone, the country and its currency. Prices across the storefront follow the zone's currency. When a customer changes country, the `ZoneSelector` moves the cart to the new zone. It removes the lines that have no price in the new currency and tells the customer, prices the other lines in the new currency, checks the discount codes again, and resets the delivery option, the payment method and any open payment session. When no country is selected, the storefront uses the default currency of your store from `shopper_currency()`, and the cart has no zone, so the checkout offers no delivery option or payment method. The `current_tax_label()` helper reads the tax zone of the selected country to display "TTC" (tax-inclusive) or "HT" (tax-exclusive) next to prices. To let customers pick a country, create at least one enabled zone in the admin panel. ## Customization [#customization] Once installed, every file belongs to your project. These are the places you will change most often. ### Styling [#styling] All pages use Flux UI components and Tailwind CSS v4. The theme lives in `resources/css/app.css`: the fonts, and the accent color that Flux uses for primary buttons, links and focus states. Change the accent variables in the `@theme` block, and in the `.dark` layer below it for dark mode: ```css title="resources/css/app.css" @theme { --color-accent: var(--color-teal-600); --color-accent-content: var(--color-teal-600); --color-accent-foreground: var(--color-white); } ``` The fonts are loaded in `resources/views/partials/head.blade.php`. The storefront header and footer are the `store-header` and `store-footer` views in `resources/views/livewire/`, and the shared Blade components, such as `product-card` and `price-display`, live in `resources/views/components/`. ### Homepage Sections [#homepage-sections] The homepage is composed of three independent Livewire components, each with its own view and cache. | Component | View | What it shows | |-----------|------|---------------| | `FeaturedCollections` | `pages/home/featured-collections.blade.php` | The three collections with the most products, cached for two hours | | `FeaturedProducts` | `pages/home/featured-products.blade.php` | Up to eight published products marked as featured, cached for 15 minutes per currency | | `ShopByCategory` | `pages/home/shop-by-category.blade.php` | Up to eight enabled root categories with products, cached for two hours | Remove or reorder these components in `resources/views/pages/home.blade.php` to change the homepage layout. ### Checkout [#checkout] The checkout actions live in `app/Actions/Checkout/`. Each one handles one concern, so you can change how shipping rates are calculated without touching the payment logic. To add a payment provider, implement it with Shopper's [payment system](/3.x/payments), register it in the admin panel, and enable it on the zones where customers can use it. `FetchPaymentMethods` only lists the drivers of its `SUPPORTED_DRIVERS` constant, `manual` and `stripe`, so add the new driver there once its payment page and return route exist. ### Adding Pages [#adding-pages] A new page takes a single-file Livewire component under `resources/views/pages/` and a named route in `routes/web.php`. The component renders in the `store` layout by default. This component sets the title of the page and renders its heading: ```blade title="resources/views/pages/about.blade.php"

    About Us

    ``` This route serves the component at `/about`, under the name `about`: ```php title="routes/web.php" Route::livewire('about', 'pages::about')->name('about'); ``` For a page with more logic, follow the class components of `app/Livewire/Pages/` and register it with `Route::get()`. ### Models [#models-1] Add methods, scopes, or relationships directly to the models in `app/Models/`. They extend the Shopper models, so everything Shopper defines on them keeps working. For example, a `featured` scope goes next to the kit's `withCurrentPrices` scope: ```php title="app/Models/Product.php" namespace App\Models; use App\Traits\HasProductPricing; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; #[Scope] protected function featured(Builder $query): Builder { return $query->where('featured', true); } } ``` # React Starter Kit (/3.x/react-starter-kit) The React Starter Kit is a storefront for Shopper built with [Inertia](https://inertiajs.com/) and [React 19](https://react.dev/). Laravel controllers query the Shopper models and pass the data to React pages as Inertia props, so the kit does not go through the [Store API](/3.x/store-api) and there is no separate API layer to maintain. The interface uses [shadcn/ui](https://ui.shadcn.com/) components and [Tailwind CSS v4](https://tailwindcss.com/), and [Laravel Wayfinder](https://github.com/laravel/wayfinder) and a PHP-to-TypeScript transformer give the pages typed routes and typed data. The kit is installed once, with the [starter kit installer](/3.x/starter-kits#how-it-works). Every file it copies belongs to your project afterwards. ## Prerequisites [#prerequisites] The installer checks the PHP, Laravel and Shopper versions of the kit's manifest before it copies anything, and the kit's Vite version needs the Node.js versions below. Shopper must already be [installed](/3.x/installation) in the application. | Requirement | Version | |-------------|---------| | PHP | 8.3+ | | Laravel | 12.68+ or 13.27+ | | Shopper | 3.0+ | | Node.js | 20.19+ or 22.12+ | ## Installation [#installation] Create a Laravel application and install Shopper as described in [Installing a Starter Kit](/3.x/starter-kits#installing-a-starter-kit), then run the installer with the package name of the kit: ```bash php artisan shopper:kit:install shopperlabs/react-starter-kit ``` The installer downloads the kit, reads its [manifest](/3.x/starter-kits/creating#the-manifest) and copies the storefront files into your project. On a new Laravel application, the kit replaces 14 files of the skeleton, such as `routes/web.php`, `bootstrap/app.php`, `app/Models/User.php`, `package.json` and `config/shopper/models.php`, and the installer asks before overwriting each of them. It then installs these Composer packages: | Package | Purpose | |---------|---------| | `inertiajs/inertia-laravel` | Inertia server-side adapter for Laravel | | `laravel/fortify` | Authentication backend (login, register, password reset, two-factor authentication) | | `laravel/wayfinder` | Typed route functions generated from your routes | | `spatie/laravel-typescript-transformer` | TypeScript types generated from the PHP DTOs | | `shopper/stripe` | Stripe payment driver | It also installs `laravel/boost` and `laravel/pao` as development dependencies. Once you confirm them, the installer runs the kit's post-install commands: `php artisan migrate`, `php artisan storage:link`, `npm install` and `npm run build`. It then writes a `.shopper-kit` file that lists every copied file and removes the kit package from your `composer.json`. ## First Run [#first-run] The post-install commands have already migrated the database, linked the storage folder and built the front-end assets, so you can start the development server: ```bash php artisan serve ``` The home page, the catalog, the categories, the search, the cart and the login and register pages answer at `http://localhost:8000`. The checkout, account and settings pages send guests to the login page. The assets are built into `public/build`. When you change a file in `resources/js` or `resources/css`, build them again with `npm run build`, or keep `npm run dev` running while you work so Vite serves the assets and updates the page as you edit. ### Store Data [#store-data] A new store has no products, so every listing renders empty until you add a catalog. Sign in to the [admin panel](/3.x/installation#access-the-admin-panel), complete the [setup wizard](/3.x/setup-store#setup-wizard), then create the data a purchase goes through: 1. A [zone](/3.x/zones) with the countries you sell to and their [currency](/3.x/currencies), such as a North America zone with the United States and Canada in USD. Enable a payment method on it, such as the cash on delivery method that Shopper seeds, and a [carrier](/3.x/carriers) with at least one shipping option, such as "Standard shipping" at `500` cents. 2. A [category](/3.x/categories) for the storefront navigation. 3. A [product](/3.x/products) that is published, with a price in the zone's currency and stock in an [inventory location](/3.x/locations). A canvas tote bag at `2500` cents ($25.00) works. Mark it as featured to show it on the home page. With this data, a customer picks the United States in the country dialog that opens on their first visit, adds two tote bags to the cart, registers, and checks out with cash on delivery: the two bags and the standard shipping make an order of `5500` cents. ### Stripe [#stripe] The installer added the `shopper/stripe` package, and the checkout of the kit already renders the Stripe payment step. Add the keys of your Stripe account to `.env`, using the test keys while you build the store: ```bash title=".env" STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_CAPTURE_METHOD=manual ``` Shopper offers Stripe once the secret key and the webhook secret are set, and the payment step needs the publishable key to load the Stripe Payment Element. [Configuration](/3.x/payments/stripe#configuration) describes each variable. Then create a payment method with the Stripe driver and enable it on your zones, as described in [Payment Method Setup](/3.x/payments/stripe#payment-method-setup). Stripe sends its webhooks to the kit's endpoint, `https://your-store.test/webhooks/stripe`. Create it in the Stripe Dashboard with the events listed in [Handled Events](/3.x/payments/stripe#handled-events), and copy its signing secret into `STRIPE_WEBHOOK_SECRET`. ## Project Structure [#project-structure] The starter kit publishes files into standard Laravel directories. Here is the structure it adds to your project. ```text app/ ├── Actions/ │ ├── Cart/ │ │ └── AddToCart.php │ ├── Checkout/ │ │ ├── BuildShippingPackages.php │ │ ├── CompleteCheckout.php │ │ ├── CreatePaymentSession.php │ │ ├── FetchDeliveryRates.php │ │ └── FetchPaymentMethods.php │ ├── Fortify/ │ │ ├── CreateNewUser.php │ │ └── ResetUserPassword.php │ ├── Product/ │ │ ├── BuildVariantOptions.php │ │ └── ResolveVariantAvailability.php │ ├── GetCountriesByZone.php │ └── ZoneSessionManager.php ├── Concerns/ │ ├── InteractsWithStorefrontMedia.php │ ├── PasswordValidationRules.php │ └── ProfileValidationRules.php ├── DTO/ │ ├── AddressData.php │ ├── CountryByZoneData.php │ ├── PriceData.php │ └── ProductReviewsData.php ├── Exceptions/ │ └── CheckoutException.php ├── Http/ │ ├── Controllers/ │ │ ├── Account/ │ │ ├── Settings/ │ │ ├── Shop/ │ │ ├── PaymentWebhookController.php │ │ └── StripeReturnController.php │ ├── Middleware/ │ │ ├── HandleAppearance.php │ │ └── HandleInertiaRequests.php │ └── Requests/Settings/ ├── Models/ │ ├── Category.php │ ├── Channel.php │ ├── Collection.php │ ├── Product.php │ ├── ProductVariant.php │ └── User.php ├── Providers/ │ ├── AppServiceProvider.php │ ├── FortifyServiceProvider.php │ └── TypeScriptTransformerServiceProvider.php ├── Traits/ │ └── HasProductPricing.php └── helpers.php resources/js/ ├── components/ │ ├── account/ │ ├── shop/ │ └── ui/ ├── hooks/ ├── layouts/ ├── lib/ ├── pages/ │ ├── account/ │ ├── auth/ │ ├── settings/ │ ├── shop/ │ └── dashboard.tsx ├── types/ └── app.tsx routes/ ├── settings.php ├── web.php └── webhooks.php tests/ ├── Feature/Auth/ ├── Feature/Settings/ ├── Feature/Shop/ └── Unit/ ``` The `Account`, `Settings` and `Shop` controllers render the matching folders of `resources/js/pages`. The `components/shop` folder holds the product cards, the price display, the zone selector and the Stripe form, and `components/ui` the shadcn/ui primitives. The `hooks` folder holds `useCart`, `useShop`, `useStripeElements` and `useAppearance`, among others. ## Routing [#routing] The starter kit defines the storefront routes in `routes/web.php`, the account settings routes in `routes/settings.php` and the payment webhook route in `routes/webhooks.php`. Each page is rendered by a controller that returns an Inertia response, and every route is named so your React components can call it through Wayfinder. ### Public Routes [#public-routes] These routes are open to guests. | Route | Controller | Description | |-------|-----------|-------------| | `GET /` | `Shop\HomeController` | Homepage with featured collections, products, and categories | | `GET /shop` | `Shop\ProductController@index` | Product catalog with search, a category filter and sorting | | `GET /shop/{product:slug}` | `Shop\ProductController@show` | Product detail with variant selection | | `GET /categories` | `Shop\CategoryController@index` | All categories | | `GET /categories/{category:slug}` | `Shop\CategoryController@show` | Products in a category | | `GET /collections/{collection:slug}` | `Shop\CollectionController@show` | Products in a collection | | `GET /search` | `Shop\SearchController` | Search products by name, from 2 characters | | `GET /cart` | `Shop\CartController@index` | Shopping cart | Cart mutations have their own endpoints, limited to 60 requests per minute: `POST /cart` adds a line, `PATCH /cart/{line}` updates a quantity, `DELETE /cart/{line}` removes a line, and `DELETE /cart` clears the cart. `POST /cart/coupon` applies a discount code, with at most 5 attempts per minute for each customer, and `DELETE /cart/coupon/{code}` removes it. `PATCH /zone` changes the country of the visitor, and `GET /search` answers 30 requests per minute. ### Authenticated Routes [#authenticated-routes] These routes require the user to be logged in. They also carry Laravel's `verified` middleware, which only checks the email address when the `User` model implements `MustVerifyEmail`. The kit's model does not, so a customer can check out right after registering. The profile settings page requires the login only. | Route | Controller | Description | |-------|-----------|-------------| | `GET /checkout` | `Shop\CheckoutController@index` | Multi-step checkout flow | | `GET /checkout/stripe-return` | `StripeReturnController` | Return URL of a Stripe payment, creates the order | | `GET /checkout/success/{order}` | `Shop\CheckoutSuccessController` | Order confirmation | | `GET /account/orders` | `Account\OrderController@index` | Order history | | `GET /account/orders/{order}` | `Account\OrderController@show` | Order detail | | `GET /account/addresses` | `Account\AddressController@index` | Address management | | `GET /dashboard` | Inertia page | Page Fortify redirects to after a login with no page to return to | | `GET /settings/profile` | `Settings\ProfileController@edit` | Profile settings | | `GET /settings/appearance` | Inertia page | Light and dark appearance | | `GET /settings/security` | `Settings\SecurityController@edit` | Password and two-factor authentication, after the password confirmation | The checkout posts each step to its own endpoint: `checkout/shipping-address`, `checkout/shipping-option`, `checkout/prepare-payment` and `checkout/place-order`. Payment providers send their webhooks to `POST /webhooks/{driver}`, such as `/webhooks/stripe`, limited to 300 requests per minute. `bootstrap/app.php` loads this route outside the `web` middleware group, so it has no session and no CSRF check. ## Architecture [#architecture] The starter kit separates business logic in Action classes, data structures in DTOs, HTTP handling in controllers, and the interface in React components. You can change one part of the storefront without touching the others. ### Actions [#actions] Actions are single-responsibility classes that hold the business logic. They are resolved from the container, so you can swap an implementation or add dependencies to it. Each one receives the product, the cart or the zone it works on: ```php use App\Actions\Cart\AddToCart; use App\Actions\Checkout\CompleteCheckout; use App\Actions\Checkout\FetchDeliveryRates; resolve(AddToCart::class)->handle($product, $variant, quantity: 2); resolve(FetchDeliveryRates::class)->handle($cart); resolve(CompleteCheckout::class)->handle($cart); ``` The checkout uses five actions. | Action | Responsibility | |--------|---------------| | `BuildShippingPackages` | Packs the cart lines into one package, with their total weight and the largest dimensions, for carrier rate requests | | `FetchDeliveryRates` | Quotes the carriers of the cart's zone and keeps the options in the cart's currency, with a warning for each carrier that fails | | `FetchPaymentMethods` | Lists the payment methods enabled on a zone that the storefront can check out with: manual methods and Stripe | | `CreatePaymentSession` | Opens a payment session with the provider for the cart total, or resumes the open one when the amount and currency are unchanged | | `CompleteCheckout` | Turns the cart into an order | `CompleteCheckout` checks that the payment method is still available on the zone, quotes the delivery option again, and refuses the order when the option is gone or its price went up. It then converts the cart into an order and records the initiated payment. Called again on the same cart, it returns the order it already created, so a double submit or a refreshed Stripe return never creates two orders. ### DTOs [#dtos] Data Transfer Objects give a typed shape to the data passed from the backend to the React pages. Each one carries the `#[TypeScript]` attribute, so the TypeScript Transformer turns it into a type your components can import. | DTO | Purpose | |-----|---------| | `AddressData` | Structured address data for forms and checkout | | `CountryByZoneData` | Selected zone and country (zone ID, code and name, country ID, name, code and flag, currency code) | | `PriceData` | Price with its comparison price and discount percentage | | `ProductReviewsData` | Product reviews with the average rating and the review count | ### Controllers [#controllers] Each storefront page is rendered by a controller in `app/Http/Controllers/`. Controllers query the Shopper models and return an Inertia response that renders the matching page component. The `show` method of the product page returns a 404 for an unpublished product, then loads the brand, the media, the related products and the variants, each with its prices in the current currency, before it renders `shop/product`: ```php title="app/Http/Controllers/Shop/ProductController.php" $currencyCode = current_currency(); $priceConstraint = fn ($q) => $q->whereRelation('currency', 'code', $currencyCode); $product->load([ 'brand', 'media', 'prices' => $priceConstraint, 'relatedProducts.brand', 'relatedProducts.media', 'relatedProducts.prices' => $priceConstraint, 'variants.media', 'variants.values.attribute', 'variants.prices' => $priceConstraint, ]); ``` To change what a page receives, edit its controller. To change how it looks, edit the matching page component in `resources/js/pages/`. ### Inertia Shared Data [#inertia-shared-data] The `HandleInertiaRequests` middleware shares data with every page, so your components can read the authenticated user and the current shop state without fetching them. The `shop` prop carries the cart count, the selected zone, the active currency, the enabled channels, the countries a visitor can pick, the tax label, and the categories of the header and footer navigation. ```php title="app/Http/Middleware/HandleInertiaRequests.php" return [ 'cart_count' => $cart?->lines->sum('quantity') ?? 0, 'zone' => $zone ? [ 'country_code' => $zone->countryCode, 'country_name' => $zone->countryName, 'currency_code' => $zone->currencyCode, 'zone_id' => $zone->zoneId, ] : null, 'currency' => current_currency(), 'channels' => Channel::query() ->scopes('enabled') ->select('id', 'name', 'slug') ->get() ->toArray(), 'available_zones' => fn (): array => resolve(GetCountriesByZone::class)->handle()->values()->toArray(), 'tax_label' => current_tax_label(), 'nav_categories' => $this->topCategories(4, 'nav'), 'footer_categories' => $this->topCategories(6, 'footer'), ]; ``` On the frontend, the `useShop` hook reads this shared data and changes the country with `changeZone`, and `useCart` exposes the `add`, `update`, `remove` and `clear` cart actions. ### Models [#models] The starter kit publishes models that extend the Shopper models. `Category`, `Channel`, `Collection`, `Product` and `ProductVariant` are registered in `config/shopper/models.php`, so that Shopper and its admin panel use them too. The kit also ships its own `User` model. ```php title="app/Models/Product.php" namespace App\Models; use App\Concerns\InteractsWithStorefrontMedia; use App\Traits\HasProductPricing; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; use InteractsWithStorefrontMedia; #[Scope] protected function withCurrentPrices(Builder $query): Builder { return $query->with([ 'prices' => fn ($q) => $q->whereRelation('currency', 'code', current_currency())->with('currency'), ]); } } ``` `HasProductPricing` resolves the price of a product or variant in the current currency, for the logged-in customer and the selected zone. The `withCurrentPrices` scope loads only the prices in the current currency, for the listings. The `InteractsWithStorefrontMedia` trait appends `thumbnail` and `images` attributes to every JSON response, so your React components receive media URLs ready to render. ### Helpers [#helpers] The `app/helpers.php` file defines four global functions used across the storefront. | Function | Purpose | |----------|---------| | `cartSession()` | Returns the current cart or creates one with the active currency, the default channel and the selected zone | | `current_currency()` | Returns the currency code for the selected zone, or the store default from `shopper_currency()` | | `current_tax_label()` | Returns the tax label ("TTC" or "HT") from the tax zone of the selected country, or an empty string when no country is selected | | `cart_context()` | Returns the cart totals the pages display: subtotal, discount, tax, shipping and total, whether prices include tax, and the subtotal of each line | ### Type Safety [#type-safety] Three tools give your React components the shape of the backend data, so they never guess it. | Tool | What it provides | |------|------------------| | Wayfinder | Typed functions for the named routes and the controller actions, generated into `resources/js/routes` and `resources/js/actions` by its Vite plugin when the assets build | | TypeScript Transformer | TypeScript definitions of the PHP DTOs, written to `resources/js/types/generated.d.ts` | | `@shopperlabs/shopper-types` | Shared domain types (Address, Cart, Order, Product, Zone and more) published as an npm package | The `TypeScriptTransformerServiceProvider` configures the transformer. After you change a DTO, regenerate the types: ```bash php artisan typescript:transform ``` ## Checkout Flow [#checkout-flow] The checkout is a multi-step process handled by `CheckoutController`. Each step posts to its own endpoint, validates its data and saves it on the cart through Shopper's `CartManager`, so a customer who comes back to the checkout resumes at the step they reached. **Step 1 - Shipping Address.** The customer enters a new address or selects one of their saved addresses in the countries of their zone. The address is saved on the cart as the shipping and the billing address, with the country selected in the storefront. **Step 2 - Delivery Options.** `FetchDeliveryRates` builds the package with `BuildShippingPackages` and quotes the [carriers](/3.x/carriers) of the cart's zone for that address, from the default inventory location. The customer selects a delivery option. **Step 3 - Payment.** `FetchPaymentMethods` lists the [payment methods](/3.x/payments) enabled on the cart's zone. For a manual method, such as cash on delivery, placing the order runs `CompleteCheckout`, then starts the payment through Shopper's `PaymentProcessingService` and shows the confirmation page. For Stripe payments, choosing the method runs `CreatePaymentSession`, which opens a Stripe PaymentIntent for the cart total without creating an order, and the payment step renders the Stripe Payment Element through the `StripePaymentForm` component and the `useStripeElements` hook. Once Stripe confirms the payment, it sends the customer back to `/checkout/stripe-return`. The `StripeReturnController` retrieves the PaymentIntent and runs `CompleteCheckout` when the payment is authorized, captured or processing. When the order cannot be created, it cancels the authorization or refunds the capture. The payment status of the order comes from the provider's webhooks, which `PaymentWebhookController` hands to Shopper. The route answers `404` until the Stripe driver is configured, as described in [Stripe](#stripe). Keep the scheduler running, as described in [Run the Scheduler and a Queue Worker](/3.x/installation#run-the-scheduler-and-a-queue-worker): Shopper applies the events that arrived before their order existed on a schedule. ## Zones and Currency [#zones-and-currency] The starter kit uses Shopper's [zones](/3.x/zones) for multi-currency and regional pricing. The `ZoneSelector` component in the footer lets customers pick their country among the countries of the enabled zones. The `ZoneSessionManager` then stores the country code in the session and resolves it to a `CountryByZoneData` DTO with the zone, the country and its currency. Prices across the storefront follow the zone's currency through the shared `shop` prop. When a customer changes country, `ZoneSessionManager` moves the cart to the new zone. It removes the lines that have no price in the new currency and tells the customer, prices the other lines in the new currency, and resets the delivery option, the payment method and any open payment session. When no country is selected, the storefront uses the default currency of your store from `shopper_currency()`, and the cart has no zone, so the checkout offers no delivery option or payment method. The `current_tax_label()` helper reads the tax zone of the selected country to display "TTC" (tax-inclusive) or "HT" (tax-exclusive) next to prices. To let customers pick a country, create at least one enabled zone in the admin panel. ## Customization [#customization] Every file the kit copied belongs to your project, so you customize the storefront by editing it. The React code lives in `resources/js`, the theme in `resources/css/app.css`, and the data each page receives in the controllers of `app/Http/Controllers`. ### Styling [#styling] The theme is a set of CSS variables in `resources/css/app.css`. The `:root` block holds the light colors and the `.dark` block the dark ones, and the `@theme` block maps each variable to a Tailwind color, so `--primary` becomes the `bg-primary` and `text-primary` utilities. To change the brand color, change `--primary` in both blocks: ```css title="resources/css/app.css" :root { --primary: oklch(0.6 0.118 184.704); } .dark { --primary: oklch(0.704 0.14 182.503); } ``` The same file sets the corner radius of the components with `--radius` and the font with `--font-sans`. The kit loads Instrument Sans from Bunny Fonts in `vite.config.ts`, so change both files when you switch fonts. Some pages, such as `resources/js/pages/shop/home.tsx`, also use Tailwind's `zinc` colors directly, and `resources/js/app.tsx` sets the color of the Inertia progress bar. The primitives in `resources/js/components/ui` are [shadcn/ui](https://ui.shadcn.com/) components, and `components.json` configures the shadcn CLI for the kit's paths. To add a component, run the CLI from the root of your project: ```bash npx shadcn@latest add switch ``` The CLI writes the component to `resources/js/components/ui/switch.tsx`, and your pages import it like the others: ```tsx import { Switch } from '@/components/ui/switch'; ``` ### Pages [#pages] Each page is a React component in `resources/js/pages`, grouped by area: | Folder | Pages | |--------|-------| | `pages/shop` | Home, catalog, product, cart, checkout, order confirmation, categories, category, collection and search | | `pages/account` | Order history, order detail and addresses | | `pages/settings` | Profile, security and appearance | | `pages/auth` | Login, register, password reset and confirmation, email verification and two-factor challenge | | `pages/dashboard.tsx` | Account overview | `resources/js/app.tsx` picks the layout of each page from its name: | Page name | Layout | |-----------|--------| | `shop/*` | `StorefrontLayout`, with the store header and footer | | `account/*` and `dashboard` | `StorefrontLayout` and `AccountLayout`, the account navigation | | `settings/*` | `StorefrontLayout`, `AccountLayout` and `SettingsSubLayout` | | `auth/*` | `AuthLayout` | | Any other name | `AppLayout`, a sidebar layout | The store header and footer live in `resources/js/layouts/storefront/store-header.tsx` and `store-footer.tsx`. Edit them to change the logo, the navigation or the footer links. To change the data a page receives, edit its controller. The home page, for example, receives its `featuredProducts`, `featuredCollections` and `categories` props from `app/Http/Controllers/Shop/HomeController.php`. ### Checkout [#checkout] The checkout is a single page, `resources/js/pages/shop/checkout.tsx`, that renders the three steps and lets the customer go back to a step they completed. The Stripe form is the `resources/js/components/shop/stripe-payment-form.tsx` component, and `resources/js/hooks/use-stripe-elements.ts` loads Stripe.js and mounts the Payment Element. On the server, each concern has its own action in `app/Actions/Checkout`, as described in [Actions](#actions), so you can change how shipping rates are quoted without touching the payment logic. To add a payment provider, implement it with Shopper's [payment system](/3.x/payments), create its payment method in the admin panel, and enable it on the zones where customers can use it. `FetchPaymentMethods` only lists the drivers of its `SUPPORTED_DRIVERS` constant, `manual` and `stripe`, so add the new driver there once its payment step and return page exist. ### Adding Pages [#adding-pages] A new page takes a controller, a named route in `routes/web.php` and a React component in `resources/js/pages`. Name it under `shop/` so it renders inside the store header and footer. This controller renders the `shop/about` page: ```php title="app/Http/Controllers/Shop/AboutController.php" name('shop.about'); ``` This component renders the title of the page inside the `Container` of the storefront: ```tsx title="resources/js/pages/shop/about.tsx" import { Head } from '@inertiajs/react'; import Container from '@/components/shop/container'; export default function About() { return ( <>

    About Us

    ); } ``` The next asset build adds an `about` function to `resources/js/routes/shop`, so the header or any other page can link to the page with `shop.about.url()`, after `import * as shop from '@/routes/shop'`. ### Models [#models-1] Add methods, scopes or relationships to the models in `app/Models`. As described in [Models](#models), `config/shopper/models.php` registers them, so Shopper and its admin panel work with your version. For example, add a `featured` scope next to `withCurrentPrices` in the product model: ```php title="app/Models/Product.php" final class Product extends Model { #[Scope] protected function featured(Builder $query): void { $query->where('featured', true); } } ``` The home page query in `HomeController` can then call `->featured()` in place of `->where('featured', true)`. # Authentication (/3.x/sdk/authentication) A visitor browses and buys as a guest without any call to `sdk.auth`. Registering or logging in gives the client a customer token, and the client then sends it with every request, so the cart, the profile and the order history belong to that customer. The [Authentication](/3.x/store-api/authentication) guide of the Store API describes the endpoints, the token lifetime and the error codes behind these methods. ## Registering a Customer [#registering-a-customer] `register()` creates the account and logs the customer in. Pass the ID of the guest cart in `cart_id` to keep the products added before signing up. Here, the sign-up form creates the account and keeps the guest cart: ```ts import { sdk } from '@/lib/shopper' const customer = await sdk.auth.register({ first_name: 'Amara', last_name: 'Ndiaye', email: 'amara@example.com', password: 'correct-horse-battery-staple', opt_in: true, cart_id: storedCartId, }) customer.email // 'amara@example.com' ``` The method returns the customer and stores the token in the client. `getCartId()` then gives the cart of the account, which is not always the ID you sent: the API merges the guest cart into the cart the customer already has, as [What Happens to the Guest Cart](/3.x/store-api/authentication#what-happens-to-the-guest-cart) explains. After the call, save that ID in place of the cart ID your storefront kept, or remove it when the customer has no cart: ```ts const cartId = sdk.auth.getCartId() if (cartId) { localStorage.setItem('shopper_cart', cartId) } else { localStorage.removeItem('shopper_cart') } ``` The client keeps this ID in memory only, until the next login or logout. Your storefront stores the cart ID itself, where it keeps the token. ## Logging In [#logging-in] `login()` takes the email, the password and the same optional `cart_id`. Like `register()`, it stores the token and sets `getCartId()`. Without `cart_id`, `getCartId()` gives the latest open cart of the customer, or `null` when there is none. The login form sends the email, the password and the guest cart: ```ts const customer = await sdk.auth.login({ email: 'amara@example.com', password: 'correct-horse-battery-staple', cart_id: storedCartId, }) ``` Wrong credentials throw a `ShopperApiError` with status `422` and the `credentials_invalid` code on the `email` field, and repeated failures throw one with status `429` and the `rate_limited` code. The [Errors](/3.x/sdk/errors) page shows how to read them. ## Persisting the Token [#persisting-the-token] The client keeps the token in memory by default, so a page reload logs the customer out. The `tokenStorage` option gives the client an object with three synchronous methods, `get()`, `set()` and `clear()`, that keep the token where your storefront needs it. ### In the Browser [#in-the-browser] A single-page storefront with no server of its own keeps the token in `localStorage`, so it survives reloads and new tabs. This client reads the token from `localStorage`, saves it there after a login and removes it at logout: ```ts title="lib/shopper.ts" import Shopper from '@shopperlabs/shopper-sdk' export const sdk = new Shopper({ baseUrl: import.meta.env.VITE_SHOPPER_URL, tokenStorage: { get: () => localStorage.getItem('shopper_token'), set: (token) => localStorage.setItem('shopper_token', token), clear: () => localStorage.removeItem('shopper_token'), }, }) ``` Any script that runs on the page can read `localStorage`, so a cross-site scripting flaw exposes the token. A storefront that has a server keeps the token in an `HttpOnly` cookie instead, out of reach of scripts. The storage is synchronous. On React Native, where secure storage such as `expo-secure-store` is asynchronous, read the token once when the app starts, before the first request, and serve it from memory. Here, `restoreToken()` loads the token from secure storage, and the client reads it from a variable and writes each change back to secure storage: ```ts title="lib/shopper.ts" import Shopper from '@shopperlabs/shopper-sdk' import * as SecureStore from 'expo-secure-store' let token: string | null = null export async function restoreToken() { token = await SecureStore.getItemAsync('shopper_token') } export const sdk = new Shopper({ baseUrl: process.env.EXPO_PUBLIC_SHOPPER_URL!, tokenStorage: { get: () => token, set: (value) => { token = value void SecureStore.setItemAsync('shopper_token', value) }, clear: () => { token = null void SecureStore.deleteItemAsync('shopper_token') }, }, }) ``` ### On a Server [#on-a-server] A storefront rendered on a server, such as Next.js, logs the customer in from a server action and keeps the token in an `HttpOnly` cookie. A new client is created for the call, so the token of one visitor never reaches another. This server action logs the customer in, saves the token and the cart ID in cookies, then opens the account page: ```ts title="app/login/actions.ts" 'use server' import Shopper from '@shopperlabs/shopper-sdk' import { cookies } from 'next/headers' import { redirect } from 'next/navigation' export async function login(formData: FormData) { const sdk = new Shopper({ baseUrl: process.env.SHOPPER_URL! }) const store = await cookies() await sdk.auth.login({ email: String(formData.get('email')), password: String(formData.get('password')), cart_id: store.get('shopper_cart')?.value, }) const options = { httpOnly: true, secure: true, sameSite: 'lax', path: '/' } as const store.set('shopper_token', sdk.auth.getToken()!, options) const cartId = sdk.auth.getCartId() if (cartId) { store.set('shopper_cart', cartId, options) } redirect('/account') } ``` Each later request creates its own client with the token of the cookie. The `shopper()` function below reads the cookie and sends the token in the `Authorization` header. Without a cookie, the client calls the API as a guest: ```ts title="lib/shopper.ts" import Shopper from '@shopperlabs/shopper-sdk' import { cookies } from 'next/headers' export async function shopper() { const token = (await cookies()).get('shopper_token')?.value return new Shopper({ baseUrl: process.env.SHOPPER_URL ?? 'http://localhost:8000', headers: token ? { Authorization: `Bearer ${token}` } : {}, }) } ``` A page of the account calls `shopper()` to get the client of the request, then reads the profile of the logged-in customer to greet them: ```ts title="app/account/page.tsx" import { shopper } from '@/lib/shopper' export default async function AccountPage() { const sdk = await shopper() const customer = await sdk.store.customer.me() return

    Welcome back, {customer.first_name}

    } ``` ## When the Token Expires [#when-the-token-expires] A token stays valid for 30 days by default, and there is no refresh endpoint, as [Token Expiration](/3.x/store-api/authentication#token-expiration) describes. When a request that carried a token answers `401`, the client clears the stored token, calls `onUnauthorized`, then throws the `ShopperApiError`. Send the customer to the login page from there. This client opens `/login` when the token has expired: ```ts title="lib/shopper.ts" export const sdk = new Shopper({ baseUrl: import.meta.env.VITE_SHOPPER_URL, onUnauthorized: () => { window.location.assign('/login') }, }) ``` A request sent without a token never calls it, and neither does a `403`. A public route with an expired token runs as a guest, so the customer's own cart answers `404` instead of `401`: treat a `404` on a cart you know belongs to the customer the same way. Keep the cart ID, because logging in again with `cart_id` attaches the cart back. `getToken()` returns the stored token, or `null`. The header of the shop uses it to know whether a customer is logged in, and shows the account menu or the login link: ```ts const loggedIn = sdk.auth.getToken() !== null ``` ## Logging Out [#logging-out] `logout()` revokes the token on the server, then clears the token and the cart ID from the client, even when the request fails. The logout button calls it, then forgets the cart ID the storefront kept: ```ts await sdk.auth.logout() localStorage.removeItem('shopper_cart') ``` The customer's cart stays attached to the account and comes back from `getCartId()` at the next login. Forget the cart ID on logout, or the next visitor on the same device would read a cart that now answers `404`. ## Resetting a Password [#resetting-a-password] A password reset takes two calls. The "Forgot password" form sends the email, and the API emails a link to the reset page of your storefront. The Laravel application sets that link, as described in [Resetting a Password](/3.x/store-api/authentication#resetting-a-password). The form sends the email the customer typed: ```ts await sdk.auth.forgotPassword('amara@example.com') ``` The reset page reads the token and the email from its URL, and sends them with the new password the customer typed: ```ts const params = new URLSearchParams(window.location.search) await sdk.auth.resetPassword({ email: params.get('email')!, token: params.get('token')!, password: 'new-correct-horse-battery-staple', }) ``` The customer then logs in with the new password. An expired or used link throws a `ShopperApiError` with the `reset_token_invalid` code on the `email` field: offer to send a new link. ## Next Steps [#next-steps] Read the code and the field messages of a failed login or registration. Read and update the profile, the avatar and the saved addresses of the logged-in customer. # Cart (/3.x/sdk/cart) The cart holds what the visitor is about to buy, priced for their zone and currency, with the totals the basket page shows. The storefront creates it at the first "Add to cart", keeps its ID, and passes that ID to every cart method. The [Cart](/3.x/store-api/cart) guide of the Store API describes the cart resource, its totals and every error code. Every cart method that returns a cart includes its lines by default. Pass `include` to ask for more, or `include: []` for the cart without its lines. ## Creating a Cart [#creating-a-cart] `cart.create()` creates an empty cart in the zone of the client, or in the default zone when the client sends no `X-Shopper-Zone` header. It takes an optional currency, email and metadata. Here, the first "Add to cart" creates a cart in euros and keeps its ID in the browser: ```ts import { sdk } from '@/lib/shopper' const cart = await sdk.store.cart.create({ currency_code: 'EUR' }) localStorage.setItem('shopper_cart', cart.id) ``` A cart created with the customer token belongs to that customer, and one created without it is a guest cart. The ID of a guest cart works like a session token: anyone who has it can read and change the cart. Keep it where the session lives, such as a cookie or the storage of the app, and out of URLs, as [Guest and Customer Carts](/3.x/store-api/cart#guest-and-customer-carts) explains. ## Reading a Cart [#reading-a-cart] `cart.retrieve()` returns the cart with its lines and totals, for the basket page or the mini cart. Include the purchasable of each line to show its name and image. This basket page reads the cart, its number of items, its total and each line: ```ts const cart = await sdk.store.cart.retrieve(cartId, { include: ['lines', 'lines.purchasable', 'lines.purchasable.product'], }) cart.lines_quantity // 3 cart.total // 18900, in cents for (const line of cart.lines ?? []) { line.quantity // 1 line.unit_price_amount // 9000 line.purchasable?.name // the name of the product or the variant } ``` A header badge only needs the counts, so it asks for the cart without its lines. This call reads the number of items to show on the cart icon: ```ts const { lines_quantity } = await sdk.store.cart.retrieve(cartId, { include: [] }) ``` The includes of a cart are `lines`, `lines.purchasable`, `lines.purchasable.product`, `addresses` and `paymentMethod`. A stored ID that answers `404` belongs to a cart deleted after 30 days without activity: create a new cart. A customer cart also answers `404` once the token expires, as [When the Token Expires](/3.x/sdk/authentication#when-the-token-expires) explains: log the customer in again instead. ## Adding a Line [#adding-a-line] `cart.createLineItem()` adds a product or a variant to the cart. Send the type and the ID of what the visitor picked; the API prices it in the currency of the cart and checks the stock. Here, the product page adds one unit of the variant the visitor picked: ```ts const cart = await sdk.store.cart.createLineItem(cartId, { purchasable_type: 'variant', purchasable_id: variant.id, quantity: 1, }) ``` A product with variants is sold through them: adding it with `purchasable_type: 'product'` throws a `ShopperApiError` with the `variant_required` code. Adding the same variant again adds to the quantity of its line. `metadata` carries data of the line, such as an engraving. This call adds a product without variants with the initials to engrave: ```ts await sdk.store.cart.createLineItem(cartId, { purchasable_type: 'product', purchasable_id: product.id, metadata: { engraving: 'A.N.' }, }) ``` The stock and quantity checks throw `stock_insufficient` or `quantity_rule_violated`, with the rule in `meta`. [Errors With Meta](/3.x/sdk/errors#errors-with-meta) shows how to correct the quantity selector, and [Stock and Quantity Rules](/3.x/store-api/cart#stock-and-quantity-rules) lists the cases. ## Updating and Removing Lines [#updating-and-removing-lines] The quantity selector of the basket page calls `cart.updateLineItem()` with the `id` of the line. The quantity goes from 1 to 1,000,000; removing a line has its own method. The first call sets the quantity of a line to 2, and the second removes the line: ```ts await sdk.store.cart.updateLineItem(cartId, line.id, { quantity: 2 }) await sdk.store.cart.deleteLineItem(cartId, line.id) ``` Both return the cart with its new totals, so the basket page renders the response without reading the cart again. ## Addresses [#addresses] `cart.setAddresses()` sets the shipping address, the billing address, or both, and the contact email at the same time. Taxes, live carrier rates and the order addresses come from the shipping address, so the cart needs it before checkout. Here, the checkout form sends one address for shipping and billing, with the email of the customer: ```ts const address = { first_name: 'Amara', last_name: 'Ndiaye', address_1: '12 Rue de Rivoli', city: 'Paris', postal_code: '75004', phone: '+33612345678', country_code: 'FR', } const cart = await sdk.store.cart.setAddresses(cartId, { shipping_address: address, billing_address: address, email: 'amara@example.com', }, { include: ['lines', 'addresses'] }) ``` Sending an address type again replaces it. A logged-in customer picks a saved address instead: [Using a Saved Address](/3.x/sdk/customers#using-a-saved-address) copies its fields into the cart address. ## Promotion Codes [#promotion-codes] `cart.applyPromotion()` applies a code the customer typed. A code that does not exist or does not apply to the cart throws `promotion_not_applicable`, and the cart stays as it was. This call applies the code `WELCOME10` and reads the discount it gives: ```ts const cart = await sdk.store.cart.applyPromotion(cartId, 'WELCOME10') cart.promotions // [{ code: 'WELCOME10', source: 'code', amount: 1890, status: 'applied' }] cart.discount_total // 1890 ``` `cart.removePromotion()` removes every code of the cart. Automatic promotions stay. The "Remove" link of the promotion field calls it: ```ts await sdk.store.cart.removePromotion(cartId) ``` A cart with several codes removes one of them by sending the code in the body. `removePromotion()` sends no body, so call the route with `store.fetch()`. This call removes `WELCOME10` and keeps the other codes: ```ts import type { Cart } from '@shopperlabs/shopper-sdk' const { data } = await sdk.store.fetch(`/carts/${cartId}/promotion`, { method: 'DELETE', body: { code: 'WELCOME10' }, include: ['lines'], }) const cart = data as Cart ``` [Promotion Codes](/3.x/store-api/cart#promotion-codes) describes the checks a code goes through. ## Changing the Currency or the Zone [#changing-the-currency-or-the-zone] `cart.update()` changes the currency of a currency switcher, the zone of a country picker, the email or the metadata of the cart. Send only the fields that change. Here, a visitor who picks the United States moves the cart to the `US` zone and to dollars: ```ts const cart = await sdk.store.cart.update(cartId, { zone_code: 'US', currency_code: 'USD' }) ``` The lines are priced again. A new zone removes the shipping method and the payment method, and a new currency removes the shipping method, as [Updating the Cart](/3.x/store-api/cart#updating-the-cart) details. Send the new zone to the catalog calls too, so the product pages and the cart show the same prices. ## Transferring a Guest Cart [#transferring-a-guest-cart] Logging in or registering with `cart_id` already attaches the guest cart to the customer, as [Authentication](/3.x/sdk/authentication#logging-in) shows. `cart.transfer()` does the same for a customer who is already logged in when a guest cart appears, such as a cart started in another tab. This call moves the guest cart to the customer, keeps the ID of the returned cart and reads the prices that changed: ```ts const { cart, price_changes } = await sdk.store.cart.transfer(guestCartId) localStorage.setItem('shopper_cart', cart.id) for (const change of price_changes) { change.line // the line ID change.from // 9000 change.to // 8500 } ``` When the customer already has an open cart, the guest lines move into it and the guest cart is deleted, so keep the ID of the returned cart. `price_changes` lists the lines whose unit price changed, to tell the customer before checkout. [Transferring a Guest Cart](/3.x/store-api/customers#transferring-a-guest-cart) lists every case. ## Next Steps [#next-steps] Choose the shipping option and the payment method, then place the order. Every attribute of the cart, its lines and its addresses. # Catalog (/3.x/sdk/catalog) The catalog methods feed the pages a visitor browses before buying: the shop page, the category and brand pages, the search results, the product page and the navigation menu. They need no customer token. The [Catalog](/3.x/store-api/catalog) guide of the Store API describes every field of the responses and what a visitor sees, such as hidden categories or unpublished products. ## Listing Products [#listing-products] `product.list()` serves the shop page, the category pages and the search results: the same call with different filters. It returns the products in `data`, and the pagination and the currency of the prices in `meta`. Here, a category page lists the first 24 products of the men category that are in stock, newest first, with their brand: ```ts import { sdk } from '@/lib/shopper' const { data: products, meta } = await sdk.store.product.list({ filter: { category_tree: 'men', in_stock: true }, sort: ['-published_at'], include: ['brand'], page: { number: 1, size: 24 }, }) meta.currency // 'EUR' meta.last_page // 4 ``` `meta.currency` is the currency every price of the page is expressed in. A product card reads `calculated_price` for a standard product and `price_range.min` for a variant product, both [in cents](/3.x/money). This function returns the price to show on a product card, formatted in the currency of the page: ```ts import type { Product } from '@shopperlabs/shopper-sdk' function cardPrice(product: Product, currency: string): string { const amount = product.calculated_price?.amount ?? product.price_range?.min if (amount === undefined) { return '' } return new Intl.NumberFormat('en', { style: 'currency', currency }).format(amount / 100) } ``` The product filters are `q`, `name`, `sku`, `featured`, `in_stock`, `category`, `category_tree`, `collection`, `brand`, `tag`, `option`, `currency`, `price_min` and `price_max`. The sorts are `name`, `created_at`, `published_at` and `price`, and the includes are listed in [Filters, Sorting and Includes](/3.x/store-api/catalog#filters-sorting-and-includes). A search box sends the term in `q`. This call returns the first 12 products that match "sneaker": ```ts const { data: results } = await sdk.store.product.list({ filter: { q: 'sneaker' }, page: { size: 12 }, }) ``` ### Price Filters [#price-filters] A price slider sends its bounds in cents in `price_min` and `price_max`. The `price_range` include adds `meta.price_range`, the lowest and highest price of the products that match the other filters, so the slider keeps its full range while the visitor moves it. Here, the category page lists the products between 50.00 and 100.00, cheapest first, and reads the bounds of the slider: ```ts const { data, meta } = await sdk.store.product.list({ filter: { category_tree: 'men', price_min: 5000, price_max: 10000 }, sort: ['price'], include: ['price_range'], }) meta.price_range // { min: 2500, max: 18900, currency_code: 'EUR' } ``` Prices are never converted: `filter.currency` picks the currency of a multi-currency shop, and products without a price in that currency are left out, as [Price Filters and Sorting](/3.x/store-api/catalog#price-filters-and-sorting) explains. ## Showing a Product [#showing-a-product] `product.retrieve()` takes the slug of the product. A product page includes the variants and the options, so the visitor can pick a size or a color. This call reads a product with its brand, its variants, its options and its rating: ```ts const product = await sdk.store.product.retrieve('classic-leather-sneaker', { include: ['brand', 'variants', 'options', 'rating'], }) product.options?.map((option) => option.name) // ['Size', 'Color'] product.variants?.length // 6 product.rating // 4.6 ``` An unknown or unpublished slug throws a `ShopperApiError` with status `404`. In a Next.js page, turn it into the 404 page. This page reads the product of its URL, caches it for 60 seconds, and shows the 404 page when the product does not exist: ```ts title="app/products/[slug]/page.tsx" import { ShopperApiError } from '@shopperlabs/shopper-sdk' import { notFound } from 'next/navigation' import { sdk } from '@/lib/shopper' export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params const product = await sdk.store.product .retrieve(slug, { include: ['variants', 'options'] }, { next: { revalidate: 60, tags: [`product:${slug}`] } }) .catch((error) => { if (error instanceof ShopperApiError && error.status === 404) { notFound() } throw error }) return

    {product.name}

    } ``` [Showing a Product](/3.x/store-api/catalog#showing-a-product) describes the variants, the options and the stock of a product. ## Categories [#categories] `category.tree()` returns every enabled category, nested, in one call: the navigation menu of the shop. It is not paginated, and each node has `id`, `name`, `slug`, `position` and `children`. Here, the menu reads the tree, caches it for one hour and lists the slugs of the subcategories: ```ts const tree = await sdk.store.category.tree({ next: { revalidate: 3600, tags: ['categories'] } }) tree.map((category) => category.children.map((child) => child.slug)) ``` `category.list()` pages through the categories, and `category.retrieve()` reads a category page by its slug. The first call searches the categories named "shoes", and the second reads the men category: ```ts const { data: categories } = await sdk.store.category.list({ filter: { name: 'shoes' } }) const category = await sdk.store.category.retrieve('men') ``` A category page then lists its products with `filter: { category_tree: 'men' }`, or `category: 'men'` to leave out the subcategories. ## Collections [#collections] `collection.list()` and `collection.retrieve()` read the published collections, such as a "Summer Sale" landing page. The products of a collection come from the product listing. This landing page reads the "Summer Sale" collection, then lists its products: ```ts const collection = await sdk.store.collection.retrieve('summer-sale') const { data: products } = await sdk.store.product.list({ filter: { collection: 'summer-sale' }, }) ``` ## Brands [#brands] `brand.list()` gives the brand index and `brand.retrieve()` a brand page, with the same pattern. The first call lists 50 brands by name, and the second reads one brand: ```ts const { data: brands } = await sdk.store.brand.list({ sort: ['name'], page: { size: 50 } }) const brand = await sdk.store.brand.retrieve('maison-cuir') ``` ## Tags [#tags] `tag.list()` returns the product tags, for a tag cloud or a filter. A tag page lists its products with `filter: { tag: 'organic' }`. This call lists the tags by name: ```ts const { data: tags } = await sdk.store.tag.list({ sort: ['name'] }) ``` ## Attributes [#attributes] `attribute.list()` returns the attributes the merchant marked as filterable, such as size or color, with their values. A filter sidebar shows each value and sends its `key` in the `option` filter of the product listing. Here, the sidebar lists the attributes and their values, then lists the products in size 42 or 43: ```ts const { data: attributes } = await sdk.store.attribute.list() for (const attribute of attributes) { attribute.name // 'Size' attribute.values?.map((value) => value.key) // ['42', '43'] } const { data: products } = await sdk.store.product.list({ filter: { option: '42,43' }, }) ``` ## Reviews [#reviews] `product.reviews()` takes the slug of a product and returns its approved reviews, newest first. Its `meta` adds the rating summary of the product: `reviews_count`, `average_rating` and `rating_distribution`. This call reads the first 10 five-star reviews of a product and its rating summary: ```ts const { data: reviews, meta } = await sdk.store.product.reviews('classic-leather-sneaker', { filter: { rating: 5 }, page: { size: 10 }, }) meta.reviews_count // 128 meta.average_rating // 4.6 ``` `review.latest()` returns the latest approved reviews of the whole shop, for a testimonials block on the home page. It is not paginated and returns 20 reviews at most. This call reads them and lists the name of each author: ```ts const testimonials = await sdk.store.review.latest() testimonials.map((review) => review.author?.name) ``` The [Reviews](/3.x/store-api/catalog#reviews) section describes the review fields and the author of a review. ## Next Steps [#next-steps] Read the store settings, and the countries, zones and currencies a visitor picks from. Add the product the visitor picked to a cart. # Checkout (/3.x/sdk/checkout) Checkout turns a cart into an order. The storefront shows the shipping options and payment methods the API offers for the cart, opens a payment at the provider for the amount the API computes, lets the customer pay, then completes the cart. The browser never sends an amount. The [Checkout](/3.x/store-api/checkout) guide of the Store API describes each step, the error codes and the payment webhooks. The checkout starts with a cart that holds lines, an email and a shipping address, set as [Cart](/3.x/sdk/cart#addresses) shows. It goes through four steps: List the shipping options of the cart and send back the one the customer picks. List the payment methods of the cart and send back the one the customer picks. Open the payment at the provider, then let the customer confirm it with the provider's browser SDK, such as Stripe.js. Place the order once the provider has confirmed the payment. A cart that needs no delivery skips the first step, and a payment method that collects offline, such as a bank transfer, skips the third. ## Shipping Options [#shipping-options] `cart.shippingOptions()` quotes the shipping options of the cart, from the carriers of its zone and its shipping address. It returns the options in `data` and the notices of the API in `warnings`. This call lists the options of the cart with their name, carrier and price: ```ts import { sdk } from '@/lib/shopper' const { data: options, warnings } = await sdk.store.cart.shippingOptions(cartId) for (const option of options) { option.name // 'Express' option.carrier_name // 'UPS' option.amount // 1500, in cents } ``` Carriers that quote live rates need the shipping address, so list the options after setting it. An empty list with no warning means that no line of the cart ships, such as a cart of e-books. The warnings are sentences for a log or a notice, never codes to branch on, as [Empty Lists and Warnings](/3.x/store-api/checkout#empty-lists-and-warnings) explains. ## Setting the Shipping Method [#setting-the-shipping-method] `cart.setShippingMethod()` takes the `id` of the option the customer picked. The API quotes the options again and keeps the price of that quote, so the shipping price always comes from the server. Here, the cart takes the option the customer picked and returns its new totals: ```ts const cart = await sdk.store.cart.setShippingMethod(cartId, option.id) cart.shipping_total // 1500 cart.total // 20400 ``` ## Payment Methods [#payment-methods] `cart.paymentMethods()` returns the payment methods the cart offers: the enabled methods of its zone whose driver is configured. The `driver` of a method tells the storefront which flow to run. This call lists the payment methods with their title and driver: ```ts const methods = await sdk.store.cart.paymentMethods(cartId) for (const method of methods) { method.title // 'Credit card' method.driver // 'stripe' or 'manual' } ``` A `stripe` method opens a payment session. A `manual` method, such as a bank transfer or cash on delivery, collects offline: its `instructions` tell the customer what to do, to show on the confirmation page. ## Setting the Payment Method [#setting-the-payment-method] `cart.setPaymentMethod()` takes the `id` of the method the customer picked. Ask for the `paymentMethod` include to get it back with the cart. This call sets the method the customer picked and returns the cart with its lines and its payment method: ```ts const cart = await sdk.store.cart.setPaymentMethod(cartId, method.id, { include: ['lines', 'paymentMethod'], }) ``` ## Paying With Stripe [#paying-with-stripe] `cart.createPaymentSession()` prices the cart again, computes the total and opens a PaymentIntent for it at Stripe. The session carries the `client_secret` that Stripe.js needs to collect the payment. This call opens the session and reads its client secret and its amount: ```ts const session = await sdk.store.cart.createPaymentSession(cartId) session.client_secret // 'pi_3QHx..._secret_...' session.amount // 20400 ``` Mount Stripe's Payment Element with the client secret, and confirm the payment with `stripe.confirmPayment()`. Stripe runs 3D Secure when the card needs it, then sends the customer to `return_url`. This function opens the session, mounts the Payment Element in `#payment-element`, confirms the payment when the customer submits the form, and shows the error of a declined card: ```ts title="checkout/payment.ts" import { loadStripe } from '@stripe/stripe-js' import { sdk } from '@/lib/shopper' export async function mountPayment(form: HTMLFormElement, cartId: string) { const session = await sdk.store.cart.createPaymentSession(cartId) const stripe = (await loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY))! const elements = stripe.elements({ clientSecret: session.client_secret! }) elements.create('payment').mount('#payment-element') form.addEventListener('submit', async (event) => { event.preventDefault() const { error } = await stripe.confirmPayment({ elements, confirmParams: { return_url: `${window.location.origin}/checkout/complete` }, }) form.querySelector('#payment-message')!.textContent = error.message ?? '' }) } ``` A new session also returns the publishable key in `data.publishable_key`, but a resumed session does not, so keep the key in the configuration of the storefront. Calling `createPaymentSession()` again on an unchanged cart resumes the same session. Any change to the lines, a promotion code, the currency, the zone or the shipping method cancels it: open a new session after every change and mount the form again, as [Calling It Again](/3.x/store-api/checkout#calling-it-again) describes. The [Stripe](/3.x/payments/stripe) page covers the capture method and the webhooks. A driver that collects on its own page returns a `redirect_url` instead of a client secret: send the customer to it with `window.location.assign(session.redirect_url)`. ## Completing the Cart [#completing-the-cart] `cart.complete()` places the order. Call it on the page behind `return_url`, once Stripe has confirmed the payment, or when the customer confirms the order for a `manual` method. Ask for the `items` include to show the order lines. This function places the order, keeps its ID for the confirmation page and forgets the cart ID: ```ts title="checkout/complete.ts" import { sdk } from '@/lib/shopper' export async function placeOrder(cartId: string) { const order = await sdk.store.cart.complete(cartId, { include: ['items'] }) localStorage.setItem('shopper_last_order', order.id) localStorage.removeItem('shopper_cart') order.number // the order number to show the customer order.price_amount // 20400, the amount the customer pays return order } ``` Completing a cart that is already completed returns the same order, so a storefront that loses the response to a timeout calls `complete()` again and never places a second order. Keep the order `id` to read the order back, as [Orders](/3.x/sdk/orders) shows, and forget the cart ID: a completed cart refuses every change with `cart_completed`. The order starts with `payment_status: 'pending'`, and the Stripe webhook moves it to authorized or paid, often before `complete()` answers. A confirmation page can show "payment pending" for the few seconds before the event arrives, as [Payment Status After Placement](/3.x/store-api/checkout#payment-status-after-placement) describes. ## When the Checkout Fails [#when-the-checkout-fails] The API checks the cart again when the payment session opens and when the cart completes. A price that went up, a stock that ran out or a carrier that raised its rate throws a `ShopperApiError` whose code tells the storefront what to do. This function places the order and, when it fails, shows the updated cart, the new shipping options, a retry or the message of the API, depending on the code: ```ts title="checkout/complete.ts" import { ShopperApiError } from '@shopperlabs/shopper-sdk' export async function completeCheckout(cartId: string) { try { return await placeOrder(cartId) } catch (error) { if (! (error instanceof ShopperApiError)) { throw error } switch (error.code) { case 'price_changed': return showCart(await sdk.store.cart.retrieve(cartId)) case 'shipping_price_changed': case 'shipping_option_unavailable': return showShippingOptions(await sdk.store.cart.shippingOptions(cartId)) case 'payment_session_in_progress': case 'payment_provider_unavailable': case 'shipping_provider_unavailable': return retryLater(error.status === 409 ? 3 : 5) default: return showMessage(error.message) } } } ``` On `price_changed`, the cart already holds the new prices: show the new total, and open a new payment session once the customer accepts it. The `409` and `503` codes wait 3 and 5 seconds, the `Retry-After` the API sends with them. `payment_released` means the stock ran out after the payment: the API gave the payment back, so the customer updates the cart and pays again. [When the Order Cannot Be Placed](/3.x/store-api/checkout#when-the-order-cannot-be-placed) lists every code, and [Price, Stock and Shipping Changes](/3.x/store-api/checkout#price-stock-and-shipping-changes) what the cart holds after each one. ## Next Steps [#next-steps] Read the order back on the confirmation page and follow its shipments. Set up the Stripe driver, its capture method and its webhooks. # Custom Endpoints (/3.x/sdk/custom-endpoints) The SDK wraps the routes Shopper ships. An app adds its own, such as a store locator or a wishlist, with the `ShopperApi` facade described in [Adding Your Own Routes](/3.x/store-api#adding-your-own-routes), and an [add-on](/3.x/addons/store-api#registering-routes) can register more. `store.fetch()` calls any of them with what the built-in methods send: the customer token, the zone and channel headers and the language, and it throws the same `ShopperApiError`. ## Calling a Route [#calling-a-route] `store.fetch()` takes a path relative to the Store API prefix, `/store` by default or the [`storePrefix`](/3.x/sdk#configuration) of the client. It sends a `GET` by default and returns the `data`, `meta` and `links` of the response. This call reads the store locations of your app, sorted by name, and sends the position of the visitor in the `near` parameter: ```ts import { sdk } from '@/lib/shopper' type StoreLocation = { id: string name: string city: string } const { data } = await sdk.store.fetch('/store-locations', { sort: ['name'], query: { near: '48.8566,2.3522' }, }) const locations = data as StoreLocation[] ``` The options are the ones of the built-in methods, `include`, `filter`, `sort`, `page` and `fields`, plus `query` for any other parameter, sent as it is. `data` is typed `T | T[] | null` because the SDK cannot know whether the route returns one resource, a list or nothing, so narrow it as above. A third argument, `init`, goes to `fetch` for an `AbortSignal` or the caching options of Next.js, as [Request Options](/3.x/sdk#request-options) shows. ## Sending a Body [#sending-a-body] `method` and `body` call the routes that write. A plain object goes as JSON, and a `FormData` goes as `multipart/form-data` for a route that takes a file. This call adds a product to the wishlist of the customer: ```ts await sdk.store.fetch('/customers/me/wishlist', { method: 'POST', body: { product_id: product.id }, }) ``` A route of the authenticated group throws status `401` without a valid token. When the client sent a token that expired, `onUnauthorized` runs first, as on the account methods. A response without a body, such as `204 No Content`, returns `data: null`. The same call reaches the options of a built-in route that its method does not send, such as the `code` that removes one promotion code from a cart, as [Promotion Codes](/3.x/sdk/cart#promotion-codes) shows. ## Returning JSON:API From Your Routes [#returning-jsonapi-from-your-routes] `store.fetch()` reads the response as a JSON:API document: each resource becomes one object with its `id` and its `attributes`, and the relationships listed in `included` are nested in it. A route that returns plain JSON, such as `{"data": [{"id": 1, "name": "Paris Marais"}]}`, comes back with the `id` alone. Return a JSON:API resource from your controller instead, with Laravel's `JsonApiResource`, the class the Shopper resources extend. This resource gives each store location the `store-locations` type, and sends its name and its city as attributes: ```php title="app/Http/Resources/StoreLocationResource.php" namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\JsonApi\JsonApiResource; class StoreLocationResource extends JsonApiResource { public function toType(Request $request): string { return 'store-locations'; } public function toAttributes(Request $request): array { return [ 'name' => $this->name, 'city' => $this->city, ]; } } ``` The controller returns the resource, or its collection for a list. This one returns every store location, sorted by name: ```php title="app/Http/Controllers/Store/StoreLocatorController.php" namespace App\Http\Controllers\Store; use App\Http\Resources\StoreLocationResource; use App\Models\StoreLocation; class StoreLocatorController { public function __invoke() { return StoreLocationResource::collection(StoreLocation::query()->orderBy('name')->get()); } } ``` ## Building Requests Yourself [#building-requests-yourself] The SDK exports the two functions its methods use, for the requests that do not go through the client, such as a server route that caches a document or a worker that reads one from a key-value store. `buildQuery()` turns the options of a call into a query string, and `flatten()` turns a JSON:API document into objects. This code builds the query of a product listing, sends it with `fetch`, and turns the response into products: ```ts import { buildQuery, flatten, type Product } from '@shopperlabs/shopper-sdk' const query = buildQuery({ include: ['brand'], filter: { category_tree: 'men' } }) // '?include=brand&filter%5Bcategory_tree%5D=men' const response = await fetch(`https://shop.example.com/store/products${query}`) const products = flatten(await response.json()) as Product[] ``` A request sent this way carries none of the headers of the client: add the token, `X-Shopper-Zone` and `X-Shopper-Channel` yourself when the route needs them. ## Next Steps [#next-steps] The route groups, the headers and the rate limits your routes share with the built-in ones. Catch the errors of a call and show the validation messages of a form. # Customers (/3.x/sdk/customers) The customer methods serve the account area of the storefront: the profile form, the profile picture and the address book. They act on the customer whose token the client holds, set by [logging in](/3.x/sdk/authentication#logging-in), and throw a `ShopperApiError` with status `401` without one. The [Customers](/3.x/store-api/customers) guide of the Store API describes every field. ## Reading the Profile [#reading-the-profile] `customer.me()` returns the profile of the logged-in customer, to greet them and fill the account form. This call reads the profile, with the first name, the email and the picture: ```ts import { sdk } from '@/lib/shopper' const customer = await sdk.store.customer.me() customer.first_name // 'Amara' customer.email // 'amara@example.com' customer.avatar // the URL of the profile picture ``` A token that expired throws status `401` here like on every account call, as [When the Token Expires](/3.x/sdk/authentication#when-the-token-expires) describes. ## Updating the Profile [#updating-the-profile] `customer.update()` saves the fields the customer changed: `first_name`, `last_name`, `phone_number`, `birth_date`, `gender` and `opt_in`. A field left out keeps its value, and `null` clears the optional ones. Here, the account form saves a new phone number, a birth date and the newsletter choice: ```ts const customer = await sdk.store.customer.update({ phone_number: '+33612345678', birth_date: '1992-04-18', opt_in: false, }) ``` The email is not part of the profile update: a body that carries `email` leaves it unchanged. Invalid fields throw status `422`, which [Validation Errors](/3.x/sdk/errors#validation-errors) turns into messages under each input. ## Profile Picture [#profile-picture] `customer.updateAvatar()` uploads a picture of 1,024 KB at most, from a file input or any `Blob`. The client sends it as `multipart/form-data`. This code takes the file the customer picked in the `#avatar` input and uploads it: ```ts const input = document.querySelector('#avatar')! const file = input.files![0] const customer = await sdk.store.customer.updateAvatar(file, file.name) customer.avatar // the URL of the new picture ``` `customer.removeAvatar()` deletes it. Without a picture, `avatar` points to a generated one, so the storefront always has an image to show. ## Addresses [#addresses] Saved addresses spare a returning customer from typing their address at every checkout. Each address is a shipping or a billing address, and the customer marks one of each as the default. ### Listing Addresses [#listing-addresses] `customer.address.list()` returns every address of the customer, newest first, in one array. It is not paginated. This call reads the addresses with their country and finds the default shipping address: ```ts const addresses = await sdk.store.customer.address.list({ include: ['country'] }) const shipping = addresses.find((address) => address.shipping_default) ``` ### Saving an Address [#saving-an-address] `customer.address.create()` saves an address from the account area, or after a checkout when the customer ticks a "save this address" box. `type` is `shipping` or `billing`, and `shipping_default` or `billing_default` moves the default from the other addresses to this one. This call saves a shipping address in Paris and makes it the default one: ```ts const address = await sdk.store.customer.address.create({ type: 'shipping', first_name: 'Amara', last_name: 'Ndiaye', street_address: '12 Rue de Rivoli', postal_code: '75004', city: 'Paris', country_code: 'FR', phone_number: '+33612345678', shipping_default: true, }) ``` ### Updating and Deleting an Address [#updating-and-deleting-an-address] `customer.address.update()` changes the fields it receives, and `customer.address.delete()` removes the address. Both take the `id` of the address. The first call adds an apartment number to the address, and the second deletes the address: ```ts await sdk.store.customer.address.update(address.id, { street_address_plus: 'Apartment 4B' }) await sdk.store.customer.address.delete(address.id) ``` An ID that belongs to another customer throws status `404`, like an ID that does not exist. ### Using a Saved Address [#using-a-saved-address] The cart takes an address object, not an address ID. To ship to a saved address, copy its fields into the cart address: four of them change name, and the others keep theirs, as [Using a Saved Address at Checkout](/3.x/store-api/customers#using-a-saved-address-at-checkout) lists. The `toCartAddress()` function below copies a saved address into a cart address, then the call ships the cart to the default shipping address: ```ts import type { Address } from '@shopperlabs/shopper-sdk' function toCartAddress(address: Address) { return { first_name: address.first_name, last_name: address.last_name, company: address.company_name, address_1: address.street_address, address_2: address.street_address_plus, city: address.city, state: address.state, postal_code: address.postal_code, phone: address.phone_number, country_code: address.country_code!, } } await sdk.store.cart.setAddresses(cartId, { shipping_address: toCartAddress(shipping), }) ``` ## Next Steps [#next-steps] List the orders of the customer and download the files they bought. Ship to the saved address and place the order. # Errors (/3.x/sdk/errors) Every SDK method throws a `ShopperApiError` when the API answers with a status outside the 2xx range. The error carries the HTTP status and the error objects of the response, so a storefront can show a message next to a form field, correct a quantity, or ask the customer to log in again. The [Errors](/3.x/store-api/errors) guide of the Store API describes the error object and lists every code. ## Catching an Error [#catching-an-error] `ShopperApiError` is exported by the SDK. Check for it with `instanceof`, then read the status and the code of the first error. Here, a promotion code that does not apply shows the message of the API, and any other error goes up: ```ts import { ShopperApiError } from '@shopperlabs/shopper-sdk' import { sdk } from '@/lib/shopper' try { await sdk.store.cart.applyPromotion(cartId, 'WELCOME10') } catch (error) { if (error instanceof ShopperApiError && error.code === 'promotion_not_applicable') { showMessage(error.message) } else { throw error } } ``` The error has these members: The HTTP status of the response, such as `422`. The error objects of the response, each with `status`, `code`, `title`, `detail`, `source` and `meta` when the API sets them, as [Error Object](/3.x/store-api/errors#error-object) describes. The `detail` of the first error, or its `title`, or `Request failed with status 500` when the response has no error object. The `code` of the first error. The `code` of the first error whose pointer names this field, such as `codeFor('email')`. The `detail` of each error, grouped by the field its pointer names. Errors without a pointer are left out. A response whose body is not JSON, such as an HTML error page from a proxy, gives a `ShopperApiError` with an empty `errors` array. A request that never reaches the API, because the network is down or the request is aborted, throws the error of `fetch` itself, such as a `TypeError` or an `AbortError`, never a `ShopperApiError`. ## Validation Errors [#validation-errors] A request whose fields fail validation throws a `ShopperApiError` with status `422` and one error per message. `fields()` groups the messages by field, ready for a form: it removes the `/data/attributes/` prefix of the pointer and joins nested paths with dots, as [Reading the Pointer](/3.x/store-api/errors#reading-the-pointer) describes. This function sends the sign-up form and returns the messages of each field when the API refuses it: ```ts title="app/register/form.ts" import { ShopperApiError } from '@shopperlabs/shopper-sdk' import { sdk } from '@/lib/shopper' export async function register(values: { last_name: string; email: string; password: string }) { try { await sdk.auth.register(values) return { errors: {} } } catch (error) { if (error instanceof ShopperApiError && error.status === 422) { return { errors: error.fields() } } throw error } } ``` An email already in use gives `{ email: ['The email has already been taken.'] }`. Show the first message of each field under its input. `codeFor()` tells two errors on the same field apart, to word the message yourself or to offer an action. Here, an email already in use shows a link to the login page: ```ts if (error.codeFor('email') === 'unique') { showLoginLink() } ``` The checkout calls, `cart.createPaymentSession()` and `cart.complete()`, take no field: their pointer names the part of the cart that blocks the checkout, such as `shipping_method` or `payment_method`. `fields()` groups them under those names. Show them at the top of the checkout page. ## Errors With Meta [#errors-with-meta] Some errors carry a `meta` object with the values that fix the request. A quantity that breaks the quantity rule of a price throws `quantity_rule_violated`, with the minimum, the maximum and the increment of the rule. This code sets the quantity selector back to a quantity the rule accepts: ```ts try { await sdk.store.cart.updateLineItem(cartId, lineId, { quantity: 3 }) } catch (error) { if (error instanceof ShopperApiError && error.code === 'quantity_rule_violated') { const { minimum, increment } = error.errors[0].meta as { minimum: number | null; increment: number | null } setQuantity(Math.max(minimum ?? 1, increment ?? 1)) } else { throw error } } ``` [Errors With Meta](/3.x/store-api/errors#errors-with-meta) lists the values of `meta`. ## Rate Limits [#rate-limits] A client past a rate limit gets status `429` and the `rate_limited` code. The API sends the seconds to wait in the `Retry-After` header, as [Rate Limit Errors](/3.x/store-api/errors#rate-limit-errors) describes. `ShopperApiError` does not carry the response headers, so wrap `fetch` to read it. This client keeps the seconds to wait in `retryAfter` each time the API answers `429`: ```ts title="lib/shopper.ts" import Shopper from '@shopperlabs/shopper-sdk' export let retryAfter = 0 export const sdk = new Shopper({ baseUrl: import.meta.env.VITE_SHOPPER_URL, fetch: async (input, init) => { const response = await fetch(input, init) if (response.status === 429) { retryAfter = Number(response.headers.get('Retry-After')) } return response }, }) ``` A login refused after five failures also answers `429`, and its `message` already gives the wait, such as `Too many login attempts. Please try again in 59 seconds.`. ## Expired Tokens [#expired-tokens] A `401` on a request that carried the customer token means the token expired or was revoked. The client clears the token and calls the `onUnauthorized` callback before it throws, as [When the Token Expires](/3.x/sdk/authentication#when-the-token-expires) describes, so the `catch` blocks of your pages do not each handle it. ## Next Steps [#next-steps] Every code of the Store API, grouped by area, with the status that carries it. Add products to a cart and handle stock and quantity errors. # JavaScript SDK (/3.x/sdk) `@shopperlabs/shopper-sdk` is the JavaScript client of the [Store API](/3.x/store-api). It builds the URLs and query strings, sends the JSON:API, zone, channel and language headers, keeps the customer token, and turns every JSON:API document into the plain nested objects described by `@shopperlabs/shopper-types`. A failed request throws a `ShopperApiError` that carries the status and the error codes of the API. The SDK has no dependency other than the types and runs wherever `fetch` exists: browsers, Node.js 18 and later, React Native and edge runtimes such as Cloudflare Workers or the Vercel Edge runtime. It works with any front-end framework, because it only wraps HTTP calls. The pages of this section show the SDK method for each part of the storefront flow. The [Store API guides](/3.x/store-api#next-steps) describe the same endpoints over plain HTTP, with every field of the responses and every error code: each SDK page links to its guide instead of repeating them. ## Installation [#installation] Install the package from npm. It brings `@shopperlabs/shopper-types` with it and re-exports its types, so a storefront installs the SDK only. Run this command in the folder of your storefront: ```bash npm install @shopperlabs/shopper-sdk ``` The package is published as an ES module. Import it with `import`, from TypeScript or from a bundler; `require()` is not supported. The Laravel application must run the Store API first, as described on the [Installation](/3.x/installation#install-the-store-api) page. ## Creating the Client [#creating-the-client] The client takes the base URL of the Laravel application that runs the Store API, without the `/store` prefix. Create it once in a module of its own and import it where you need it. This module creates the client with the URL of the shop: ```ts title="lib/shopper.ts" import Shopper from '@shopperlabs/shopper-sdk' export const sdk = new Shopper({ baseUrl: process.env.NEXT_PUBLIC_SHOPPER_URL ?? 'http://localhost:8000', }) ``` The client groups its methods in two modules. `sdk.auth` registers, logs in and logs out customers. `sdk.store` holds one resource per part of the Store API, named in the singular: `sdk.store.product`, `sdk.store.cart`, `sdk.store.customer`, and so on. This example imports the client, lists the 12 newest products of the men category that are in stock, then creates a cart: ```ts import { sdk } from '@/lib/shopper' const { data: products } = await sdk.store.product.list({ filter: { category_tree: 'men', in_stock: true }, sort: ['-published_at'], page: { size: 12 }, }) const cart = await sdk.store.cart.create() ``` A storefront rendered on a server, such as Next.js server components or Nuxt server routes, needs one client per request as soon as customers log in: see [Server-Side Storefronts](#server-side-storefronts). ## Configuration [#configuration] The constructor takes one object. Only `baseUrl` is required: The URL of the Laravel application, such as `https://shop.example.com`. A trailing slash is removed. The prefix of the Store API routes. Change it when your application sets `SHOPPER_API_PREFIX`, as [Base URL](/3.x/store-api#base-url) describes. Sent as `Accept-Language` on every request, such as `fr`. It sets the language of translated content and of error messages. See [Language](/3.x/store-api#language). The slug of a sales channel, sent as `X-Shopper-Channel` on every request. The catalog then returns only the products of that channel; without it, the API uses its default channel, or no channel filter. See [Sales Channel](/3.x/store-api#sales-channel). Headers added to every request, such as `X-Shopper-Zone`. They override the headers the SDK sets, `Authorization` included. The `fetch` function to call, for a runtime without a global `fetch` or to wrap every request. Where the customer token lives between requests. It is kept in memory by default, so it is lost on page reload. See [Persisting the Token](/3.x/sdk/authentication#persisting-the-token). Called when a request that carried a token answers `401`, after the SDK has cleared the token. See [When the Token Expires](/3.x/sdk/authentication#when-the-token-expires). ### Zone [#zone] The zone of a request sets the currency of the prices, the zone of new carts, and the shipping options and payment methods offered at checkout, as described in [Zone](/3.x/store-api#zone). The SDK has no zone option: send the `X-Shopper-Zone` header with the code of the zone through `headers`. This client asks for the prices and the checkout options of the `EU` zone: ```ts title="lib/shopper.ts" export const sdk = new Shopper({ baseUrl: process.env.NEXT_PUBLIC_SHOPPER_URL ?? 'http://localhost:8000', headers: { 'X-Shopper-Zone': 'EU' }, }) ``` A visitor who picks another country changes the zone of the catalog and of the cart separately. Catalog calls take the header per request, through their [request options](#request-options). An existing cart keeps the zone it was created with until you change it with [`cart.update()`](/3.x/sdk/cart#changing-the-currency-or-the-zone). ### Language and Sales Channel [#language-and-sales-channel] A language switcher changes the language of every later call with `setLocale()`, and `setChannel()` does the same for the sales channel. `null` goes back to the default of the shop. Here, the client switches to French and to the `mobile-app` channel, then goes back to the default channel: ```ts sdk.setLocale('fr') sdk.getLocale() // 'fr' sdk.setChannel('mobile-app') sdk.getChannel() // 'mobile-app' sdk.setChannel(null) ``` ## Query Parameters [#query-parameters] The methods that read a resource take an optional `RequestParams` object. The SDK turns it into the JSON:API query parameters described in [JSON:API Conventions](/3.x/store-api/json-api): | Option | Example | Query string | |--------|---------|--------------| | `include` | `['brand', 'variants']` | `include=brand,variants` | | `filter` | `{ brand: 'maison-cuir', in_stock: true }` | `filter[brand]=maison-cuir&filter[in_stock]=true` | | `sort` | `['-published_at', 'name']` | `sort=-published_at,name` | | `page` | `{ number: 2, size: 24 }` | `page[number]=2&page[size]=24` | | `page` | `{ cursor: '' }` | `page[cursor]=` | | `fields` | `{ products: ['name', 'slug'] }` | `fields[products]=name,slug` | A filter takes a string, a number or a boolean. Several values of one filter are a comma-separated string, such as `{ option: '42,43' }`. The filters, sorts and includes each resource accepts are listed in its Store API guide; an unknown one throws a `400` error with the `bad_request` code. ## Responses [#responses] The API answers JSON:API documents: the attributes of a resource sit in `attributes`, and its related resources sit once each in a top-level `included` array. The SDK flattens them. A resource becomes one object with its `id` and its attributes, and each relationship you include becomes a nested object or array. This call reads a product with its brand and its variants, which then read as plain properties: ```ts const product = await sdk.store.product.retrieve('classic-leather-sneaker', { include: ['brand', 'variants'], }) product.name // 'Classic Leather Sneaker' product.brand?.name // 'Maison Cuir' product.variants?.length // 6 ``` A relationship you did not include stays out of the object. One whose related resource is not in `included` becomes a stub with only its `id`. Relationship names keep the case of the API, such as `order.shippingAddress` or `cart.paymentMethod`. ### Listings [#listings] `list()` returns an object with the records in `data`, plus the `meta` and `links` of the document. The pagination values sit there, as [Pagination](/3.x/store-api/json-api#pagination) describes. This call reads the first 20 brands by name, the number of pages and the link to the next page: ```ts const { data: brands, meta, links } = await sdk.store.brand.list({ sort: ['name'], page: { number: 1, size: 20 }, }) meta?.last_page // 3 links?.next // 'https://shop.example.com/store/brands?sort=name&page%5Bnumber%5D=2&page%5Bsize%5D=20' ``` With cursor pagination, start with an empty cursor and pass `meta.next_cursor` to the next call, with the same filters and sort, until it is `null`. This loop reads every brand, 50 at a time: ```ts import type { Brand } from '@shopperlabs/shopper-sdk' const brands: Brand[] = [] let cursor: string | null = '' while (cursor !== null) { const page = await sdk.store.brand.list({ sort: ['name'], page: { size: 50, cursor } }) brands.push(...page.data) cursor = (page.meta?.next_cursor as string | null) ?? null } ``` The listings that the API never paginates return the records directly: `category.tree()`, `review.latest()`, `cart.paymentMethods()` and `customer.address.list()`. `cart.shippingOptions()` returns the options with the warnings of the quote. ## Request Options [#request-options] The catalog and store resources take a last argument, `init`, passed to `fetch` for that call: an `AbortSignal`, a cache mode, extra headers, or the caching options of Next.js. Headers given here win over the headers of the client. Here, a search can be cancelled with the controller, and asks for the prices of the `US` zone: ```ts const controller = new AbortController() const { data } = await sdk.store.product.list( { filter: { q: 'sneaker' } }, { signal: controller.signal, headers: { 'X-Shopper-Zone': 'US' } }, ) ``` In a Next.js server component, `next.revalidate` and `next.tags` cache the response in the Next.js data cache, and `revalidateTag()` clears it when the store changes. This home page caches the settings for 5 minutes and the featured products for 60 seconds: ```ts title="app/page.tsx" const settings = await sdk.store.setting.retrieve(undefined, { next: { revalidate: 300, tags: ['settings'] }, }) const { data: featured } = await sdk.store.product.list( { filter: { featured: true }, page: { size: 8 } }, { next: { revalidate: 60, tags: ['products'] } }, ) ``` These methods take `init`: `list()` and `retrieve()` of the catalog and store resources, `product.reviews()`, `review.latest()`, `category.tree()`, `setting.retrieve()` and `setting.get()`, and `store.fetch()`. The cart, customer, order and shipment methods do not: they send the headers of the client, and a cart changes zone through [`cart.update()`](/3.x/sdk/cart#changing-the-currency-or-the-zone). ## Server-Side Storefronts [#server-side-storefronts] In the browser, each visitor runs their own copy of the client, so a module-level client is enough. On a server, a module-level client is shared by every request the process handles: a token stored by one visitor's login would be sent with the next visitor's requests. A storefront that renders on the server creates a client per request when customers log in, with a [token storage](/3.x/sdk/authentication#persisting-the-token) that reads the cookie of that request. The Store API counts its rate limits per IP address. When every call comes from your storefront server, all visitors share the quota of that server. Forward the visitor's address in `X-Forwarded-For` and trust the storefront server in Laravel, as described in [Behind a Server-Side Storefront](/3.x/store-api#behind-a-server-side-storefront). This `shopper()` function creates a client for each request and forwards the IP address of the visitor: ```ts title="lib/shopper.ts" import Shopper from '@shopperlabs/shopper-sdk' import { headers } from 'next/headers' export async function shopper() { const forwardedFor = (await headers()).get('x-forwarded-for') return new Shopper({ baseUrl: process.env.SHOPPER_URL ?? 'http://localhost:8000', headers: forwardedFor ? { 'X-Forwarded-For': forwardedFor } : {}, }) } ``` ## TypeScript [#typescript] The SDK is written in TypeScript and every method is typed. The resource types of `@shopperlabs/shopper-types`, such as `Product`, `Cart`, `Order` or `Customer`, are re-exported by the SDK, so you import them from one package. Here, the types come from the SDK, and `RequestParams` types the options that the listing pages share: ```ts import type { Cart, Product, RequestParams } from '@shopperlabs/shopper-sdk' export const listingParams: RequestParams = { include: ['brand', 'rating'], page: { size: 24 }, } ``` The API sends every `id` as a string, and the objects the SDK methods return type it that way, for the resource and for each relation it includes. The `Cart` type itself types `id` as `string | number`, because the Inertia starter kits also pass it the numeric ids of Eloquent models, so a variable typed `Cart` loses the string. Type the variable `Flattened`, the shape the methods return. This code keeps the cart in a variable and sends its `id` back to update it, a call that a variable typed `Cart` would not compile: ```ts import type { Cart, Flattened } from '@shopperlabs/shopper-sdk' let cart: Flattened = await sdk.store.cart.create() cart = await sdk.store.cart.update(cart.id, { email: 'jane@example.com' }) ``` A few payload types are not exported from the package root, such as the address of a cart. Read them from the method signature. This type takes the second argument of `cart.setAddresses()`, the addresses of the cart: ```ts import type { CartModule } from '@shopperlabs/shopper-sdk' type CartAddresses = Parameters[1] ``` Every amount is an integer in cents, as in the API. The [Money](/3.x/money) page covers cents and formatting. ## Next Steps [#next-steps] Register and log in customers, keep their token across page loads, and log them out. Catch `ShopperApiError`, show validation messages next to their fields and react to error codes. List and filter products, and read categories, collections, brands, tags, attributes and reviews. Read the store settings, the legal pages, and the countries, zones and currencies. Create a cart, add and change lines, set addresses and apply promotion codes. Choose shipping and payment, open a payment session and place the order. Manage the profile, the avatar and the saved addresses of the logged-in customer. Show the order confirmation, the order history, shipments and digital downloads. Call the routes of an add-on, or any Store API route the SDK does not wrap. # Orders (/3.x/sdk/orders) Once the checkout places an order, the storefront shows it on the confirmation page, in the order history of the account, on a tracking page while the parcel travels, and in the downloads of a digital product. Orders are read-only for the storefront: the merchant changes them in the admin panel, and the payment and carrier webhooks move their statuses. The [Orders](/3.x/store-api/orders) guide of the Store API describes every attribute and status. ## Order Confirmation [#order-confirmation] `order.retrieve()` reads the order the checkout just placed, with the `id` that [`cart.complete()`](/3.x/sdk/checkout#completing-the-cart) returned. It works for guests and customers alike, so the confirmation page needs no account. This confirmation page reads the order with its lines: ```ts import { sdk } from '@/lib/shopper' const order = await sdk.store.order.retrieve(orderId, { include: ['items'] }) order.number // the order number to show the customer order.price_amount // 14390, the amount paid in cents for (const item of order.items ?? []) { item.name // the name of the product as it was at checkout item.quantity // 1 } ``` A guest order is readable by anyone holding its ID, so keep the ID in the confirmation URL or the session of the visitor, and out of logs and analytics events. A customer order needs the token of that customer, and throws status `404` without it, like an ID that does not exist. `items` is the only include of this call: any other throws status `422` with the `include_not_allowed` code. The addresses, the payment method and the shipments are on the order details of the account, as [Who Can Read an Order](/3.x/store-api/orders#who-can-read-an-order) explains. ## Order History [#order-history] `customer.orders.list()` pages through the orders of the logged-in customer, newest first, 15 per page by default. `filter.status` takes one [status](/3.x/store-api/orders#statuses) or several, comma-separated, so each tab of the history page is one call. Here, the "In progress" tab lists 10 orders that are new or processing, with their lines: ```ts const { data: orders } = await sdk.store.customer.orders.list({ filter: { status: 'new,processing' }, include: ['items'], page: { size: 10 }, }) for (const order of orders) { order.number order.status // 'processing' order.created_at } ``` `sort: ['created_at']` lists the oldest orders first. [Filters, Sorting and Includes](/3.x/store-api/orders#filters-sorting-and-includes) lists the includes of the history. ## Order Details [#order-details] `customer.orders.retrieve()` serves the order page of the account: the lines, the addresses, the payment method, the packages and the refund. Ask for the relationships the page shows. This call reads an order of the customer with its lines, its addresses, its payment method, its shipments and its refund: ```ts const order = await sdk.store.customer.orders.retrieve(orderId, { include: ['items', 'shippingAddress', 'billingAddress', 'paymentMethod', 'shippings', 'refund'], }) order.payment_status // 'paid' order.shipping_status // 'shipped' order.shippingAddress?.city // 'Paris' order.shippings?.map((shipment) => shipment.tracking_number) ``` Show `price_amount` as the amount paid: `total` covers the lines only, without shipping, and fits a "Subtotal" row. The order keeps a copy of the addresses and of each line as they were at checkout, so a change to a saved address or to the catalog leaves a past order as it was. [Amounts](/3.x/store-api/orders#amounts) details each total. ## Tracking a Shipment [#tracking-a-shipment] `shipment.retrieve()` reads one package and its tracking events, oldest first. It needs no token, so a tracking page works from a link in a shipping email. The shipment ID comes from the `shippings` of the order details, or from the `shipment.*` webhooks for the email you send when the package ships. This tracking page reads a shipment and its events: ```ts const shipment = await sdk.store.shipment.retrieve(shipmentId, { include: ['events'] }) shipment.status // 'in_transit' shipment.carrier_name // 'UPS' shipment.tracking_url // the carrier's own tracking page for (const event of shipment.events ?? []) { event.status // 'at_sorting_center' event.location // 'Lyon' event.occurred_at } ``` `events` is the only include of a shipment. An unknown ID throws status `404`. [Tracking a Shipment](/3.x/store-api/orders#tracking-a-shipment) lists the statuses of a package. ## Downloading Purchased Files [#downloading-purchased-files] A customer who buys a digital product, such as a PDF guide, downloads its files from the order page of their account. Once the payment status of the order is `paid` or `partially_refunded`, each item of a downloadable product carries `files` on the [order details](#order-details), with the `id`, `name`, `extension` and `size` in bytes of each file. Show one **Download** button per file. The files have no public URL. `customer.fileLink()` asks for a link when the customer clicks, with the order ID, the item ID and the file ID, and the browser follows it right away. The `download()` function below asks for the link of one file and opens it: ```ts async function download(orderId: string, itemId: string, fileId: string) { const { url } = await sdk.store.customer.fileLink(orderId, itemId, fileId) window.location.assign(url) } ``` The link works for five minutes: ask for a new one at every click, and never store it or put it in an email. A guest order has no downloads, so a store that sells digital products asks buyers to create an account. [Downloading Purchased Files](/3.x/store-api/orders#downloading-purchased-files) describes the link for each storage disk. ## Next Steps [#next-steps] Manage the profile and the saved addresses of the account. Call a route of your own app through the client. # Store and Regions (/3.x/sdk/store) The store methods read what the storefront shows around the catalog: the name, logo and contact details of the shop in the header and footer, the legal pages, and the countries, zones and currencies a visitor picks from. They need no customer token and change rarely, so a storefront caches them. The [Store](/3.x/store-api/store) guide of the Store API describes every field of the responses. ## Store Settings [#store-settings] `setting.retrieve()` returns the public settings of the shop in one object: the name, the logo, the address, the social links, the default currency, the currencies and the supported languages. This call reads them, then the name, the logo and the languages the header shows: ```ts import { sdk } from '@/lib/shopper' const settings = await sdk.store.setting.retrieve() settings.name // 'Maison Cuir' settings.logo?.url // 'https://shop.example.com/storage/logo.png' settings.supported_locales // [{ code: 'en', label: 'English' }, { code: 'fr', label: 'Français' }] ``` `setting.get()` returns one key of the settings, typed after it. This call reads the currencies of the shop: ```ts const currencies = await sdk.store.setting.get('currencies') // ['EUR', 'USD'] ``` `get()` reads the whole settings to return one key, so a page that needs several keys calls `retrieve()` once. ### Caching the Settings [#caching-the-settings] A storefront reads the settings on nearly every page. The API lets browsers and CDNs cache the response for 300 seconds, as [Caching the Settings](/3.x/store-api/store#caching-the-settings) describes. In a Next.js server component, cache it in the Next.js data cache and clear it with `revalidateTag('settings')` when the merchant changes them. This call caches the settings for 300 seconds under the `settings` tag: ```ts const settings = await sdk.store.setting.retrieve(undefined, { next: { revalidate: 300, tags: ['settings'] }, }) ``` The settings follow the language of the client, set with `locale` or `setLocale()`: the country name of the address is translated. ## Legal Pages [#legal-pages] `legal.list()` returns the enabled legal pages for the footer links. Shopper creates four at install, with the slugs `refund`, `privacy`, `terms` and `shipping`. `legal.retrieve()` reads one page by its slug. Here, the footer lists the legal pages with their links, and the privacy page reads its content: ```ts const { data: pages } = await sdk.store.legal.list() pages.map((page) => ({ title: page.title, href: `/legal/${page.slug}` })) const privacy = await sdk.store.legal.retrieve('privacy') privacy.content // '

    Who we are

    ...

    ' ``` `content` is HTML written by the merchant in the admin panel, or `null` when the page is not written yet. A page the merchant disabled throws a `ShopperApiError` with status `404`: hide its link. ## Countries [#countries] `country.list()` pages through the countries, for the country field of an address form. Filter by `region` or by `zone` to offer only the countries the shop ships to, and `country.retrieve()` reads one country by its two-letter or three-letter ISO code. This address form lists the countries of the `EU` zone by name, then reads Cameroon: ```ts const { data: countries } = await sdk.store.country.list({ filter: { zone: 'EU' }, sort: ['name'], page: { size: 100 }, }) const cameroon = await sdk.store.country.retrieve('CM') cameroon.translated_name // 'Cameroun' with setLocale('fr') ``` ## Zones [#zones] A zone groups countries that share a currency, shipping options and payment methods. `zone.list()` returns the enabled zones, and `zone.retrieve()` reads one by its code. The first call lists the zones with their countries and currency, and the second reads the `af` zone with its countries: ```ts const { data: zones } = await sdk.store.zone.list({ include: ['countries', 'currency'] }) const africa = await sdk.store.zone.retrieve('af', { include: ['countries'] }) ``` The [Zones](/3.x/store-api/store#zones) section lists the includes of a zone. ## Currencies [#currencies] `currency.list()` returns the enabled currencies, for a currency switcher. `currency.retrieve()` reads one by its ISO code. This switcher lists the currencies, then reads the euro and its symbol: ```ts const { data: currencies } = await sdk.store.currency.list() const euro = await sdk.store.currency.retrieve('EUR') euro.symbol // '€' ``` ## Picking a Zone and a Currency [#picking-a-zone-and-a-currency] The API never guesses where a visitor is: the storefront decides the zone and sends its code in the `X-Shopper-Zone` header, as [Picking a Zone and a Currency](/3.x/store-api/store#picking-a-zone-and-a-currency) describes. Load the zones with their countries once, keep a map from each country to its zone, and look the visitor's country up in it. The `zoneByCountry()` function below builds that map, from the two-letter code of each country to the code of its zone: ```ts title="lib/zones.ts" import { sdk } from '@/lib/shopper' export async function zoneByCountry(): Promise> { const { data: zones } = await sdk.store.zone.list({ include: ['countries'], page: { size: 100 }, }) const map = new Map() for (const zone of zones) { for (const country of zone.countries ?? []) { if (zone.code) { map.set(country.cca2, zone.code) } } } return map } ``` The country comes from the geolocation header of your CDN, a country selector or the address of a returning customer. Send the zone with the catalog calls through the `headers` of the client or of the call, as [Zone](/3.x/sdk#zone) shows, and set it on the cart with [`cart.update()`](/3.x/sdk/cart#changing-the-currency-or-the-zone). A currency switcher that keeps the zone adds `filter: { currency: 'USD' }` to the catalog calls. ## Next Steps [#next-steps] List the products of the zone, in its currency. Create a cart in the zone of the visitor. # Creating a Starter Kit (/3.x/starter-kits/creating) A starter kit is a Git repository that holds the files of a storefront and a `shopper-kit.yaml` manifest. You do not assemble it by hand: you build the storefront in a Laravel application that runs Shopper, and two Artisan commands turn it into a kit. `shopper:kit:init` creates the kit with its manifest, and `shopper:kit:export` copies the storefront files from the application into it. This page builds `acme/storefront`, a Livewire storefront, then publishes it and lists it on the Shopper website. [Starter Kits](/3.x/starter-kits) covers what the installer does with the kit. ## Developing the Storefront [#developing-the-storefront] The application you build the storefront in is the source of the kit: every file the kit ships is a file of that application, and every Composer package the kit needs is required there. Start from a new Laravel application with Shopper [installed](/3.x/installation), so the kit holds your storefront and nothing else, then write the storefront as in any Laravel project: routes, controllers or Livewire components, views, CSS and JavaScript. You can also start from one of the [official kits](/3.x/starter-kits#available-kits): install it in the application, then change it. Your kit then ships the official kit's files with your changes. The kit is copied into other projects, so its code reads API keys and service credentials from the configuration, never from a value written in a file. Each project sets its own in its `.env` file, which a kit never ships. ## Creating the Kit [#creating-the-kit] Run `shopper:kit:init` from the application. Create the kit next to the application rather than inside it, with the `--path` option, so the kit gets a Git repository of its own: ```bash php artisan shopper:kit:init --path=../storefront ``` Without `--path`, the command creates a folder named after the package, `storefront` in this example, at the root of the application, inside the application's repository. When the folder already exists, the command asks whether to overwrite it, and deletes it if you confirm. The command asks five questions: | Prompt | Default | Used for | |--------|---------|----------| | Kit name | None, required | The `name` of the manifest and the title of the README | | Package name (vendor/name) | None, required | The `name` of `composer.json`, the install command in the README, and the folder name without `--path` | | Description | Empty | The `description` of `composer.json` and of the manifest | | Author | The vendor of the package name | The `author` of the manifest and the author in `composer.json` | | Stack | None, at least one | The `stack` of the manifest | The package name accepts lowercase letters, digits and hyphens on each side of the slash, such as `acme/storefront`. The **Stack** prompt is a searchable list of the technologies the Shopper website knows: type to filter it, move with the arrow keys, press the space bar on each technology the kit uses, then press Enter. The kit starts with three files: ```text storefront/ ├── README.md ├── composer.json └── shopper-kit.yaml ``` The `composer.json` names the package: ```json title="composer.json" { "name": "acme/storefront", "description": "A Livewire storefront for Shopper.", "license": "MIT", "authors": [ { "name": "acme" } ] } ``` The manifest holds your answers, the Shopper, PHP and Laravel versions of Shopper 3, and four paths to export: ```yaml title="shopper-kit.yaml" name: 'Acme Storefront' description: 'A Livewire storefront for Shopper.' version: 1.0.0 author: acme url: '' preview: '' docs: '' stack: [livewire, blade] shopper: ^3.0 php: ^8.3 laravel: ^12.68|^13.27 export_paths: - resources/views - resources/css - resources/js - routes ``` The `README.md` has the kit name, the install command and a link to the Shopper documentation. Replace it before you publish the kit: the Shopper website shows it as the kit's page, as described in [Writing the README](#writing-the-readme). ## The Manifest [#the-manifest] The manifest tells the installer what to copy into a project, which packages to install and which commands to run, and gives the Shopper website what it shows about the kit. Once the storefront is written, the manifest of `acme/storefront` reads: ```yaml title="shopper-kit.yaml" name: 'Acme Storefront' description: 'A Livewire storefront for Shopper.' version: 1.0.0 author: acme url: 'https://github.com/acme/storefront' preview: 'https://demo.example.com' docs: 'https://github.com/acme/storefront#readme' stack: [livewire, blade, alpinejs] shopper: ^3.0 php: ^8.3 laravel: ^12.68|^13.27 screenshots: - .github/screenshots/home.webp - .github/screenshots/product.webp export_paths: - app/Livewire - resources/views - resources/css - resources/js - routes/web.php dependencies: livewire/flux: ^2.20 post_install: - 'php artisan migrate' - 'php artisan storage:link' - 'npm install && npm run build' ``` | Field | Required | Description | |-------|----------|-------------| | `name` | Yes | Name of the kit | | `export_paths` | Yes | Files and directories copied from the application into the kit, then from the kit into each project | | `description` | No | One sentence about the kit | | `version` | No | Version of the kit, `0.0.0` by default | | `author` | No | Author name | | `url` | No | Repository URL | | `shopper` | No | Shopper version constraint, `*` by default | | `php` | No | PHP version constraint, `*` by default | | `laravel` | No | Laravel version constraint, `*` by default | | `dependencies` | No | Composer packages the installer requires in the project, as `package: constraint` | | `dev_dependencies` | No | Composer packages the installer requires as development dependencies | | `post_install` | No | Commands the installer runs in the project once the files are copied | | `stack` | No | Technologies the kit uses | | `preview` | No | URL of a live demo | | `docs` | No | URL of the kit's documentation | | `screenshots` | No | Paths of images in the kit's repository | The Shopper website reads `description`, `version`, `url`, `stack`, `preview`, `docs` and `screenshots` for the kit's page. The installer ignores them, except `version`, which it writes to the [state file](/3.x/starter-kits#the-shopper-kit-state-file) of the project. Keep `version` equal to the Git tag of the release. ### Version Constraints [#version-constraints] Before it copies anything, the installer compares `shopper`, `php` and `laravel` with the project. When a constraint is not met, it prints a warning and asks whether to continue, and `--force` continues without asking. A constraint of `*` is not checked. The Shopper website reads the `shopper` constraint to show which Shopper versions the kit supports, such as 3.x for `^3.0`. ### Export Paths [#export-paths] Each path is relative to the application root, and the installer copies it to the same path in the project. A directory is copied with its files and subdirectories, except hidden files such as `.gitkeep`: list a hidden file on its own line to ship it. List the files your storefront owns rather than whole directories such as `config` or `app`, which would ship every file in them, including the ones each Laravel application already has. The installer asks before it overwrites a file of the project. Some paths never leave a project. The export stops on `composer.json`, `composer.lock`, `shopper-kit.yaml`, `.env`, `vendor`, `node_modules` and `.git`. The installer never copies `.env`, `.env.*`, `composer.json`, `composer.lock`, `vendor`, `.git` and `node_modules`, nor a path that contains `..` or starts with `/`. ### Dependencies [#dependencies] The installer requires the packages of `dependencies` in one `composer require`, then those of `dev_dependencies` with `--dev`. When Composer cannot install one of them, the whole command fails and installs none of its packages: the installer prints a warning and goes on. The export replaces each constraint with the one the application's `composer.json` requires, so you can list a package with `'*'` and let the export write its version. Front-end packages are not dependencies of the manifest: add `package.json` to `export_paths`, and `npm install` to `post_install`. ### Post-install Commands [#post-install-commands] The installer lists the commands and runs them once you confirm, in order, from the project root, with a limit of five minutes each. A command that fails prints a warning, and the next one runs. A command that contains `|`, `&`, `;`, `>` or `<` runs through the shell, so `npm install && npm run build` works. ### Stack and Screenshots [#stack-and-screenshots] The Shopper website shows the `stack` values it knows: `livewire`, `blade`, `inertia`, `alpinejs`, `react`, `vue`, `svelte`, `angular`, `nextjs`, `nuxt`, `remix`, `tanstack`, `astro`, `expo` and `flutter`. A screenshot is the path of an image in the kit's repository, such as `.github/screenshots/home.webp`. The website drops a screenshot given as a URL on another host. Store the images under `.github`, which the export keeps when it [clears the kit](#exporting-the-storefront), and leave them out of `export_paths`: the projects that install the kit do not need them. The export writes the manifest again, in the order shown above. A comment, or a key the manifest does not know, is lost at each export. ## The composer.json File [#the-composerjson-file] The kit's `composer.json` gives Composer the package name, and the kit needs nothing more in it. The installer requires the kit only to read its manifest and copy its files, then removes it from the project. List the packages the storefront needs in the manifest's `dependencies`, not in the `require` of the kit's `composer.json`: only the manifest's packages are added to the project's `composer.json`. The export never changes this file, and `--clear` keeps it. ## Exporting the Storefront [#exporting-the-storefront] Run `shopper:kit:export` from the application, with the path of the kit. A relative path starts from the application root: ```bash php artisan shopper:kit:export ../storefront ``` The command reads the kit's manifest, checks each export path, then copies every path of `export_paths` from the application into the kit, replacing the files already there. It then sets each dependency to the application's constraint and writes the manifest again. The export stops without copying anything when the folder has no manifest, or when an export path is forbidden or missing from the application: ```text No shopper-kit.yaml found at [../storefront]. Run shopper:kit:init first. Export path [.env] is forbidden and cannot be exported. Export path [app/Http/Controllers/Shop] does not exist in your project. ``` It warns, and exports anyway, when a dependency is not required by the application, when a `stack` value is not one the Shopper website knows, and when a screenshot is missing from the kit: ```text Dependency [spatie/laravel-sitemap] is listed in shopper-kit.yaml but not installed in your project. Stack [tailwind] is not a known technology and will not appear on the listing. Screenshot [.github/screenshots/home.webp] does not exist in the kit. ``` The export copies files and never deletes any, so a file you delete or rename in the application stays in the kit. The `--clear` option empties the kit first: ```bash php artisan shopper:kit:export ../storefront --clear ``` It keeps the `.git` and `.github` directories, `README.md`, `CHANGELOG.md`, `LICENSE`, `LICENSE.md`, `composer.json` and the manifest, and deletes everything else, a `.gitignore` included. Export again each time you change the storefront, then commit the changes in the kit's repository. ## Testing the Kit [#testing-the-kit] The installer finds a kit on Packagist, or in a public repository on GitHub, GitLab or Bitbucket, and installs its latest stable version. Test the kit the way a developer installs it: from its repository, in a new application. On GitHub, create a public repository with the path of the package name, `acme/storefront`. Without Packagist, the installer looks for the kit at `github.com/acme/storefront`, then at the same path on Bitbucket and GitLab. Commit the kit and push it: ```bash cd ../storefront git init -b main git add . git commit -m "Release 1.0.0" git remote add origin git@github.com:acme/storefront.git git push -u origin main ``` Tag the version of the manifest and push the tag: ```bash git tag 1.0.0 git push origin 1.0.0 ``` In a new Laravel application with Shopper [installed](/3.x/installation), run the installer with the package name: ```bash php artisan shopper:kit:install acme/storefront ``` Read the installer's output: it goes on after a dependency or a post-install command fails, and prints a warning for each one. Then open the storefront, go through the catalog, the cart and the checkout, and check that `.shopper-kit` lists the files you expect. The installer cannot install a kit that is not pushed and tagged. It looks for the package on Packagist and on the three hosts before Composer runs, so a Composer path repository in the application does not help. Without a tag, Composer only finds the `dev-main` version, which an application that accepts stable versions refuses. To fix something, change the storefront in the application, export, commit, tag a new version and install it again in a new application. ## Publishing the Kit [#publishing-the-kit] A kit reaches developers through its repository, and through the Shopper website once it is [listed](#listing-on-the-shopper-website). ### Versioning [#versioning] Number the releases with [semantic versioning](https://semver.org), and keep the `version` of the manifest equal to the tag. A kit is copied once: a project that installed `1.0.0` never receives `1.1.0`, so describe each change in the changelog, where the developers who installed an earlier version can port it by hand. Release a new major version when the kit moves to a new Shopper major, with its `shopper` constraint. ### Publishing on Packagist [#publishing-on-packagist] Packagist is optional. Without it, the installer finds the kit on GitHub, GitLab or Bitbucket at the path of its package name, and adds the repository to the project's `composer.json` during the install. With Packagist, the repository can have any path. Submit the kit as described for add-ons in [Publishing on Packagist](/3.x/addons/publishing#publishing-on-packagist). ### Writing the README [#writing-the-readme] The Shopper website shows the README of the kit as its page. It drops the first heading, since the page shows the kit's name, removes raw HTML, and turns relative links and images into links to the repository. Describe what the storefront covers, and how to configure it once installed: the services it needs, such as a Stripe key, and the commands to run. The website also reads a `## Features` section: its `###` headings become the groups of features, and the bold text that starts each bullet becomes a feature. ````markdown title="README.md" # Acme Storefront A Livewire storefront for Shopper. ## Features ### Catalog - **Product listing** with filters by category and brand - **Search** on product names ### Checkout - **One-page checkout** with Stripe ## Installation ```bash php artisan shopper:kit:install acme/storefront ``` ```` The website shows `CHANGELOG.md` as the kit's release notes. ## Listing on the Shopper Website [#listing-on-the-shopper-website] The Shopper website lists the kits of the [starter kit registry](https://github.com/shopperlabs/starter-kits), a public repository. You list a kit with a pull request that adds it to the registry. Fork `shopperlabs/starter-kits` on GitHub. Add an entry for the kit to the `kits` array of `registry.json`: ```json title="registry.json" { "name": "Acme Storefront", "slug": "acme-storefront", "package": "acme/storefront", "repo": "acme/storefront", "description": "A Livewire storefront for Shopper with a one-page Stripe checkout.", "author": "acme", "shopper": "^3.0", "tags": ["livewire", "storefront"], "official": false, "preview": null } ``` Open a pull request to the registry. A workflow validates the entry, and the kit is listed once the pull request is merged. | Field | Value | |-------|-------| | `name` | Name of the kit | | `slug` | Unique identifier in the website URL, lowercase letters, digits and hyphens | | `package` | The Composer name, `vendor/name` | | `repo` | The GitHub repository, `owner/repo` | | `description` | 10 to 200 characters | | `author` | Author or organization name | | `shopper` | Shopper version constraint, such as `^3.0` | | `tags` | At least one, lowercase, such as `livewire`, `inertia`, `blade`, `vue`, `react`, `storefront`, `headless` or `minimal` | | `official` | `false`: only the kits Shopper maintains are official | | `preview` | URL of a live demo, or `null` | The workflow checks the JSON against the registry's schema, refuses a `slug` or a `package` already in the registry, and checks that the GitHub repository exists and has a `shopper-kit.yaml` at its root. Once the entry is merged, the website reads the manifest, the README and the changelog from the default branch of the repository, along with the date of its last push. It shows the manifest's name, description, version, stack, requirements, dependencies, preview, documentation link and screenshots, and falls back to the registry entry for a description or a preview the manifest leaves empty. The website refreshes this every 24 hours, so a change to the repository can take a day to show. A kit whose manifest the website cannot read does not appear. # Starter Kits (/3.x/starter-kits) Shopper ships the admin panel and the commerce models, and no storefront. You build the customer side with the technology you prefer: Blade, Livewire or Inertia inside your Laravel application, or a separate front end on the [Store API](/3.x/store-api). If you would rather start from a working storefront than from a blank page, Shopper provides **Starter Kits**. A kit is a complete storefront (catalog pages, cart, checkout with Stripe and customer accounts) that the installer copies into your Laravel application. Once installed, the code belongs to you. Modify anything, delete what you don't need, or use it as a reference to build something different. ## Available Kits [#available-kits] Shopper maintains three kits. They cover the same pages: a home page, the product listing with categories, collections and search, the product page, the cart, a checkout that takes payment with Stripe, and a customer account with orders, addresses, and profile and security settings. They differ in the front-end stack. ### Livewire [#livewire] The [Livewire Starter Kit](/3.x/livewire-starter-kit) is a Laravel storefront built with [Livewire](https://livewire.laravel.com/), [Flux UI](https://fluxui.dev) and [Tailwind CSS](https://tailwindcss.com/). Every page is a Livewire component rendered with Blade. Because the Shopper admin panel is also built with Livewire, you can reuse patterns and components across your admin and storefront. ### React [#react] The [React Starter Kit](/3.x/react-starter-kit) is an [Inertia](https://inertiajs.com/) storefront built with [React](https://react.dev/), TypeScript, [shadcn/ui](https://ui.shadcn.com/) and [Tailwind CSS](https://tailwindcss.com/). Laravel controllers pass the data to each page, so there is no separate API layer, and [Wayfinder](https://github.com/laravel/wayfinder) generates typed functions for the Laravel routes the pages call. ### Vue [#vue] The [Vue Starter Kit](/3.x/vue-starter-kit) is an [Inertia](https://inertiajs.com/) storefront built with [Vue](https://vuejs.org/), TypeScript, [shadcn-vue](https://www.shadcn-vue.com/) and [Tailwind CSS](https://tailwindcss.com/). Like the React kit, it renders Inertia pages from Laravel controllers and calls the routes through Wayfinder. ## Installing a Starter Kit [#installing-a-starter-kit] A kit installs into a Laravel application where Shopper is installed. Start from a new application: the kit replaces files that the Laravel skeleton ships. Create a new Laravel 12 or 13 application: ```bash composer create-project laravel/laravel my-store cd my-store ``` Install Shopper and create your admin user, as described in [Installation](/3.x/installation). Run the installer with the package name of the kit: ```bash php artisan shopper:kit:install shopperlabs/livewire-starter-kit ``` The installer asks before it overwrites each file of your application, then before it runs the kit's post-install commands. Follow the page of the kit you installed: it lists the settings to add to `.env`, such as your Stripe keys, and how to build the front-end assets. The other kits install the same way, with `shopperlabs/react-starter-kit` or `shopperlabs/vue-starter-kit`. ## How It Works [#how-it-works] The `shopper:kit:install` command is built into Shopper, so no additional package is required. It performs the following pipeline: 1. **Backup** your `composer.json` for rollback if anything fails 2. **Detect** the kit package on Packagist, GitHub, Bitbucket, or GitLab 3. **Download** the kit temporarily via `composer require` 4. **Read** the `shopper-kit.yaml` manifest from the kit package 5. **Validate** PHP, Laravel, and Shopper version constraints, and ask whether to continue when one is not met 6. **Copy** files from the kit into your project according to `export_paths` 7. **Install** Composer dependencies declared in the manifest 8. **Run** post-install commands (migrations, storage link, asset build), after you confirm them 9. **Write** a `.shopper-kit` state file tracking installed files with SHA-256 hashes 10. **Remove** the kit package, and the repository entry added in step 2, from your `composer.json` 11. **Clean up** the backup file After installation, every file lives in your project. The kit package is gone from your dependencies. The [manifest](/3.x/starter-kits/creating#the-manifest) of the kit decides which files are copied, which packages are installed and which commands run. Install a kit on a new application. A kit replaces files that the Laravel skeleton ships, such as `routes/web.php` and `bootstrap/app.php`, and the Inertia kits also replace `package.json`. The installer asks before overwriting each existing file. The command accepts four options: | Option | Description | |--------|-------------| | `--force` | Skip every confirmation: overwrite existing files, run the post-install commands, and continue when a version constraint is not met | | `--path=` | Copy the kit files, run the post-install commands and write the state file in another directory than the project root | | `--no-deps` | Skip the Composer dependencies declared in the manifest | | `--no-post-install` | Skip the post-install commands | ## The `.shopper-kit` State File [#the-shopper-kit-state-file] After installation, a `.shopper-kit` file is created at the root of your project. It records which kit was installed, its version, and the SHA-256 hash of every copied file. ```json title=".shopper-kit" { "kit": "shopperlabs/livewire-starter-kit", "version": "2.0.0", "installed_at": "2026-11-20T14:32:00+00:00", "files": { "app/Livewire/Pages/Home.php": "3f1c9b0e7d4a5c2e8b6f0a1d9e7c5b3a2f4e6d8c0b1a3f5e7d9c2b4a6e8f0d1c", "resources/views/pages/home.blade.php": "9a2e4c6b8d0f1e3a5c7b9d2f4e6a8c0b1d3f5e7a9c2b4d6f8e0a1c3b5d7f9e2a" } } ``` Commit this file. When you run `shopper:kit:install` again in the same project, the installer reads it and asks before installing over the existing kit. The hashes record each file as the kit shipped it, so you can tell later which files you changed. ## Starter Kits vs Themes [#starter-kits-vs-themes] Starter kits are not themes. In Shopper, a [theme](/3.x/themes) only sets the colors of the admin panel. On e-commerce platforms that ship storefront themes, a theme is a runtime dependency: the store relies on it, receives its updates, and can switch to another one from the admin. A starter kit is scaffolding used once: the installer copies files into your project, installs dependencies, and removes itself. There is no package to update and nothing active at runtime. If you want to "switch" starter kits, you start a new project. This is by design: you get full ownership and can change every line of code, at the cost of not being able to swap front ends with a click. ```text Starter Kit Storefront theme -------------------------------- -------------------------------- Scaffold, used once Runtime, active permanently Code belongs to the developer Managed by the platform Not switchable Switchable from admin Manual merge for updates Update = dependency upgrade ``` ## Scope [#scope] A starter kit installs into a Laravel application: the installer is an Artisan command that copies files into the project and adds Composer packages to it. The kits available today render the storefront from Laravel, with Livewire or Inertia, and read the Shopper models directly. A storefront that runs on its own server, such as a Next.js or Nuxt site or a mobile app, calls the [Store API](/3.x/store-api) instead. The [Storefront](/3.x/storefront) page compares the two approaches. ## Creating Your Own Starter Kit [#creating-your-own-starter-kit] Any storefront you build on Shopper can become a starter kit. You write it in a Laravel application, create the kit with `shopper:kit:init`, copy the storefront into it with `shopper:kit:export`, and publish it on GitHub, GitLab, Bitbucket or Packagist. Anyone can then install it with `shopper:kit:install`, and a pull request to the starter kit registry lists it on the Shopper website. Scaffold, export, test, publish and list your own kit. ## Frequently Asked Questions [#frequently-asked-questions] ### How do I update a kit I installed? [#how-do-i-update-a-kit-i-installed] There is nothing to update: the files belong to your project, and a new version of the kit only reaches the projects that install it afterwards. To bring a fix from a new version into your store, read the kit's changelog and apply the change by hand. The hashes of the [state file](#the-shopper-kit-state-file) tell you which files you changed since the install, and which ones you can replace with the new version as they are. ### Can I install a kit in an existing application? [#can-i-install-a-kit-in-an-existing-application] The installer runs in any Laravel application where Shopper is installed, and asks before it overwrites each file. In an application that already has its own routes, layouts or `package.json`, overwriting them breaks what you built, and refusing leaves the kit incomplete. Install the kit in a new application instead, then copy the parts you want into yours. # Authentication (/3.x/store-api/authentication) Most of the Store API answers without any credentials, so a visitor can browse the catalog, fill a cart and check out as a guest. A customer account adds a profile, saved addresses, an order history and carts that follow the customer from one device to another. The API identifies a customer with a bearer token issued by [Laravel Sanctum](https://laravel.com/docs/sanctum) at registration and login. This page follows the life of that token: register or log in to get one, send it on each request, then log out or reset the password. ## Endpoints [#endpoints] The authentication endpoints sit under `/store/auth`. All of them except logout are public and share the `shopper-api-auth` rate limit of 20 requests per minute per IP address, described in [Rate Limits](/3.x/store-api#rate-limits). Create a customer account and return a token Check the email and password and return a token Revoke the token sent with the request Email a password reset link Set a new password from the reset link The request bodies are flat JSON objects sent with `Content-Type: application/json`, as on every Store API route. ## Guest and Customer Requests [#guest-and-customer-requests] A request without an `Authorization` header is a guest request. A guest can call every public route: the catalog, the store settings, the regions, the cart and its checkout, and the order confirmation lookup. A guest checkout only needs an email on the cart, as the [Checkout](/3.x/store-api/checkout) guide shows. A request with a valid customer token runs as that customer. The token gives access to: - the routes under `/store/customers/me`: profile, avatar, addresses, order history and digital downloads, covered in the [Customers](/3.x/store-api/customers) and [Orders](/3.x/store-api/orders) guides; - `POST /store/carts/{cartId}/transfer`, which attaches a guest cart to the customer; - the carts that belong to the customer. A cart attached to a customer answers `404 Not Found` to any request that does not carry that customer's token, so a cart ID alone never exposes a customer's cart; - prices calculated for the customer. The API passes the customer to the price resolver, which ignores it by default; a custom resolver can return customer group prices, as described on the [Pricing](/3.x/pricing) page. The same public route can answer differently for a guest and for a customer, which is why product responses that include calculated prices carry `Vary: Authorization`. ## Registering a Customer [#registering-a-customer] Registration creates the account and logs the customer in at once: the response carries the token, so the storefront does not need a second call to log in. Send the guest cart ID in `cart_id` to keep the products the visitor added before signing up. Comma-separated attributes to return, such as `first_name,last_name`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). The last name of the customer, up to 255 characters. The first name of the customer, up to 255 characters. A valid email address, up to 255 characters, not used by another account. The password. It follows the application's `Password::defaults()` rule: at least 8 characters unless your application sets other defaults. Whether the customer accepts marketing emails. The ID of a guest cart to attach to the new account. This request creates the account of Camille Martin and attaches her guest cart: ```bash title="Request" curl -X POST "http://localhost:8000/store/auth/register" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{ "first_name": "Camille", "last_name": "Martin", "email": "camille.martin@example.com", "password": "sneakers-in-paris", "opt_in": true, "cart_id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C" }' ``` The API answers `201 Created` with the customer and, in `meta`, the token and the ID of the customer's cart: ```json title="Response 201" { "data": { "id": "01JD9B2K7X4N8R3T6V1Y5Z0QWE", "type": "customers", "attributes": { "first_name": "Camille", "last_name": "Martin", "email": "camille.martin@example.com", "avatar": "https://ui-avatars.com/api/?name=Camille+Martin&color=1d4ed8&background=dbeafe", "avatar_type": null, "phone_number": null, "gender": null, "birth_date": null, "opt_in": true, "email_verified": false, "created_at": "2026-11-19T10:24:31+00:00" } }, "meta": { "token": "3|Xk9mWqT2xLp8RzN6vHc1YbJ7sDe5GaU0iOk3nQw49e8b7c6d", "cart_id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C" } } ``` Store `meta.token` where your storefront keeps credentials, such as an `httpOnly` cookie set by your storefront server, and replace the cart ID you kept with `meta.cart_id`. The `avatar_type` attribute is `null` in this response and `avatar_ui` once the customer is read again, for instance at the next login. The account gets the customer role set in `roles.user` of `config/shopper/admin.php`, and Shopper fires the `Shopper\Core\Events\Customers\CustomerRegistered` event once the account is saved. Listen to it to send a welcome email or sync the customer to a mailing tool. An email already in use answers `422 Unprocessable Content` with the `unique` code on the `email` field. The [Errors](/3.x/store-api/errors#validation-errors) page shows the full shape: ```json title="Response 422" { "errors": [ { "status": "422", "code": "unique", "title": "Unprocessable Content", "detail": "The email has already been taken.", "source": { "pointer": "/data/attributes/email" } } ] } ``` | Status | Code | When | |--------|------|------| | 422 | `unique` | `email` is used by another account | | 422 | Rule name, such as `required` | Another field fails validation, `password` for a password the `Password::defaults()` rule refuses | ### What Happens to the Guest Cart [#what-happens-to-the-guest-cart] The `cart_id` sent at registration or login never makes the call fail. The API attaches the cart when it is an open cart that belongs to no customer, or to this customer, and ignores it otherwise: an unknown ID, a completed cart or a cart of another customer. When the customer already has an open cart, the guest cart is merged into it and `meta.cart_id` is the ID of that existing cart, not the one you sent. When the guest cart cannot be attached, for example because its payment session is already collected, `meta.cart_id` is the guest cart ID. Without `cart_id`, `meta.cart_id` is the latest open cart of the customer, or `null` when there is none. In every case, `meta.cart_id` is the cart your storefront uses from then on. ## Logging In [#logging-in] Login checks an email and a password and issues a new token. Like registration, it takes an optional `cart_id` to bring the guest cart into the customer's account. Comma-separated attributes to return, such as `first_name,last_name`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). The email address of the account. The password of the account. The ID of a guest cart to attach to the customer, as described in [What Happens to the Guest Cart](#what-happens-to-the-guest-cart). This request logs Camille Martin in, and brings her guest cart into her account with `cart_id`: ```bash title="Request" curl -X POST "http://localhost:8000/store/auth/login" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{ "email": "camille.martin@example.com", "password": "sneakers-in-paris", "cart_id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C" }' ``` The API answers `200 OK` with the same document as registration: ```json title="Response 200" { "data": { "id": "01JD9B2K7X4N8R3T6V1Y5Z0QWE", "type": "customers", "attributes": { "first_name": "Camille", "last_name": "Martin", "email": "camille.martin@example.com", "avatar": "https://ui-avatars.com/api/?name=Camille+Martin&color=1d4ed8&background=dbeafe", "avatar_type": "avatar_ui", "phone_number": null, "gender": null, "birth_date": null, "opt_in": true, "email_verified": false, "created_at": "2026-11-19T10:24:31+00:00" } }, "meta": { "token": "4|Pq7Hn2Lw9Xc4Vb8Mz1Rt6Ky3Jd5Sf0Ga2Ue8Wo1N9c1d2e3f", "cart_id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C" } } ``` Each login creates a new token and leaves the others valid, so a customer can stay logged in on a phone and a laptop at the same time. A wrong email or password answers `422 Unprocessable Content` with the `credentials_invalid` code on the `email` field. The message does not say which of the two is wrong: ```json title="Response 422" { "errors": [ { "status": "422", "code": "credentials_invalid", "title": "Unprocessable Content", "detail": "These credentials do not match our records.", "source": { "pointer": "/data/attributes/email" } } ] } ``` | Status | Code | When | |--------|------|------| | 422 | `credentials_invalid` | The email and the password match no account | | 422 | Rule name, such as `required` | A field fails validation | ### Failed Logins [#failed-logins] Failed logins are counted per email address and IP address, the key Laravel's own login throttling uses, so an attacker on another network cannot lock a customer out. After 5 failures within a minute (`login_failures` in `config/shopper/http.php`), the API refuses the next attempts for that email from that address, even with the right password, until the minute has passed. A successful login clears the count. A refused attempt answers `429 Too Many Requests` with the `rate_limited` code and a `Retry-After` header that gives the seconds to wait: ```json title="Response 429" { "errors": [ { "status": "429", "code": "rate_limited", "title": "Too Many Requests", "detail": "Too many login attempts. Please try again in 42 seconds." } ] } ``` Show the `detail` to the customer, or a countdown built from `Retry-After`. Shopper fires Laravel's `Illuminate\Auth\Events\Lockout` event on each refused attempt. ## Using the Token [#using-the-token] Send the token in the `Authorization` header with the `Bearer` scheme, on every request of the customer, public routes included, so that the API knows who owns the cart: ```bash title="Request" curl "http://localhost:8000/store/customers/me" \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 4|Pq7Hn2Lw9Xc4Vb8Mz1Rt6Ky3Jd5Sf0Ga2Ue8Wo1N9c1d2e3f" ``` The token carries the `store` ability. The API accepts only tokens that carry it, so a Sanctum token your application issues for another purpose answers `401 Unauthorized` on every Store API route. An expired or revoked token is handled differently by the two route groups: | Route group | Missing token | Expired or revoked token | |-------------|---------------|--------------------------| | Public | Runs as a guest | Runs as a guest: a cart that belongs to the customer answers `404 Not Found` | | Authenticated | `401 Unauthorized` | `401 Unauthorized` | The `401` answer carries the `unauthenticated` code: ```json title="Response 401" { "errors": [ { "status": "401", "code": "unauthenticated", "title": "Unauthorized", "detail": "Unauthenticated." } ] } ``` On a `401`, or on a `404` for the customer's own cart, drop the stored token and send the customer to the login page. Keep the cart ID: logging in again with `cart_id` attaches the cart back. ## Token Expiration [#token-expiration] A token stays valid for 30 days after login or registration. Change the lifetime in minutes with `SHOPPER_API_TOKEN_EXPIRATION`, or set it to `0` to keep tokens until the customer logs out or resets the password. There is no refresh endpoint: when a token expires, the customer logs in again. ```bash title=".env" SHOPPER_API_TOKEN_EXPIRATION=10080 ``` The `expiration` key of `config/sanctum.php` also applies to these tokens when your application sets it, and the shorter of the two lifetimes wins. Expired tokens stay in the `personal_access_tokens` table until the daily `sanctum:prune-expired --hours=24` task deletes them, once the [scheduler runs](/3.x/installation#run-the-scheduler-and-a-queue-worker). ## Logging Out [#logging-out] Logout revokes the token sent with the request and leaves the customer's other tokens valid, so logging out on a phone keeps the laptop session. The route belongs to the authenticated group, so it needs a valid token: ```bash title="Request" curl -X POST "http://localhost:8000/store/auth/logout" \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 4|Pq7Hn2Lw9Xc4Vb8Mz1Rt6Ky3Jd5Sf0Ga2Ue8Wo1N9c1d2e3f" ``` The API answers `204 No Content`. The customer's cart stays attached to the account and comes back in `meta.cart_id` at the next login. | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The token is missing, expired, revoked or not a store token | ## Resetting a Password [#resetting-a-password] A password reset takes two calls: the first sends an email with a link to your storefront, the second sends the new password with the token from that link. It uses Laravel's password broker, so the `passwords.users` settings of `config/auth.php` apply: a reset token expires after 60 minutes, and a second email to the same address is not sent within 60 seconds of the first. The reset email must link to the reset page of your storefront. Set that link before the storefront shows its "Forgot password" form, in the `boot` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use Illuminate\Auth\Notifications\ResetPassword; public function boot(): void { ResetPassword::createUrlUsing(function (object $notifiable, string $token): string { return 'https://shop.example.com/reset-password?token='.$token.'&email='.urlencode($notifiable->getEmailForPasswordReset()); }); } ``` The email is sent by the user model's `Notifiable` trait, through the mail settings of your application. The email address the customer typed in the form. Your storefront's "Forgot password" form sends the email address: ```bash title="Request" curl -X POST "http://localhost:8000/store/auth/forgot-password" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"email": "camille.martin@example.com"}' ``` The API answers `202 Accepted` with an empty body whether or not an account uses that email, so the form cannot reveal who has an account. Show the same message in both cases, such as "If an account exists for this email, a reset link is on its way." | Status | Code | When | |--------|------|------| | 422 | Rule name, such as `email` | `email` is missing or not a valid email address | The `token` of the reset link. The `email` of the reset link. The new password, checked by the same `Password::defaults()` rule as at registration. Your reset page reads `token` and `email` from the link and sends them with the new password. The password follows the same rule as at registration; the API does not ask for a confirmation field, so compare the two inputs in your form. ```bash title="Request" curl -X POST "http://localhost:8000/store/auth/reset-password" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{ "token": "8f14e45fceea167a5a36dedd4bea2543b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6", "email": "camille.martin@example.com", "password": "new-sneakers-2026" }' ``` The API answers `204 No Content`. The reset revokes every token of the customer, so all devices are logged out, and fires Laravel's `Illuminate\Auth\Events\PasswordReset` event. The customer then logs in with the new password. An expired, used or wrong token answers `422 Unprocessable Content` with the `reset_token_invalid` code on the `email` field. Offer to send a new link: ```json title="Response 422" { "errors": [ { "status": "422", "code": "reset_token_invalid", "title": "Unprocessable Content", "detail": "This password reset token is invalid.", "source": { "pointer": "/data/attributes/email" } } ] } ``` | Status | Code | When | |--------|------|------| | 422 | `reset_token_invalid` | The token is expired, used or wrong for this email | | 422 | Rule name, such as `required` | A field fails validation, `password` for a password the `Password::defaults()` rule refuses | ## Next Steps [#next-steps] With a token in hand, the storefront can read the customer's account and attach carts to it. Read and update the profile, the avatar and the saved addresses. Create a cart as a guest or as a customer and add products to it. Handle the error codes the authentication endpoints return. # Cart (/3.x/store-api/cart) A storefront keeps the shopping basket of a visitor in a Shopper cart. The Store API creates the cart, prices every line from the catalog, checks stock, applies promotion codes, computes tax once a shipping address is known, and returns the totals with every response. The storefront never computes a price: it sends what the customer picked and renders the cart the API answers with. Every amount in a cart response is an integer in cents: a line priced at €90.00 carries `9000`. The [Money](/3.x/money) page covers cents and formatting. The [Checkout](/3.x/store-api/checkout) guide picks up where this page ends, with shipping, payment and the order. ## Endpoints [#endpoints] The cart endpoints sit in the public route group: they work without a customer token, and with one. The ones that create or add things share the checkout rate limit of 30 requests per minute (`shopper.http.rate_limiters`), on top of the general limit described in [Rate limits](/3.x/store-api#rate-limits). On these public routes both limits count requests per IP address, for guests and logged-in customers alike. Create a cart Read a cart Change the currency, zone, email or metadata Add a product or a variant Change the quantity or metadata of a line Remove a line Set the shipping and billing addresses Apply a promotion code Remove one or every promotion code Request bodies are flat JSON objects, such as `{"quantity": 2}`, sent with `Content-Type: application/json`. Responses are JSON:API documents, described in [JSON:API Conventions](/3.x/store-api/json-api). Every endpoint of this page answers with the whole cart, so the storefront re-renders from the response without a second call. ## Creating a Cart [#creating-a-cart] A storefront creates the cart the first time the visitor adds something, and keeps its ID for every later call. The cart takes its zone from the `X-Shopper-Zone` header of this request, or the default zone when the header is missing, as described in [Request headers](/3.x/store-api#request-headers). The zone sets the prices, the shipping options and the payment methods the cart offers. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). ISO code of an enabled currency of the shop, such as `EUR`. Upper-cased before validation. Defaults to the currency of the zone, then to the default currency of the shop. Contact email of the checkout, lower-cased. Up to 255 characters. Your own data, such as a gift note or a tracking source. Up to 50 keys and 4,096 characters once encoded as JSON. Every parameter is optional, so an empty body creates a cart in the currency of the zone: ```bash title="Request" curl -X POST http://localhost:8000/store/carts \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -H "X-Shopper-Zone: EU" \ -d '{"email": "camille.martin@example.com"}' ``` The API answers `201 Created` with the new cart. Its `id` is the cart ID the storefront stores: ```json title="Response 201" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "email": "camille.martin@example.com", "promotions": [], "completed_at": null, "metadata": null, "lines_count": 0, "lines_quantity": 0, "subtotal": 0, "discount_total": 0, "tax_total": 0, "shipping_total": 0, "total": 0, "tax_inclusive": false, "shipping_option_id": null, "created_at": "2026-11-19T10:15:00+00:00", "updated_at": "2026-11-19T10:15:00+00:00" } } } ``` A `currency_code` that is unknown, disabled or not one of the shop currencies answers `422` with the code `exists` on `/data/attributes/currency_code`. | Status | Code | When | |--------|------|------| | 422 | `exists` | `currency_code` is unknown, disabled or not one of the shop currencies | | 422 | Rule name, such as `email` | Another field fails validation | | 400 | `bad_request` | An `include` path outside the cart list | ## Guest and Customer Carts [#guest-and-customer-carts] Who can use a cart depends on the request that created it. A request without a customer token creates a guest cart. A request with the bearer token of a logged-in customer, described in [Logging in](/3.x/store-api/authentication#logging-in), creates a cart that belongs to that customer. Send the same token on every later call for that cart. A guest cart has no owner: any request that carries its ID can read and change it. The ID is a ULID, 26 characters with 80 random bits, so it cannot be guessed, but it works like a session token. Keep it where the visitor's session lives, such as an `HttpOnly` cookie or the secure storage of a mobile app, and keep it out of URLs, logs and analytics events. A customer cart answers only to its owner. A request without the token, or with the token of another customer, gets `404 not_found`, the same answer as an ID that does not exist, so the API never confirms that a cart exists. An expired or revoked token counts as no token, so the customer cart also answers `404` once the token expires: log the customer in again before creating a new cart. A valid token without the `store` ability answers `401 unauthenticated`, even on these public routes. When a guest logs in during checkout, transfer the guest cart to the customer with the cart transfer endpoint described in [Customers](/3.x/store-api/customers). The cart then answers only to that customer. A completed cart, one that became an order, stays readable with the same ID. Any change to it answers `409 cart_completed`. Open carts that see no activity for 30 days are deleted by the scheduled `shopper:prune-carts` command, as the [Cart](/3.x/cart) page describes, so a storefront that gets `404` on a stored ID creates a new cart. ## Adding a Line [#adding-a-line] A line is one product or one variant in the cart, with its quantity. The storefront sends the type and the public ID of what the customer picked; the API finds it in the catalog, prices it in the cart currency and checks stock. The client never sends a price. The cart ID, the `id` returned by [Creating a Cart](#creating-a-cart). Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). `variant` for a product variant, `product` for a product without variants. The public ID of the variant or the product, the `id` the [Catalog](/3.x/store-api/catalog) endpoints return. Quantity to add, from 1 to 1,000,000. Data of this line, such as an engraving text. Same limits as the cart metadata. This request adds two pairs of Classic Leather Sneakers in size 42, black, and asks for the lines in the same response with `include=lines`: ```bash title="Request" curl -X POST "http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/lines?include=lines" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{ "purchasable_type": "variant", "purchasable_id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "quantity": 2 }' ``` The API answers `200 OK` with the recalculated cart. The line carries the unit price frozen when it was added: ```json title="Response 200" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "email": "camille.martin@example.com", "promotions": [], "completed_at": null, "metadata": null, "lines_count": 1, "lines_quantity": 2, "subtotal": 18000, "discount_total": 0, "tax_total": 0, "shipping_total": 0, "total": 18000, "tax_inclusive": false, "shipping_option_id": null, "created_at": "2026-11-19T10:15:00+00:00", "updated_at": "2026-11-19T10:16:12+00:00" }, "relationships": { "lines": { "data": [ { "id": "01JD8Z7C1E3G5J7K9N1Q3S5V7W", "type": "cart-lines" } ] } } }, "included": [ { "id": "01JD8Z7C1E3G5J7K9N1Q3S5V7W", "type": "cart-lines", "attributes": { "purchasable_type": "variant", "quantity": 2, "unit_price_amount": 9000, "is_custom_price": false, "subtotal": 18000, "discount_total": 0, "tax_total": 0, "adjustments": [], "tax_lines": [], "metadata": null, "created_at": "2026-11-19T10:16:12+00:00", "updated_at": "2026-11-19T10:16:12+00:00" } } ] } ``` Adding the same variant again adds to the quantity of its existing line instead of creating a second line. When the new request carries metadata that differs from the metadata of that line, the API refuses with `422 cart_line_metadata_conflict`: update that line or remove it first. | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `purchasable_unavailable` | The product or variant cannot be bought | | 422 | `variant_required` | The product is sold through its variants | | 422 | `price_missing` | No price in the cart currency | | 422 | `stock_insufficient` | Not enough stock for the quantity | | 422 | `quantity_rule_violated` | The quantity breaks a minimum, maximum or increment, details in `meta` | | 422 | `cart_line_metadata_conflict` | The line already exists with other metadata | | 422 | Rule name, such as `required` | A field fails validation | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | ### Products and Variants [#products-and-variants] A product that has variants is sold through them. Adding such a product with `purchasable_type: "product"` answers `422 variant_required` on `/data/attributes/purchasable_id`: the storefront asks the customer for a size or a color and adds the variant. The [Catalog](/3.x/store-api/catalog) guide shows how to read the variants of a product, and [Product Variants](/3.x/product-variants) explains how they are built. The API accepts a product when it is published and not an external product, and a variant when its product is published. Anything else answers `422 purchasable_unavailable` on `/data/attributes/purchasable_id`. A purchasable that has prices, but none in the cart currency, answers `422 price_missing` on `/data/attributes/purchasable_id`. ### Stock and Quantity Rules [#stock-and-quantity-rules] The API checks stock when a line is added or its quantity changes. A variant or product that tracks its inventory and does not allow backorders answers `422 stock_insufficient` on `/data/attributes/quantity` when the stock cannot cover the quantity. The check runs again when the order is placed, as the [Checkout](/3.x/store-api/checkout) guide explains. A price can carry quantity rules (a minimum, a maximum, an increment), described in [Pricing](/3.x/pricing). A quantity that breaks one answers `422 quantity_rule_violated` with a `meta` object, so the storefront can correct the quantity selector: ```json title="Response 422" { "errors": [ { "status": "422", "code": "quantity_rule_violated", "title": "Unprocessable Content", "detail": "This item must be ordered in multiples of 2.", "source": { "pointer": "/data/attributes/quantity" }, "meta": { "purchasable_id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "quantity": 3, "minimum": 2, "maximum": null, "increment": 2 } } ] } ``` ## Reading a Cart [#reading-a-cart] A storefront reads the cart to render the basket page or the mini cart. The totals come with the cart, so one request is enough: the API reuses the stored totals when they were calculated in the last 15 minutes (`shopper.cart.totals_ttl_minutes`) and recalculates them otherwise. The cart ID, the `id` returned by [Creating a Cart](#creating-a-cart). Related resources to return with the cart, comma-separated, from the table below. Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). The cart document carries only the cart attributes by default. The `include` query parameter adds related resources, as described in [Includes](/3.x/store-api/json-api#includes). The cart accepts these paths, which `CartResource` declares in its `includes()` method: | Include | Adds | |---------|------| | `lines` | The cart lines | | `lines.purchasable` | The lines and the variant or product of each line | | `lines.purchasable.product` | The same, plus the parent product of each variant | | `addresses` | The shipping and billing addresses | | `paymentMethod` | The payment method chosen at checkout | Any other path answers `400 bad_request`. A basket page asks for `lines.purchasable` to show the variant of each line, or `lines.purchasable.product` to add the parent product and its images: ```bash title="Request" curl "http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C?include=lines.purchasable" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK`. In this trimmed response, the cart keeps its totals and the variant keeps three of its attributes; the [Catalog](/3.x/store-api/catalog) guide lists them all: ```json title="Response 200" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "lines_count": 1, "lines_quantity": 2, "subtotal": 18000, "discount_total": 0, "tax_total": 0, "shipping_total": 0, "total": 18000, "tax_inclusive": false }, "relationships": { "lines": { "data": [ { "id": "01JD8Z7C1E3G5J7K9N1Q3S5V7W", "type": "cart-lines" } ] } } }, "included": [ { "id": "01JD8Z7C1E3G5J7K9N1Q3S5V7W", "type": "cart-lines", "attributes": { "purchasable_type": "variant", "quantity": 2, "unit_price_amount": 9000, "subtotal": 18000 }, "relationships": { "purchasable": { "data": { "id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "type": "variants" } } } }, { "id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "type": "variants", "attributes": { "name": "42 / Black", "sku": "CLS-BLK-42", "prices": [ { "public_id": "01JD8YR6A8C0E2G4J6K8N0Q2S4", "amount": 9000, "compare_amount": null, "currency_code": "EUR" }, { "public_id": "01JD8YR6A8C0E2G4J6K8N0Q2S5", "amount": 9900, "compare_amount": null, "currency_code": "USD" } ] } } ] } ``` | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 400 | `bad_request` | An `include` path outside the cart list | Render the price of a line from `unit_price_amount` and `subtotal` of the line, not from the `prices` of the variant: the line keeps the price it was added at, which can differ from the current catalog price until checkout checks it again. ## Updating and Removing Lines [#updating-and-removing-lines] The quantity selector of the basket page changes a line through its ID, the `id` of the `cart-lines` resource. A quantity of zero is not accepted: removing a line has its own endpoint. The cart ID. The `id` of the `cart-lines` resource. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). New quantity of the line, from 1 to 1,000,000. Checked against stock and quantity rules like an added line. New metadata of the line. `null` clears it. This request brings the line of sneakers from two pairs down to one: ```bash title="Request" curl -X PATCH http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/lines/01JD8Z7C1E3G5J7K9N1Q3S5V7W \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"quantity": 1}' ``` The API answers `200 OK` with the cart. | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request, or no line with this ID in the cart | | 422 | `stock_insufficient` | Not enough stock for the quantity | | 422 | `quantity_rule_violated` | The quantity breaks a minimum, maximum or increment, details in `meta` | | 422 | Rule name, such as `min` | A field fails validation | | 409 | `cart_line_locked` | The line has a custom price | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | The cart ID. The `id` of the `cart-lines` resource. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). Removing the line works the same way and also answers `200 OK` with the recalculated cart, not an empty `204`: ```bash title="Request" curl -X DELETE http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/lines/01JD8Z7C1E3G5J7K9N1Q3S5V7W \ -H "Accept: application/vnd.api+json" ``` | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request, or no line with this ID in the cart | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | A line ID that does not belong to the cart answers `404 not_found`. A line with `is_custom_price: true` holds a price negotiated in the back office: its quantity cannot change and the API answers `409 cart_line_locked`. The storefront can still remove it. ## Addresses [#addresses] The cart needs a shipping address before checkout: taxes, live carrier rates and the order addresses come from it. One request sets the shipping address, the billing address, or both, and can set the contact email at the same time. Sending an address type again replaces the previous one. The cart ID. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). Each address object takes the same fields, listed under each one: The delivery address. Required when `billing_address` is missing. First name, up to 255 characters. Last name, up to 255 characters. Company name, up to 255 characters. Street and number. Apartment, floor or building. City. State or province. Tax rules of a province match on this value. Postal code. Phone number. Two-letter ISO code of the country, such as `FR`. Upper-cased before validation. The billing address. Required when `shipping_address` is missing. First name, up to 255 characters. Last name, up to 255 characters. Company name, up to 255 characters. Street and number. Apartment, floor or building. City. State or province. Tax rules of a province match on this value. Postal code. Phone number. Two-letter ISO code of the country, such as `FR`. Upper-cased before validation. Contact email of the checkout, lower-cased. Replaces the email of the cart. This request sets a shipping address in Paris, and asks for the addresses back with `include=addresses`: ```bash title="Request" curl -X POST "http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/addresses?include=addresses" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{ "shipping_address": { "first_name": "Camille", "last_name": "Martin", "address_1": "12 Rue de Rivoli", "city": "Paris", "postal_code": "75004", "phone": "+33612345678", "country_code": "FR" } }' ``` The API answers `200 OK` with the cart. With a French address, the 20% VAT now shows in `tax_total`, and `tax_inclusive` is `true` because the tax zone of France is set up with prices that include tax. The response is trimmed to the totals and the address: ```json title="Response 200" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "subtotal": 18000, "discount_total": 0, "tax_total": 3000, "shipping_total": 0, "total": 18000, "tax_inclusive": true }, "relationships": { "addresses": { "data": [ { "id": "01JD8ZA4B6D8F0H2K4M6P8R0T2", "type": "cart-addresses" } ] } } }, "included": [ { "id": "01JD8ZA4B6D8F0H2K4M6P8R0T2", "type": "cart-addresses", "attributes": { "type": "shipping", "first_name": "Camille", "last_name": "Martin", "full_name": "Camille Martin", "company": null, "address_1": "12 Rue de Rivoli", "address_2": null, "city": "Paris", "state": null, "postal_code": "75004", "country_code": "FR", "phone": "+33612345678" } } ] } ``` | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | Rule name, such as `required_with` | A field fails validation, the pointer names it, such as `/data/attributes/shipping_address/city` | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | The address does not change the zone of the cart. When the country is outside the zone, the shipping options endpoint returns no option and a warning, as the [Checkout](/3.x/store-api/checkout) guide shows: switch the cart to the zone of that country with `zone_code`, described in [Updating the cart](#updating-the-cart). The [Taxes](/3.x/taxes) page explains how the tax zone is picked from the country and the state. ## Promotion Codes [#promotion-codes] A promotion code entered by the customer is checked against the whole cart before it is kept: its currency, zone, dates, eligible products, minimum amount or quantity, usage limits and campaign budget. A code that cannot apply is refused and leaves the cart as it was. Automatic promotions need no request: they appear in `promotions` as soon as the cart qualifies. The [Discounts](/3.x/discounts) page describes how promotions are set up. The cart ID. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). The promotion code, up to 255 characters. This request applies the code `WELCOME10` to the cart: ```bash title="Request" curl -X POST http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/promotion \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"code": "WELCOME10"}' ``` The API answers `200 OK` with the cart. `WELCOME10` takes 10% off the subtotal, and the VAT is recalculated on the discounted amount. The response is trimmed to the totals: ```json title="Response 200" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "promotions": [ { "code": "WELCOME10", "source": "code", "amount": 1800, "status": "applied" } ], "subtotal": 18000, "discount_total": 1800, "tax_total": 2700, "shipping_total": 0, "total": 16200, "tax_inclusive": true } } } ``` Each entry of `promotions` has a `source` of `code` or `automatic`, the `amount` it takes off the cart in cents, and a `status`. A promotion is `applied` when its amount is above zero, and `suppressed` when it takes nothing off the cart right now, such as a code that an exclusive promotion of higher priority overrides. A suppressed code stays on the cart. A cart applies at most 5 promotions at once (`shopper.cart.max_promotions`). Each line shows its share of the discount in its own `adjustments`, with the code and the amount. A code the cart cannot use answers `422 promotion_not_applicable`, with the same message whatever the reason, so codes cannot be discovered by trying them: ```json title="Response 422" { "errors": [ { "status": "422", "code": "promotion_not_applicable", "title": "Unprocessable Content", "detail": "This promotion code does not apply to your cart.", "source": { "pointer": "/data/attributes/code" } } ] } ``` | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `promotion_not_applicable` | The code does not exist or does not apply to the cart | | 422 | Rule name, such as `required` | A field fails validation | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | The cart ID. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). The promotion code to remove. Without it, every code of the cart is removed. Removing a code takes the same `code` field. Without it, the request removes every code of the cart; automatic promotions stay: ```bash title="Request" curl -X DELETE http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/promotion \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"code": "WELCOME10"}' ``` The API answers `200 OK` with the cart. When the cart later changes currency or zone, the codes that no longer apply are dropped from it. | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | ## Updating the Cart [#updating-the-cart] The cart itself has four fields a storefront changes after creating it: the currency of a currency switcher, the zone of a country picker, the email of the checkout form and the metadata. Send only the fields that change. The cart ID. Related resources to return with the cart, listed in [Reading a Cart](#reading-a-cart). Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). ISO code of an enabled currency of the shop. The lines are priced again in that currency. Code of an enabled zone, the code the `X-Shopper-Zone` header carries. The lines are priced again for that zone. Contact email of the checkout, lower-cased. Replaces the cart metadata. `null` clears it. This request switches the cart to US dollars: ```bash title="Request" curl -X PATCH http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"currency_code": "USD"}' ``` The API answers `200 OK` with the cart priced in the new currency. Switching currency or zone resets part of the checkout: | Change | Lines | Shipping method | Payment method | Promotion codes | |--------|-------|-----------------|----------------|-----------------| | `currency_code` | Priced again in the new currency | Removed | Kept | Dropped when they no longer apply | | `zone_code` | Priced again for the new zone | Removed | Removed | Dropped when they no longer apply | The currency of the cart stays the same on a zone switch: send both fields to change both. When a line has no price in the new currency, the API refuses with `422 price_missing` on `/data/attributes/currency_code` and changes nothing. A line with a custom price cannot change currency and answers `409 cart_line_locked`. | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `price_missing` | A line has no price in the new currency | | 422 | Rule name, such as `exists` | A field fails validation, such as a disabled `zone_code` | | 409 | `cart_line_locked` | A line has a custom price | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | ## The Cart Resource [#the-cart-resource] The cart resource has the type `carts` and the public ID of the cart as its `id`. These attributes come with every cart response: ISO code of the cart currency. Contact email of the checkout. The promotions on the cart. The promotion code. `code` or `automatic`. What the promotion takes off the cart, in cents. `applied` or `suppressed`. When the cart became an order, ISO 8601. Your own data. Number of lines. Sum of the line quantities. Sum of the line subtotals, in cents. Total of the promotions, in cents. Tax of the cart, in cents, 0 until the cart has a shipping address. Price of the chosen shipping option, in cents. Amount to pay, in cents. Whether the prices already include `tax_total`. The chosen shipping option, `{carrier_code}:{service_code}`. ISO 8601. ISO 8601. The total follows the tax mode of the shipping address. When `tax_inclusive` is `true`, `total` is the subtotal minus the discounts, plus shipping, and `tax_total` is the share of VAT it already contains: show it as "VAT included". When it is `false`, `total` adds `tax_total` on top. The subtotal minus the discounts never goes below zero. The [Cart](/3.x/cart#calculation-pipeline) page describes the calculation pipeline behind these numbers. A `cart-lines` resource has these attributes: `variant` or `product`. Quantity of the line. Unit price frozen when the line was added, in cents. Whether the price was set by hand in the back office, which locks the line. `unit_price_amount` times `quantity`, in cents. Discount on the line, in cents. Tax on the line, in cents. The discounts of the line. Discount amount, in cents. The promotion code. The taxes of the line. Code of the tax rate. Name of the tax rate. A percentage, `20` for 20%. Tax amount, in cents. Data of the line. ISO 8601. ISO 8601. Its `purchasable` relationship points to a `variants` or a `products` resource, the same resources the catalog returns. A `cart-addresses` resource carries `type` (`shipping` or `billing`), `first_name`, `last_name`, `full_name`, `company`, `address_1`, `address_2`, `city`, `state`, `postal_code`, `country_code` and `phone`. ## Errors [#errors] Errors use the JSON:API error object, with a `code` a client can branch on, described with every code in [Error codes](/3.x/store-api/errors#error-codes). On top of validation errors, `401 unauthenticated` for a rejected token and `429 rate_limited`, the cart endpoints answer with these codes: | Code | Status | Endpoints | When | |------|--------|-----------|------| | `not_found` | 404 | All but `POST /carts` | No cart with this ID for this request, or no line with this ID in the cart | | `bad_request` | 400 | All that answer with the cart | An `include` path outside the cart allowlist | | `purchasable_unavailable` | 422 | Add a line | The product or variant cannot be bought | | `variant_required` | 422 | Add a line | The product is sold through its variants | | `price_missing` | 422 | Add a line, update the cart | No price in the cart currency, or in the new currency | | `stock_insufficient` | 422 | Add a line, update a line | Not enough stock for the quantity | | `quantity_rule_violated` | 422 | Add a line, update a line | The quantity breaks a minimum, maximum or increment, details in `meta` | | `cart_line_metadata_conflict` | 422 | Add a line | The line already exists with other metadata | | `promotion_not_applicable` | 422 | Apply a code | The code does not exist or does not apply to the cart | | `cart_line_locked` | 409 | Update a line, update the cart | The line has a custom price | | `cart_completed` | 409 | All changes | The cart is already an order | | `payment_session_collected` | 409 | All changes | The customer already paid: the cart can no longer change, complete it | | `payment_session_in_progress` | 409 | All changes | Another request is changing the cart, retry after the `Retry-After` header (3 seconds) | | `payment_provider_unavailable` | 503 | All changes | The open payment could not be cancelled at the provider, retry after the `Retry-After` header (5 seconds) | The last three come from the payment session a checkout opens. A change to the cart that alters its total cancels that session, and the storefront opens a new one, as the [Checkout](/3.x/store-api/checkout) guide explains. ## Next Steps [#next-steps] The cart now holds lines, an email and a shipping address. The checkout guide lists the shipping options and payment methods for this cart, opens the payment and turns the cart into an order. Shipping, payment session and order placement. Customer accounts and the transfer of a guest cart. # Catalog (/3.x/store-api/catalog) The catalog endpoints feed the pages a visitor browses before the cart: the product grid, the product page, the category menu, the brand and collection pages, the filter sidebar and the reviews. They are read-only and public, so a storefront calls them without a customer token, from the server or from the browser. Every amount is an integer in cents: a product priced at €90.00 carries `9000`. The [Money](/3.x/money#amounts-in-the-store-api) page covers cents and formatting. Responses are JSON:API documents, and this page lists what each endpoint accepts; the mechanics of `include`, `fields`, `filter`, `sort` and `page` are described once in [JSON:API Conventions](/3.x/store-api/json-api). ## Endpoints [#endpoints] All the catalog routes answer `GET` requests in the public route group. A bearer token is optional: when present, it only changes the prices a custom price resolver returns, as explained in [Prices, currency and stock](#prices-currency-and-stock). List products, with filters, sorting and price bounds Read one product, with its variants and options List the approved reviews of a product, with the rating summary Read the latest approved reviews of the shop List categories Read the whole category tree in one call Read one category List collections Read one collection List brands Read one brand List product tags List the attributes a filter sidebar can offer The `{slug}` of a show endpoint is the slug of the record, such as `classic-leather-sneakers`. Its `id` does not work there. The `/store/categories/tree` route is matched before `/store/categories/{slug}`, so a category whose slug is `tree` cannot be read on its own. ## What a Visitor Sees [#what-a-visitor-sees] The API never returns a record the merchant has not made public. Each endpoint applies the same rule as the admin panel, so a storefront does not filter anything itself: | Resource | Returned when | |----------|---------------| | Products | `published_at` is in the past and the product is visible. With a sales channel, the product must also be in that channel. | | Categories | The category and all its parents are enabled. Disabling a category hides its whole branch. | | Collections | `published_at` is set and in the past. | | Brands | The brand is enabled. | | Tags | Always. | | Attributes | The attribute is enabled, marked filterable, and of type `checkbox`, `colorpicker` or `select`. | | Reviews | The review is approved. | The sales channel comes from the `X-Shopper-Channel` header, or the default channel of the API, as described in [Request headers](/3.x/store-api#request-headers). It filters products only: the product listing, the product page, and the products embedded with `include=products` or counted with `products_count`. Categories, collections, brands, tags and reviews stay the same for every channel. The [Channels](/3.x/channels#what-the-channel-changes) page lists what the channel changes. A show endpoint answers `404 Not Found` for a record the visitor cannot see, exactly as for a slug that does not exist: ```json title="Response 404" { "errors": [ { "status": "404", "code": "not_found", "title": "Not Found", "detail": "Not Found" } ] } ``` ## Listing Products [#listing-products] The product listing powers the shop page, the category pages, the search results and the brand pages: the same endpoint with different filters. Search term, matched case-insensitively anywhere in the name, the description or the SKU of the product. Only the first comma-separated term is searched, and `%` and `_` act as wildcards. Keeps the products whose name contains the value, case-insensitively. Exact SKU of the product. The SKUs of variants are not searched. `true` keeps the featured products, `false` the others. `true` keeps what a visitor can buy now: external products, products with stock left or that allow backorders, and variant products with at least one such variant. `false` keeps the rest. Slug or ID of a category. Keeps the products assigned to that category itself, without its subcategories. A hidden category matches nothing. Slug or ID of a category. Keeps the products of that category and of every enabled category below it. Use it for a parent category page such as "Men". Slug or ID of a published collection. Slug or ID of an enabled brand. Slug or ID of a tag. Key or label of an attribute value, such as `42` or `Black`. Keeps the products with a variant that carries the value, or with the value set on the product, whatever the attribute. See [Attributes](#attributes). ISO code of an enabled currency, such as `USD`, in any case. Sets the currency of every price, price sort and price bound of the response. Defaults to the currency of the zone, then to the default currency of the shop. Lowest price to keep, in cents, in the currency of the request. Products without a price in that currency are left out. Highest price to keep, in cents, in the currency of the request. Products without a price in that currency are left out. `name`, `created_at`, `published_at` or `price`, prefixed with `-` for descending order, such as `-published_at` for the newest first. Without `sort`, products come in creation order. See [Sorting](/3.x/store-api/json-api#sorting). Comma-separated list from the [includes table](#filters-sorting-and-includes). See [Includes](/3.x/store-api/json-api#includes). Comma-separated attributes to return, such as `name,slug,price_range,thumbnail`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). Products per page, from 1 to 100. Page to return, from 1 to 100. Past page 100, switch to `page[cursor]`. See [Pagination](/3.x/store-api/json-api#pagination). Cursor from the `links` of a previous page. Switches the listing to cursor pagination. The simplest call returns the first 15 published products, in the order they were created: ```bash title="Request" curl http://localhost:8000/store/products \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: EU" ``` A category page filters by the category slug and picks a page size. The `-g` option stops curl from reading the brackets of the query string: ```bash title="Request" curl -g "http://localhost:8000/store/products?filter[category]=men-shoes&page[size]=2" \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: EU" ``` The API answers `200 OK` with a page of products, the pagination links and the page details. `meta.currency` is the currency every price of the response is expressed in: ```json title="Response 200" { "data": [ { "id": "01JD8YQ1A2B3C4D5E6F7G8H9JK", "type": "products", "attributes": { "name": "Classic Leather Sneakers", "slug": "classic-leather-sneakers", "sku": null, "barcode": null, "summary": "Full-grain leather sneakers with a cushioned insole.", "description": "

    Full-grain leather upper, rubber cupsole and a removable cushioned insole.

    ", "featured": true, "type": "variant", "published_at": "2026-10-01T08:00:00+00:00", "seo_title": null, "seo_description": null, "metadata": null, "in_stock": true, "price_range": { "currency_code": "EUR", "min": 9000, "max": 9500 }, "prices": [], "images": [ { "id": "9d2f1c4e-3b7a-4f8e-a1d2-6c5b4e3f2a10", "url": "http://localhost:8000/storage/12/classic-leather-sneakers.jpg", "conversions": { "large": "http://localhost:8000/storage/12/conversions/classic-leather-sneakers-large.jpg", "medium": "http://localhost:8000/storage/12/conversions/classic-leather-sneakers-medium.jpg" }, "name": "classic-leather-sneakers", "extension": "jpg", "created_at": "2026-09-28T14:22:10+00:00", "updated_at": "2026-09-28T14:22:12+00:00" } ], "thumbnail": { "id": "9d2f1c4e-3b7a-4f8e-a1d2-6c5b4e3f2a10", "url": "http://localhost:8000/storage/12/classic-leather-sneakers.jpg", "conversions": { "large": "http://localhost:8000/storage/12/conversions/classic-leather-sneakers-large.jpg", "medium": "http://localhost:8000/storage/12/conversions/classic-leather-sneakers-medium.jpg" }, "name": "classic-leather-sneakers", "extension": "jpg", "created_at": "2026-09-28T14:22:10+00:00", "updated_at": "2026-09-28T14:22:12+00:00" }, "created_at": "2026-09-28T14:20:00+00:00", "updated_at": "2026-11-12T09:05:00+00:00" } }, { "id": "01JD8YQ2B3C4D5E6F7G8H9JKM0", "type": "products", "attributes": { "name": "Leather Care Kit", "slug": "leather-care-kit", "sku": "LCK-001", "barcode": null, "summary": "Cleaner, conditioner and brush for leather shoes.", "description": "

    Everything to clean, feed and protect smooth leather.

    ", "featured": false, "type": "standard", "published_at": "2026-10-01T08:00:00+00:00", "seo_title": null, "seo_description": null, "metadata": null, "stock": 42, "in_stock": true, "price_range": { "currency_code": "EUR", "min": 1990, "max": 1990 }, "prices": [ { "public_id": "01JD8YQ7P9R1T3V5X7Z9B1D3F5", "amount": 1990, "compare_amount": 2490, "currency_code": "EUR" }, { "public_id": "01JD8YQ7P9R1T3V5X7Z9B1D3F6", "amount": 2190, "compare_amount": null, "currency_code": "USD" } ], "calculated_price": { "amount": 1990, "compare_amount": 2490, "original_amount": null, "currency_code": "EUR", "meta": null }, "quantity_rule": null, "images": [], "thumbnail": null, "created_at": "2026-09-30T10:12:00+00:00", "updated_at": "2026-11-02T16:40:00+00:00" } } ], "links": { "first": "http://localhost:8000/store/products?filter%5Bcategory%5D=men-shoes&page%5Bsize%5D=2&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/products?filter%5Bcategory%5D=men-shoes&page%5Bsize%5D=2&page%5Bnumber%5D=2", "prev": null, "next": "http://localhost:8000/store/products?filter%5Bcategory%5D=men-shoes&page%5Bsize%5D=2&page%5Bnumber%5D=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 2, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/products?filter%5Bcategory%5D=men-shoes&page%5Bsize%5D=2&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": "http://localhost:8000/store/products?filter%5Bcategory%5D=men-shoes&page%5Bsize%5D=2&page%5Bnumber%5D=2", "label": "2", "page": 2, "active": false }, { "url": "http://localhost:8000/store/products?filter%5Bcategory%5D=men-shoes&page%5Bsize%5D=2&page%5Bnumber%5D=2", "label": "Next »", "page": 2, "active": false } ], "path": "http://localhost:8000/store/products", "per_page": 2, "to": 2, "total": 3, "currency": "EUR" } } ``` | Status | Code | When | |--------|------|------| | 422 | `filter_too_wide` | A filter has more than 50 values | | 422 | `currency_unknown` | `filter[currency]` matches no enabled currency | | 422 | `currency_required` | A price sort or bound on a shop with no enabled currency | | 400 | `bad_request` | An unknown filter, sort or include |
    The two products show the two shapes a grid meets. Classic Leather Sneakers is a variant product: its prices live on its variants, so `prices` is empty, and the card shows "From €90.00" with `price_range.min`. Leather Care Kit is a standard product with a single price, so the card shows `calculated_price.amount` and strikes through `compare_amount`. ### The Product Resource [#the-product-resource] Some attributes depend on the product type or on an include. An attribute that does not apply is left out of the response, not sent as `null`: Name of the product. The slug the product page reads with `/store/products/{slug}`. SKU of the product. A variant product keeps its codes on each variant. Barcode of the product. A variant product keeps its codes on each variant. Short description, as entered in the admin panel. Long description, as entered in the admin panel. `true` for a product the merchant highlights. `standard`, `variant`, `virtual` or `external`. See [Products](/3.x/products). Publication date, in ISO 8601. Value for the page ``. </Field> <Field name="seo_description" type="string, null"> Value for the meta description. </Field> <Field name="metadata" type="object, null"> Your own data, or `null`. </Field> <Field name="external_id" type="string, null"> External products only: the ID on the platform that sells the product. </Field> <Field name="stock" type="integer"> Availability. See [Stock](#stock). </Field> <Field name="in_stock" type="boolean"> Availability. See [Stock](#stock). </Field> <Field name="price_range" type="object, null"> Lowest and highest price in the currency of the request. See [Prices, currency and stock](#prices-currency-and-stock). </Field> <Field name="prices" type="array"> Every price of the product in an enabled currency. Empty for a variant product. </Field> <Field name="calculated_price" type="object, null"> The price to charge in the currency of the request. Not on variant products. </Field> <Field name="quantity_rule" type="object, null"> The quantity limits. Not on variant products. </Field> <Field name="images" type="array"> Every image of the gallery, as media objects. </Field> <Field name="thumbnail" type="object, null"> The thumbnail image, or the first gallery image when the product has no thumbnail, or `null`. </Field> <Field name="files" type="array"> Virtual products only: the downloadable files, each with `id`, `name`, `extension` and `size` in bytes. The files themselves are downloaded from the order, see [Orders](/3.x/store-api/orders). </Field> <Field name="rating" type="number, null"> With `include=rating` only: the average rating of the approved reviews, rounded to one decimal or `null` without reviews. </Field> <Field name="reviews_count" type="integer"> With `include=rating` only: the number of approved reviews. </Field> <Field name="options" type="array"> With `include=options` only. See [Options](#options). </Field> <Field name="created_at" type="string"> Creation date, in ISO 8601. </Field> <Field name="updated_at" type="string"> Date of the last change, in ISO 8601. </Field> </Attributes> A media object carries the `id` of the file, its `url`, the `conversions` already generated (by default `large` at 800 x 800 and `medium` at 500 x 500, keyed by name), the file `name` and `extension`, and its dates. A conversion that is not generated yet is missing from `conversions`, so fall back to `url`. The product relationships are `brand`, `categories`, `collections`, `tags`, `relatedProducts`, and `variants` on variant products. A relationship appears in `relationships` only when it is requested with `include`. ### Filters, Sorting and Includes [#filters-sorting-and-includes] The listing accepts the filters, sorts and includes that `ProductResource` declares, and [Extending the Allowlists](/3.x/store-api/json-api#extending-the-allowlists) shows how to add your own. A comma inside one filter means OR, such as `filter[brand]=maison-cuir,nordic-steps`, and different filters combine with AND. A filter accepts up to 50 values; more returns `422` with the code `filter_too_wide`. An unknown filter, sort or include returns `400` with the code `bad_request`. The [Errors](/3.x/store-api/errors#error-codes) page lists every code. The includes add related records, or extra attributes computed on demand: | Include | Adds | |---------|------| | `brand` | The brand, when it is enabled. | | `categories` | The categories of the product that sit in a visible branch, with their parent loaded. | | `collections` | The published collections of the product. | | `tags` | The tags of the product. | | `variants` | The variants of a variant product, with their prices, stock and option values. | | `options` | The `options` attribute: the attributes and values the product uses. | | `relatedProducts` | The related products that are published and in the sales channel, with their stock and `price_range`. | | `rating` | The `rating` and `reviews_count` attributes, from the approved reviews. | | `price_range` | Listing only: `meta.price_range`, the lowest and highest price of the products that match the filters. See [Price filters and sorting](#price-filters-and-sorting). | Several filters together build a search results page with facets. This request searches "leather" in the products of the "Men" branch that are in stock, from the brand Maison Cuir, newest first: ```bash title="Request" curl -g "http://localhost:8000/store/products?filter[q]=leather&filter[category_tree]=men&filter[in_stock]=true&filter[brand]=maison-cuir&sort=-published_at&include=brand,rating" \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: EU" ``` ## Prices, Currency and Stock [#prices-currency-and-stock] A storefront shows prices in one currency per page, and the API resolves that currency once per request so every amount of the response agrees. Prices are never converted: an amount always comes from a price the merchant set in that currency, and a product without a price in the currency shows no amount at all. The currency of a request is, in this order: 1. The `filter[currency]` query parameter, on the listing and on the product page. 2. The currency of the zone sent in `X-Shopper-Zone`, or of the default zone. See [Picking a zone and a currency](/3.x/store-api/store). 3. The default currency of the shop. A code in `filter[currency]` that matches no enabled currency is an error, never a silent fallback. The API answers `422 Unprocessable Content`: ```json title="Response 422" { "errors": [ { "status": "422", "code": "currency_unknown", "title": "Unprocessable Content", "detail": "The \"EURO\" currency is unknown or not enabled on this shop.", "source": { "pointer": "/data/attributes/filter/currency" } } ] } ``` The check runs against every enabled currency, not only the currencies the shop sells in, and Shopper enables all 158 currencies at install. A code such as `GBP` on a shop that sells in EUR and USD passes with `200 OK`, and every `calculated_price` and `price_range` of the response is `null`. Send a code from the `currencies` of the [store settings](/3.x/store-api/store#reading-the-store-settings), the list a cart accepts. A product carries up to four price attributes. Read the one that matches what the page shows: | Attribute | Shape | Use it for | |-----------|-------|------------| | `calculated_price` | `amount`, `compare_amount`, `original_amount`, `currency_code`, `meta` | The price to display and charge for a standard, virtual or external product, and for each variant on the product page. `null` when there is no price in the currency. | | `quantity_rule` | `minimum`, `maximum`, `increment` | The quantity limits of the quantity picker. `null` when no rule applies. | | `price_range` | `currency_code`, `min`, `max` | "From" prices on cards, mostly for variant products: the lowest and highest price of the product or of its variants. `null` when there is no price in the currency. | | `prices` | A list of `public_id`, `amount`, `compare_amount`, `currency_code` | Every price of the product in every enabled currency, as the merchant set them. Empty for a variant product. | `compare_amount` is the "compare at" price to strike through, or `null`. With the default price resolver, `calculated_price.amount` is the price set for the currency, `original_amount` and `meta` are `null`, and `quantity_rule` is `null`. A custom resolver can return a customer price instead: the API passes it the currency, the zone, the channel and the customer of the bearer token, if any. Product responses carry `Vary: Authorization` for that reason, so a shared cache must not serve one customer's prices to another. The [Pricing](/3.x/pricing#custom-price-resolver) page covers resolvers and [quantity rules](/3.x/pricing#quantity-rules). To show the prices of a product in US dollars whatever the zone, pass the currency: ```bash title="Request" curl -g "http://localhost:8000/store/products/leather-care-kit?filter[currency]=USD&fields[products]=name,price_range,prices,calculated_price" \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: EU" ``` The API answers `200 OK`. `price_range`, `calculated_price` and `meta.currency` follow the requested currency, while `prices` still lists every currency: ```json title="Response 200" { "data": { "id": "01JD8YQ2B3C4D5E6F7G8H9JKM0", "type": "products", "attributes": { "name": "Leather Care Kit", "price_range": { "currency_code": "USD", "min": 2190, "max": 2190 }, "prices": [ { "public_id": "01JD8YQ7P9R1T3V5X7Z9B1D3F5", "amount": 1990, "compare_amount": 2490, "currency_code": "EUR" }, { "public_id": "01JD8YQ7P9R1T3V5X7Z9B1D3F6", "amount": 2190, "compare_amount": null, "currency_code": "USD" } ], "calculated_price": { "amount": 2190, "compare_amount": null, "original_amount": null, "currency_code": "USD", "meta": null } } }, "meta": { "currency": "USD" } } ``` The currency of the page does not set the currency of the cart. The cart takes its own `currency_code`, as described in [Cart](/3.x/store-api/cart). ### Price Filters and Sorting [#price-filters-and-sorting] A price slider needs two things: the products within the chosen bounds, and the bounds of the slider itself. `filter[price_min]`, `filter[price_max]` and `sort=price` work on the lowest price of each product in the currency of the request: the price of a standard product, or the cheapest variant of a variant product. Products without a price in that currency are left out of the results. Bounds are integers in cents. `include=price_range` adds `meta.price_range`, the lowest and highest of these prices over every product that matches the other filters. It ignores `price_min` and `price_max`, so the slider keeps its full range while the visitor moves it. This request keeps the products of the "Men" branch between €50.00 and €100.00, cheapest first, and asks for the slider range: ```bash title="Request" curl -g "http://localhost:8000/store/products?filter[category_tree]=men&filter[price_min]=5000&filter[price_max]=10000&sort=price&include=price_range&fields[products]=name,price_range" \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: EU" ``` The API answers `200 OK`. One product falls within the bounds, and `meta.price_range` covers the whole branch, from the €19.90 care kit to a €189.00 jacket: ```json title="Response 200" { "data": [ { "id": "01JD8YQ1A2B3C4D5E6F7G8H9JK", "type": "products", "attributes": { "name": "Classic Leather Sneakers", "price_range": { "currency_code": "EUR", "min": 9000, "max": 9500 } } } ], "links": { "first": "http://localhost:8000/store/products?filter%5Bcategory_tree%5D=men&filter%5Bprice_min%5D=5000&filter%5Bprice_max%5D=10000&sort=price&include=price_range&fields%5Bproducts%5D=name%2Cprice_range&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/products?filter%5Bcategory_tree%5D=men&filter%5Bprice_min%5D=5000&filter%5Bprice_max%5D=10000&sort=price&include=price_range&fields%5Bproducts%5D=name%2Cprice_range&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/products?filter%5Bcategory_tree%5D=men&filter%5Bprice_min%5D=5000&filter%5Bprice_max%5D=10000&sort=price&include=price_range&fields%5Bproducts%5D=name%2Cprice_range&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/products", "per_page": 15, "to": 1, "total": 1, "currency": "EUR", "price_range": { "min": 1990, "max": 18900, "currency_code": "EUR" } } } ``` `meta.price_range` is `null` when no matching product has a price in the currency. The prices come from the price index, which reads the prices set on products and variants; the [Pricing](/3.x/pricing#price-index) page explains how to replace it. When the shop has no enabled currency at all, a price sort or bound answers `422` with the code `currency_required`. ### Stock [#stock] A product card needs to know whether to show "Add to cart" or "Sold out", and the API computes that per product type, so the storefront reads one boolean: | Product type | Attributes | |--------------|------------| | `standard`, `virtual` | `stock`, the quantity on hand, and `in_stock`: `true` when `stock` is above 0 or the product allows backorders. | | `variant` | `in_stock` only: `true` when at least one variant has stock or allows backorders. Each variant carries its own `stock` and `in_stock` with `include=variants`. | | `external` | `in_stock`, always `true`. The product is sold elsewhere. | The listing, the product page, related products, and the products embedded in brands and categories carry these attributes. The products embedded with `include=products` in collections and tags do not, so read the stock from the product listing with `filter[collection]` or `filter[tag]` instead. The [Product variants](/3.x/product-variants#stock-management) page covers how stock is counted. ## Showing a Product [#showing-a-product] The product page reads one product by slug and asks for what it shows: the variants to pick from, and often the options, the brand and the rating. <Endpoint id="get-store-products-slug" method="GET" path="/store/products/{slug}" auth="optional"> <Params title="Path parameters"> <Field name="slug" type="string" required> Slug of the product, such as `classic-leather-sneakers`. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> Comma-separated list from the [includes table](#filters-sorting-and-includes) of the listing. See [Includes](/3.x/store-api/json-api#includes). </Field> <Field name="filter[currency]" type="string"> ISO code of an enabled currency, such as `USD`, in any case. Sets the currency of every price of the response. Defaults to the currency of the zone, then to the default currency of the shop. </Field> <Field name="fields[products]" type="string"> Comma-separated attributes to return, such as `name,slug,price_range`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request asks for the variants, and limits the product attributes to keep the example short: ```bash title="Request" curl -g "http://localhost:8000/store/products/classic-leather-sneakers?include=variants&fields[products]=name,slug,type,in_stock,price_range" \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: EU" ``` The API answers `200 OK` with the product, its variants in `included`, and the currency in `meta`: ```json title="Response 200" { "data": { "id": "01JD8YQ1A2B3C4D5E6F7G8H9JK", "type": "products", "attributes": { "name": "Classic Leather Sneakers", "slug": "classic-leather-sneakers", "type": "variant", "in_stock": true, "price_range": { "currency_code": "EUR", "min": 9000, "max": 9500 } }, "relationships": { "variants": { "data": [ { "id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "type": "variants" }, { "id": "01JD8YQ4J6M8P0R2T4V6X8Z0B2", "type": "variants" } ] } } }, "included": [ { "id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "type": "variants", "attributes": { "name": "42 / Black", "sku": "CLS-42-BLK", "barcode": null, "ean": null, "upc": null, "position": 1, "allow_backorder": false, "stock": 12, "in_stock": true, "metadata": null, "prices": [ { "public_id": "01JD8YQ5M7P9R1T3V5X7Z9B1D3", "amount": 9000, "compare_amount": null, "currency_code": "EUR" }, { "public_id": "01JD8YQ5M7P9R1T3V5X7Z9B1D4", "amount": 9900, "compare_amount": null, "currency_code": "USD" } ], "calculated_price": { "amount": 9000, "compare_amount": null, "original_amount": null, "currency_code": "EUR", "meta": null }, "quantity_rule": null, "values": [ { "value": "42", "key": "42", "attribute": "Size", "attribute_slug": "size" }, { "value": "Black", "key": "#000000", "attribute": "Color", "attribute_slug": "color" } ], "images": [], "thumbnail": null, "created_at": "2026-09-28T14:25:00+00:00", "updated_at": "2026-11-12T09:05:00+00:00" } }, { "id": "01JD8YQ4J6M8P0R2T4V6X8Z0B2", "type": "variants", "attributes": { "name": "43 / Brown", "sku": "CLS-43-BRN", "barcode": null, "ean": null, "upc": null, "position": 2, "allow_backorder": false, "stock": 0, "in_stock": false, "metadata": null, "prices": [ { "public_id": "01JD8YQ6N8Q0S2T4W6Y8A0C2E4", "amount": 9500, "compare_amount": null, "currency_code": "EUR" }, { "public_id": "01JD8YQ6N8Q0S2T4W6Y8A0C2E5", "amount": 10500, "compare_amount": null, "currency_code": "USD" } ], "calculated_price": { "amount": 9500, "compare_amount": null, "original_amount": null, "currency_code": "EUR", "meta": null }, "quantity_rule": null, "values": [ { "value": "43", "key": "43", "attribute": "Size", "attribute_slug": "size" }, { "value": "Brown", "key": "#8b4513", "attribute": "Color", "attribute_slug": "color" } ], "images": [], "thumbnail": null, "created_at": "2026-09-28T14:25:00+00:00", "updated_at": "2026-11-12T09:05:00+00:00" } } ], "meta": { "currency": "EUR" } } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No published product with this slug in the sales channel of the request | | 422 | `currency_unknown` | `filter[currency]` matches no enabled currency | | 400 | `bad_request` | An unknown include | </Errors> </Endpoint> The variant picker matches the visitor's choices against `values`, where `key` is the stored value (a hex code for a color) and `value` the label to show. When the visitor picks "43 / Brown", the page shows €95.00 from `calculated_price` and disables "Add to cart" because `in_stock` is `false`. The cart takes the variant `id`, as described in [Cart](/3.x/store-api/cart). A variant shows its own `images` and `thumbnail`; when it has none, show the images of the product. The product listing accepts `include=variants` too, but there the variants carry no `calculated_price` and no `quantity_rule`. Read the price of a variant on a listing from its `prices` entry in the currency of `meta.currency`, or read the variants from the product page. The product page accepts the includes of the listing, `filter[currency]` and `fields`. Other filters, sorts and pagination parameters do not apply. Add `relatedProducts` for a "You may also like" row and `rating` for the stars next to the title. A product outside the sales channel of the request answers `404`, like an unpublished one. ### Options [#options] The options are the attributes the merchant set on the product, such as its sizes, its colors or its material, with only the values the product uses. A product page shows them as specifications, or builds the variant picker from them before matching a variant. Ask for them with `include=options`: ```bash title="Request" curl -g "http://localhost:8000/store/products/classic-leather-sneakers?include=options&fields[products]=name,options" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with an `options` attribute. Attributes come in the order the merchant added them to the product, and values by position: ```json title="Response 200" { "data": { "id": "01JD8YQ1A2B3C4D5E6F7G8H9JK", "type": "products", "attributes": { "name": "Classic Leather Sneakers", "options": [ { "name": "Size", "slug": "size", "description": null, "type": "select", "icon": null, "custom_value": null, "values": [ { "key": "42", "value": "42", "position": 1, "swatch_url": null }, { "key": "43", "value": "43", "position": 2, "swatch_url": null } ] }, { "name": "Color", "slug": "color", "description": null, "type": "colorpicker", "icon": null, "custom_value": null, "values": [ { "key": "#000000", "value": "Black", "position": 1, "swatch_url": null }, { "key": "#8b4513", "value": "Brown", "position": 2, "swatch_url": null } ] }, { "name": "Material", "slug": "material", "description": null, "type": "text", "icon": null, "custom_value": "Full-grain leather", "values": [] } ] } }, "meta": { "currency": "EUR" } } ``` `custom_value` holds the free text of a `text`, `number`, `richtext` or `datepicker` attribute, which has no predefined values. `swatch_url` is the URL of a swatch image the merchant uploaded for that value on this product, or `null`. Disabled attributes are left out. External products have no options. The [Attributes](/3.x/attributes#product-attributes-and-variant-options) page explains how options and variant values relate. ## Categories [#categories] Categories give the storefront its menu, its category pages and its breadcrumbs. The API offers three reads: the tree for the menu, the listing for flat lists such as a sitemap, and the category itself for a category page. ### The Category Tree [#the-category-tree] A navigation menu needs every visible category, nested, in one request. `/store/categories/tree` returns the enabled branches with their children, ordered by position. It is not paginated and is not a JSON:API document: each node carries `id`, `name`, `slug`, `position` and `children` directly. <Endpoint id="get-store-categories-tree" method="GET" path="/store/categories/tree" auth="public"> This request reads the whole tree: ```bash title="Request" curl http://localhost:8000/store/categories/tree \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the root categories in `data`: ```json title="Response 200" { "data": [ { "id": "01JD8XR1M2N3P4Q5R6S7T8V9W0", "name": "Men", "slug": "men", "position": 1, "children": [ { "id": "01JD8XR2N3P4Q5R6S7T8V9W0X1", "name": "Shoes", "slug": "men-shoes", "position": 1, "children": [] }, { "id": "01JD8XR3P4Q5R6S7T8V9W0X1Y2", "name": "Jackets", "slug": "men-jackets", "position": 2, "children": [] } ] }, { "id": "01JD8XR4Q5R6S7T8V9W0X1Y2Z3", "name": "Women", "slug": "women", "position": 2, "children": [] } ] } ``` </Endpoint> The tree is the same for every sales channel, and it does not count products. A category with no products in the current channel still appears. ### Reading a Category [#reading-a-category] A category page shows the category name, its description, a breadcrumb and the products. <Endpoint id="get-store-categories-slug" method="GET" path="/store/categories/{slug}" auth="public"> <Params title="Path parameters"> <Field name="slug" type="string" required> Slug of the category, such as `men-shoes`. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> Comma-separated list of `parent`, `children`, `ancestors`, `products` and `products_count`. `parent` and `children` return enabled categories only. `products` embeds the published products assigned to the category itself, without pagination. </Field> <Field name="fields[categories]" type="string"> Comma-separated attributes to return, such as `name,slug`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> Read the category with `include=ancestors` for the breadcrumb, and `include=products_count` for the number of products: ```bash title="Request" curl "http://localhost:8000/store/categories/men-shoes?include=ancestors,products_count" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the category and its ancestors in `included`, root first: ```json title="Response 200" { "data": { "id": "01JD8XR2N3P4Q5R6S7T8V9W0X1", "type": "categories", "attributes": { "name": "Shoes", "slug": "men-shoes", "description": "<p>Sneakers, boots and loafers for men.</p>", "position": 1, "parent_id": "01JD8XR1M2N3P4Q5R6S7T8V9W0", "is_enabled": true, "depth": 1, "products_count": 3, "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-20T09:00:00+00:00", "updated_at": "2026-10-04T11:30:00+00:00" }, "relationships": { "ancestors": { "data": [ { "id": "01JD8XR1M2N3P4Q5R6S7T8V9W0", "type": "categories" } ] } } }, "included": [ { "id": "01JD8XR1M2N3P4Q5R6S7T8V9W0", "type": "categories", "attributes": { "name": "Men", "slug": "men", "description": null, "position": 1, "parent_id": null, "is_enabled": true, "depth": 0, "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-20T08:55:00+00:00", "updated_at": "2026-09-20T08:55:00+00:00" } } ] } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No category with this slug, or the category or one of its parents is disabled | | 400 | `bad_request` | An unknown include | </Errors> </Endpoint> `parent_id` is the `id` of the parent category, and `depth` is 0 for a root category. `products_count` counts the published products of the category and of all its enabled subcategories, in the sales channel of the request. Then list the products with `filter[category_tree]` or `filter[category]` on the [product listing](#listing-products), which paginates, sorts and carries prices. The listing returns every visible category of every level in one flat list. `position` ranks a category among its siblings, so `sort=position` mixes the levels: read [the tree](#the-category-tree) for the order of the admin panel. The [Categories](/3.x/categories#visibility-and-depth) page explains how visibility and depth are computed. <Endpoint id="get-store-categories" method="GET" path="/store/categories" auth="public"> <Params title="Query parameters"> <Field name="filter[name]" type="string"> Keeps the categories whose name contains the value, case-insensitively. </Field> <Field name="sort" type="string"> `name` or `position`, prefixed with `-` for descending order. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="include" type="string"> Comma-separated list of `parent`, `children`, `ancestors`, `products` and `products_count`. `parent` and `children` return enabled categories only. `products` embeds the published products assigned to the category itself, without pagination. </Field> <Field name="fields[categories]" type="string"> Comma-separated attributes to return, such as `name,slug`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="page[size]" type="integer" default="15"> Categories per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> Page to return, from 1 to 100. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="page[cursor]" type="string"> Cursor from the `links` of a previous page. Switches the listing to cursor pagination. </Field> </Params> This request reads the first page of the list, two categories per page: ```bash title="Request" curl -g "http://localhost:8000/store/categories?page[size]=2" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with a page of categories, the pagination links and the page details. A category carries the attributes shown in [Reading a Category](#reading-a-category): ```json title="Response 200" { "data": [ { "id": "01JD8XR1M2N3P4Q5R6S7T8V9W0", "type": "categories", "attributes": { "name": "Men", "slug": "men", "description": null, "position": 1, "parent_id": null, "is_enabled": true, "depth": 0, "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-20T08:55:00+00:00", "updated_at": "2026-09-20T08:55:00+00:00" } }, { "id": "01JD8XR2N3P4Q5R6S7T8V9W0X1", "type": "categories", "attributes": { "name": "Shoes", "slug": "men-shoes", "description": "<p>Sneakers, boots and loafers for men.</p>", "position": 1, "parent_id": "01JD8XR1M2N3P4Q5R6S7T8V9W0", "is_enabled": true, "depth": 1, "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-20T09:00:00+00:00", "updated_at": "2026-10-04T11:30:00+00:00" } } ], "links": { "first": "http://localhost:8000/store/categories?page%5Bsize%5D=2&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/categories?page%5Bsize%5D=2&page%5Bnumber%5D=2", "prev": null, "next": "http://localhost:8000/store/categories?page%5Bsize%5D=2&page%5Bnumber%5D=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 2, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/categories?page%5Bsize%5D=2&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": "http://localhost:8000/store/categories?page%5Bsize%5D=2&page%5Bnumber%5D=2", "label": "2", "page": 2, "active": false }, { "url": "http://localhost:8000/store/categories?page%5Bsize%5D=2&page%5Bnumber%5D=2", "label": "Next »", "page": 2, "active": false } ], "path": "http://localhost:8000/store/categories", "per_page": 2, "to": 2, "total": 4 } } ``` <Errors> | Status | Code | When | |--------|------|------| | 422 | `filter_too_wide` | A filter has more than 50 values | | 400 | `bad_request` | An unknown filter, sort or include | </Errors> </Endpoint> ## Collections [#collections] Collections group products for a campaign or a theme, such as "Gift Ideas" or "Winter Essentials". The API returns the published ones only: a collection whose `published_at` is empty or in the future stays hidden. <Endpoint id="get-store-collections-slug" method="GET" path="/store/collections/{slug}" auth="public"> <Params title="Path parameters"> <Field name="slug" type="string" required> Slug of the collection, such as `gift-ideas`. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `products` embeds the published products of the collection in the sales channel, without pagination. </Field> <Field name="fields[collections]" type="string"> Comma-separated attributes to return, such as `name,slug`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request reads the `gift-ideas` collection with its products, limited to their name, slug and prices: ```bash title="Request" curl "http://localhost:8000/store/collections/gift-ideas?include=products&fields[products]=name,slug,prices" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the collection and its products in `included`: ```json title="Response 200" { "data": { "id": "01JD8XT4Q6S8V0X2Z4B6D8F0H2", "type": "collections", "attributes": { "name": "Gift Ideas", "slug": "gift-ideas", "description": "<p>Small leather goods and care kits under €50.</p>", "type": "manual", "published_at": "2026-11-01T00:00:00+00:00", "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-10-25T15:00:00+00:00", "updated_at": "2026-11-01T00:00:00+00:00" }, "relationships": { "products": { "data": [ { "id": "01JD8YQ2B3C4D5E6F7G8H9JKM0", "type": "products" } ] } } }, "included": [ { "id": "01JD8YQ2B3C4D5E6F7G8H9JKM0", "type": "products", "attributes": { "name": "Leather Care Kit", "slug": "leather-care-kit", "prices": [ { "public_id": "01JD8YQ7P9R1T3V5X7Z9B1D3F5", "amount": 1990, "compare_amount": 2490, "currency_code": "EUR" }, { "public_id": "01JD8YQ7P9R1T3V5X7Z9B1D3F6", "amount": 2190, "compare_amount": null, "currency_code": "USD" } ] } } ] } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No published collection with this slug | | 400 | `bad_request` | An unknown include | </Errors> </Endpoint> `type` is `manual` when the merchant picks the products, or `auto` when rules select them. See [Collection types](/3.x/collections#collection-types). The products embedded with `include=products` are published and in the sales channel, but they come without pagination, stock, `price_range` or `calculated_price`. For the product grid of a collection page, call the product listing with `filter[collection]=gift-ideas`. The collection listing accepts `filter[name]` (partial match), `sort=name`, `include=products` and the pagination parameters. <Endpoint id="get-store-collections" method="GET" path="/store/collections" auth="public"> <Params title="Query parameters"> <Field name="filter[name]" type="string"> Keeps the collections whose name contains the value, case-insensitively. </Field> <Field name="sort" type="string"> `name`, or `-name` for descending order. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="include" type="string"> `products` embeds the published products of each collection in the sales channel, without pagination. </Field> <Field name="fields[collections]" type="string"> Comma-separated attributes to return, such as `name,slug`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="page[size]" type="integer" default="15"> Collections per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> Page to return, from 1 to 100. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="page[cursor]" type="string"> Cursor from the `links` of a previous page. Switches the listing to cursor pagination. </Field> </Params> This request lists the published collections by name: ```bash title="Request" curl "http://localhost:8000/store/collections?sort=name" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the collections, the pagination links and the page details. All of them fit on one page here: ```json title="Response 200" { "data": [ { "id": "01JD8XT4Q6S8V0X2Z4B6D8F0H2", "type": "collections", "attributes": { "name": "Gift Ideas", "slug": "gift-ideas", "description": "<p>Small leather goods and care kits under €50.</p>", "type": "manual", "published_at": "2026-11-01T00:00:00+00:00", "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-10-25T15:00:00+00:00", "updated_at": "2026-11-01T00:00:00+00:00" } }, { "id": "01JD8XT5R7T9W1Y3A5C7E9G1J3", "type": "collections", "attributes": { "name": "Winter Essentials", "slug": "winter-essentials", "description": "<p>Boots and warm leather goods for the cold months.</p>", "type": "auto", "published_at": "2026-11-15T00:00:00+00:00", "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-11-10T09:30:00+00:00", "updated_at": "2026-11-15T00:00:00+00:00" } } ], "links": { "first": "http://localhost:8000/store/collections?sort=name&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/collections?sort=name&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/collections?sort=name&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/collections", "per_page": 15, "to": 2, "total": 2 } } ``` <Errors> | Status | Code | When | |--------|------|------| | 422 | `filter_too_wide` | A filter has more than 50 values | | 400 | `bad_request` | An unknown filter, sort or include | </Errors> </Endpoint> ## Brands [#brands] A brand page shows the brand name, its logo, its website and its products. <Endpoint id="get-store-brands-slug" method="GET" path="/store/brands/{slug}" auth="public"> <Params title="Path parameters"> <Field name="slug" type="string" required> Slug of the brand, such as `maison-cuir`. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `products` embeds the published products of the brand in the sales channel, without pagination. </Field> <Field name="fields[brands]" type="string"> Comma-separated attributes to return, such as `name,slug,thumbnail`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> The API returns enabled brands only, by slug: ```bash title="Request" curl http://localhost:8000/store/brands/maison-cuir \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the brand: ```json title="Response 200" { "data": { "id": "01JD8XV1C3E5G7J9K1M3P5R7T9", "type": "brands", "attributes": { "name": "Maison Cuir", "slug": "maison-cuir", "website": "https://maisoncuir.example", "description": "<p>Leather shoes made in Portugal since 1962.</p>", "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-15T10:00:00+00:00", "updated_at": "2026-09-15T10:00:00+00:00" } } } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No enabled brand with this slug | | 400 | `bad_request` | An unknown include | </Errors> </Endpoint> `thumbnail` is the brand logo as a media object, or `null`. The brand endpoints accept `filter[name]` (partial match), `sort=name` or `sort=position`, and `include=products`, which embeds the published products of the brand in the sales channel, with their stock but without pagination. For a paginated grid, call the product listing with `filter[brand]=maison-cuir`. <Endpoint id="get-store-brands" method="GET" path="/store/brands" auth="public"> <Params title="Query parameters"> <Field name="filter[name]" type="string"> Keeps the brands whose name contains the value, case-insensitively. </Field> <Field name="sort" type="string"> `name` or `position`, prefixed with `-` for descending order. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="include" type="string"> `products` embeds the published products of each brand in the sales channel, without pagination. </Field> <Field name="fields[brands]" type="string"> Comma-separated attributes to return, such as `name,slug,thumbnail`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="page[size]" type="integer" default="15"> Brands per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> Page to return, from 1 to 100. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="page[cursor]" type="string"> Cursor from the `links` of a previous page. Switches the listing to cursor pagination. </Field> </Params> A brand directory lists the brands by name. This request reads the first page, two brands per page: ```bash title="Request" curl -g "http://localhost:8000/store/brands?sort=name&page[size]=2" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with a page of brands, the pagination links and the page details: ```json title="Response 200" { "data": [ { "id": "01JD8XV0B2D4F6H8J0K2M4P6R8", "type": "brands", "attributes": { "name": "Atelier Ferrand", "slug": "atelier-ferrand", "website": "https://atelierferrand.example", "description": "<p>Leather bags and belts made in Lyon.</p>", "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-15T09:30:00+00:00", "updated_at": "2026-09-15T09:30:00+00:00" } }, { "id": "01JD8XV1C3E5G7J9K1M3P5R7T9", "type": "brands", "attributes": { "name": "Maison Cuir", "slug": "maison-cuir", "website": "https://maisoncuir.example", "description": "<p>Leather shoes made in Portugal since 1962.</p>", "seo_title": null, "seo_description": null, "metadata": null, "thumbnail": null, "created_at": "2026-09-15T10:00:00+00:00", "updated_at": "2026-09-15T10:00:00+00:00" } } ], "links": { "first": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=3", "prev": null, "next": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 3, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=2", "label": "2", "page": 2, "active": false }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=3", "label": "3", "page": 3, "active": false }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=2", "label": "Next »", "page": 2, "active": false } ], "path": "http://localhost:8000/store/brands", "per_page": 2, "to": 2, "total": 5 } } ``` <Errors> | Status | Code | When | |--------|------|------| | 422 | `filter_too_wide` | A filter has more than 50 values | | 400 | `bad_request` | An unknown filter, sort or include | </Errors> </Endpoint> ## Tags [#tags] Tags label products across categories, such as "vegan" or "new-season". <Endpoint id="get-store-tags" method="GET" path="/store/tags" auth="public"> <Params title="Query parameters"> <Field name="filter[name]" type="string"> Keeps the tags whose name contains the value, case-insensitively. </Field> <Field name="sort" type="string"> `name`, or `-name` for descending order. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="include" type="string"> `products` embeds the published products of each tag in the sales channel, without pagination. </Field> <Field name="fields[tags]" type="string"> Comma-separated attributes to return, such as `name,slug`. With `include=products`, `fields[products]` does the same for the products. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="page[size]" type="integer" default="15"> Tags per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> Page to return, from 1 to 100. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="page[cursor]" type="string"> Cursor from the `links` of a previous page. Switches the listing to cursor pagination. </Field> </Params> The API lists every tag, with no show endpoint, so a storefront uses them to build filter chips or tag pages: ```bash title="Request" curl -g "http://localhost:8000/store/tags?sort=name&page[size]=50" \ -H "Accept: application/vnd.api+json" ``` <Errors> | Status | Code | When | |--------|------|------| | 422 | `filter_too_wide` | A filter has more than 50 values | | 400 | `bad_request` | An unknown filter, sort or include | </Errors> </Endpoint> Each tag carries `name`, `slug`, `created_at` and `updated_at`. The listing accepts `filter[name]` (partial match), `sort=name`, `include=products` and the pagination parameters. As with collections, the products embedded in a tag carry no stock, so a tag page calls the product listing with `filter[tag]=vegan`. ## Attributes [#attributes] A filter sidebar offers the attributes a visitor can narrow the catalog by, such as size or color, with their values. The attribute listing returns the attributes the merchant marked as filterable, of the types that have predefined values: `checkbox`, `colorpicker` and `select`. <Endpoint id="get-store-attributes" method="GET" path="/store/attributes" auth="public"> <Params title="Query parameters"> <Field name="filter[name]" type="string"> Keeps the attributes whose name contains the value, case-insensitively. </Field> <Field name="sort" type="string"> `name`, or `-name` for descending order. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="fields[attributes]" type="string"> Comma-separated attributes to return, such as `name,values`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="page[size]" type="integer" default="15"> Attributes per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> Page to return, from 1 to 100. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="page[cursor]" type="string"> Cursor from the `links` of a previous page. Switches the listing to cursor pagination. </Field> </Params> This request lists the filterable attributes and their values: ```bash title="Request" curl http://localhost:8000/store/attributes \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with a page of attributes and their values: ```json title="Response 200" { "data": [ { "id": "01JD8XS1A3C5E7G9J1M3P5R7T9", "type": "attributes", "attributes": { "name": "Size", "slug": "size", "description": null, "type": "select", "icon": null, "values": [ { "key": "42", "value": "42", "position": 1 }, { "key": "43", "value": "43", "position": 2 } ] } }, { "id": "01JD8XS2B4D6F8H0K2N4Q6S8V0", "type": "attributes", "attributes": { "name": "Color", "slug": "color", "description": null, "type": "colorpicker", "icon": null, "values": [ { "key": "#000000", "value": "Black", "position": 1 }, { "key": "#8b4513", "value": "Brown", "position": 2 } ] } } ], "links": { "first": "http://localhost:8000/store/attributes?page%5Bnumber%5D=1", "last": "http://localhost:8000/store/attributes?page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/attributes?page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/attributes", "per_page": 15, "to": 2, "total": 2 } } ``` <Errors> | Status | Code | When | |--------|------|------| | 422 | `filter_too_wide` | A filter has more than 50 values | | 400 | `bad_request` | An unknown filter or sort, or any include | </Errors> </Endpoint> When the visitor ticks a value, pass its `key` or its `value` to `filter[option]` on the product listing. Several values in one filter mean OR, so `filter[option]=42,43` keeps the products available in size 42 or 43. The filter does not know which attribute a value belongs to, and it cannot require two values at once: `filter[option]=42,Black` returns the products in size 42 or in black, not the black ones in size 42. A product matches when one of its variants carries the value, whatever the stock of that variant. Encode a hex key in the URL, `%23000000` for `#000000`, or send the label instead. `values` lists every value of the attribute, including values no visible product uses, so a facet can lead to an empty result. The values come in no set order: sort them by `position` before showing them. The listing accepts `filter[name]` (partial match), `sort=name` and the pagination parameters, without includes. The [Attributes](/3.x/attributes#searchable-and-filterable-attributes) page explains how a merchant makes an attribute filterable. ## Reviews [#reviews] Reviews give a product page its stars, its rating summary and the comments of buyers. The API returns approved reviews only, with the author name shortened to a first name and an initial. ### Reviews of a Product [#reviews-of-a-product] The reviews of a product are paginated, newest first, and the response adds the rating summary of the product in `meta`. The product must be published, or the API answers `404`. <Endpoint id="get-store-products-slug-reviews" method="GET" path="/store/products/{slug}/reviews" auth="public"> <Params title="Path parameters"> <Field name="slug" type="string" required> Slug of a published product, such as `classic-leather-sneakers`. </Field> </Params> <Params title="Query parameters"> <Field name="filter[rating]" type="integer"> Keeps the reviews with this exact rating, from 1 to 5. </Field> <Field name="sort" type="string" default="-created_at"> `created_at` or `rating`, prefixed with `-` for descending order. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="fields[reviews]" type="string"> Comma-separated attributes to return, such as `rating,title,content`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="page[size]" type="integer" default="15"> Reviews per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> Page to return, from 1 to 100. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="page[cursor]" type="string"> Cursor from the `links` of a previous page. Switches the listing to cursor pagination. </Field> </Params> This request keeps the 3-star reviews, as a "3 stars" filter of the rating summary would: ```bash title="Request" curl -g "http://localhost:8000/store/products/classic-leather-sneakers/reviews?filter[rating]=3" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK`. The summary in `meta` counts every approved review of the product, whatever the filter: ```json title="Response 200" { "data": [ { "id": "01JD9A2K4M6P8R0T2V4X6Z8B0D", "type": "reviews", "attributes": { "title": "Runs half a size small", "content": "Nice leather and a clean look. Order half a size up.", "rating": 3, "is_recommended": true, "author": { "name": "Camille M.", "avatar": "http://localhost:8000/storage/avatars/kD3f9QmZ7xWb2LpR8sTn4VhY6cJe1AuG0oNi5MrK.jpg" }, "created_at": "2026-11-10T16:42:00+00:00" } } ], "links": { "first": "http://localhost:8000/store/products/classic-leather-sneakers/reviews?filter%5Brating%5D=3&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/products/classic-leather-sneakers/reviews?filter%5Brating%5D=3&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/products/classic-leather-sneakers/reviews?filter%5Brating%5D=3&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/products/classic-leather-sneakers/reviews", "per_page": 15, "to": 1, "total": 1, "reviews_count": 12, "average_rating": 4.6, "rating_distribution": { "1": 0, "2": 0, "3": 1, "4": 3, "5": 8 } } } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No published product with this slug | | 422 | `filter_too_wide` | A filter has more than 50 values | | 400 | `bad_request` | An unknown filter or sort, or any include | </Errors> </Endpoint> `average_rating` is rounded to one decimal, and `null` when the product has no approved review. `rating_distribution` always has the five keys, so a storefront draws the bars without checking for missing ratings. `author` is `null` when the author account no longer exists. The endpoint accepts `filter[rating]` (exact), `sort=created_at` or `sort=rating` with `-` for descending (the default is `-created_at`), and the pagination parameters. For the stars on a product card, `include=rating` on the product listing is cheaper: it adds `rating` and `reviews_count` to each product without reading the reviews. ### Latest Reviews [#latest-reviews] A home page testimonials block shows the most recent reviews of the whole shop. <Endpoint id="get-store-reviews" method="GET" path="/store/reviews" auth="public"> <Params title="Query parameters"> <Field name="fields[reviews]" type="string"> Comma-separated attributes to return, such as `rating,title,content`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> `/store/reviews` returns the latest approved reviews, newest first, capped at 20 by `reviews.latest_limit` in `config/shopper/api.php`: ```bash title="Request" curl http://localhost:8000/store/reviews \ -H "Accept: application/vnd.api+json" ``` </Endpoint> The response holds a `data` list of reviews in the shape above, with no `links` or `meta`: the endpoint has no pagination, filters or sorting. A review does not say which product it belongs to, so this block cannot link a review to its product page. ## Next Steps [#next-steps] With the products on screen, the next step is the cart. The store settings and the zones decide the currency and the prices this page shows. <Cards> <Card title="Cart" href="/3.x/store-api/cart"> Create a cart and add a product or a variant to it. </Card> <Card title="Store and regions" href="/3.x/store-api/store"> Read the store settings, the zones and the currencies, and pick a zone for the visitor. </Card> </Cards> # Checkout (/3.x/store-api/checkout) Checkout turns a cart into an order. The storefront offers the shipping options and payment methods the API returns for the cart, opens a payment at the provider for the amount the API computes, lets the customer pay in the browser, then completes the cart. The API owns every amount: it quotes shipping, sets the amount of the payment, checks prices and stock again before it places the order, and answers with the order. This guide starts where [Cart](/3.x/store-api/cart) ends, with a cart that holds lines, an email and a shipping address. Amounts are integers in cents, as on the cart. A checkout goes through four steps: <Steps> <Step title="Set the shipping method"> List the shipping options of the cart and send back the one the customer picks. </Step> <Step title="Set the payment method"> List the payment methods of the cart and send back the one the customer picks. </Step> <Step title="Open a payment session"> Ask the API to open the payment at the provider, then let the customer confirm it in the browser with the provider's SDK, such as Stripe.js. </Step> <Step title="Complete the cart"> Place the order once the provider has confirmed the payment. The provider's webhooks then move the payment status of the order. </Step> </Steps> A cart that needs no delivery skips the first step, and a payment method that collects offline, such as a bank transfer, skips the third. ## Endpoints [#endpoints] The checkout endpoints take the cart ID and follow the access rules of the cart endpoints: a guest cart answers to any request that carries its ID, a customer cart only to the bearer token of its owner, as described in [Cart](/3.x/store-api/cart). The calls that set the payment method, open the payment session and complete the cart share the checkout rate limit of 30 requests per minute (`shopper.http.rate_limiters`), counted per IP address, on top of the general limit described in [Rate limits](/3.x/store-api#rate-limits). <Routes> <Route method="GET" path="/store/carts/{cartId}/shipping-options" href="#get-store-carts-cartid-shipping-options">List the shipping options</Route> <Route method="POST" path="/store/carts/{cartId}/shipping-method" href="#post-store-carts-cartid-shipping-method">Set the shipping method</Route> <Route method="GET" path="/store/carts/{cartId}/payment-methods" href="#get-store-carts-cartid-payment-methods">List the payment methods</Route> <Route method="POST" path="/store/carts/{cartId}/payment-method" href="#post-store-carts-cartid-payment-method">Set the payment method</Route> <Route method="POST" path="/store/carts/{cartId}/payment-session" href="#post-store-carts-cartid-payment-session">Open or resume the payment session</Route> <Route method="POST" path="/store/carts/{cartId}/complete" href="#post-store-carts-cartid-complete">Place the order</Route> <Route method="POST" path="/store/webhooks/{driver}" href="#post-store-webhooks-driver">Receive the events of a payment provider</Route> <Route method="POST" path="/store/webhooks/shipping/{driver}" href="#post-store-webhooks-shipping-driver">Receive the tracking events of a carrier</Route> </Routes> The two listing endpoints return every option in one response: they take no filters, sorts, includes or pagination. Request bodies are flat JSON objects sent with `Content-Type: application/json`, and responses are JSON:API documents, described in [JSON:API Conventions](/3.x/store-api/json-api). ## Shipping Options [#shipping-options] The shipping options depend on the cart: its zone, the carriers of that zone, the shippable lines and the shipping address. Carriers that quote live rates, such as UPS, FedEx or USPS once their credentials are set, need the shipping address and an inventory location to ship from: until the address is set, they are left out without a warning. The other carriers of the zone offer the options set up for them in the admin panel, at a fixed price. [Carriers](/3.x/carriers) describes both kinds. List the options after the shipping address is set, so that every carrier can answer. <Endpoint id="get-store-carts-cartid-shipping-options" method="GET" path="/store/carts/{cartId}/shipping-options" auth="owner"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The cart ID, the `id` returned by [Creating a Cart](/3.x/store-api/cart#creating-a-cart). </Field> </Params> <Params title="Query parameters"> <Field name="fields[shipping-options]" type="string"> Comma-separated attributes to return, such as `name,amount,estimated_days`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request lists the shipping options of the cart, once its shipping address is set: ```bash title="Request" curl http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/shipping-options \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the options and a `meta.warnings` list: ```json title="Response 200" { "data": [ { "id": "colissimo:01JD8XM5N7Q9S1T3W5Y7A9C1E3", "type": "shipping-options", "attributes": { "name": "Colissimo Home", "carrier_name": "Colissimo", "carrier_code": "colissimo", "service_code": "01JD8XM5N7Q9S1T3W5Y7A9C1E3", "amount": 690, "currency": "EUR", "price_type": "flat", "estimated_days": null, "estimated_delivery": null } }, { "id": "chronopost:01JD8XN8P0R2T4V6X8Z0B2D4F6", "type": "shipping-options", "attributes": { "name": "Chronopost 24h", "carrier_name": "Chronopost", "carrier_code": "chronopost", "service_code": "01JD8XN8P0R2T4V6X8Z0B2D4F6", "amount": 1490, "currency": "EUR", "price_type": "flat", "estimated_days": null, "estimated_delivery": null } } ], "meta": { "warnings": [] } } ``` The `id` of an option is `{carrier_code}:{service_code}`, the value the storefront sends back to choose it. The options are computed for each request and never stored, so their IDs and prices can change between two calls. <Attributes title="shipping-options attributes"> <Field name="name" type="string"> Name of the service, to show to the customer. </Field> <Field name="carrier_name" type="string"> Name of the carrier. </Field> <Field name="carrier_code" type="string"> Slug of the carrier. </Field> <Field name="service_code" type="string"> Code of the service at the carrier, or the ID of the option for a fixed-price option. </Field> <Field name="amount" type="integer"> Price of the option, in cents. </Field> <Field name="currency" type="string"> ISO code of the price, always the cart currency. </Field> <Field name="price_type" type="string"> `flat` for a fixed-price option, `calculated` for a live rate. </Field> <Field name="estimated_days" type="string, null"> Delivery time quoted by the carrier, `null` for a fixed-price option. </Field> <Field name="estimated_delivery" type="string, null"> Delivery date quoted by the carrier, `null` for a fixed-price option. </Field> </Attributes> <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `http_error` | The cart has no zone | </Errors> </Endpoint> ### Empty Lists and Warnings [#empty-lists-and-warnings] An empty list does not always mean the same thing, and `meta.warnings` explains most cases. Warnings are sentences meant for a log or a notice, not codes: branch on the options themselves. | Situation | Options | Warning | |-----------|---------|---------| | No line of the cart ships | None | None: the cart needs no shipping method | | The country of the shipping address is outside the zone of the cart | None | "The shipping address is outside the cart zone. Choose the zone of its country." | | No inventory location can be the origin of a shipment | Fixed-price options only | "Live carrier rates are unavailable: no inventory location can act as the shipment origin." | | A carrier did not answer | The options of the other carriers | "Rates from "UPS" are temporarily unavailable." | | A carrier quoted in another currency | The options in the cart currency | "Options priced in USD were removed: the cart is priced in EUR." | A line ships unless it holds a virtual product added as a product, such as an e-book. A variant always counts as shippable, even when its product is virtual. When the shipping address is outside the zone, switch the cart to the zone of that country with `zone_code`, as described in [Cart](/3.x/store-api/cart), and list the options again. A cart created without a known `X-Shopper-Zone` header, in an application that sets no `shopper.http.zone.default_code`, has no zone. Listing its options answers `422` with the generic code `http_error` and the detail "The cart has no shipping zone, so no shipping option applies to it.": set a zone on the cart first. ## Setting the Shipping Method [#setting-the-shipping-method] The storefront sends back the ID of the option the customer picked. The API quotes the options of the cart again and keeps the price of that new quote, so the shipping price always comes from the server. <Endpoint id="post-store-carts-cartid-shipping-method" method="POST" path="/store/carts/{cartId}/shipping-method" auth="owner"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The cart ID. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> Related resources to return with the cart, listed in [Reading a Cart](/3.x/store-api/cart#reading-a-cart). </Field> <Field name="fields[carts]" type="string"> Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> <Params title="Body"> <Field name="option_id" type="string" required> The `id` of a shipping option, such as `colissimo:01JD8XM5N7Q9S1T3W5Y7A9C1E3`. </Field> </Params> This request picks the Colissimo option of the listing above: ```bash title="Request" curl -X POST http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/shipping-method \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"option_id": "colissimo:01JD8XM5N7Q9S1T3W5Y7A9C1E3"}' ``` The API answers `200 OK` with the cart. Shipping now shows in `shipping_total` and in `total`. The response is trimmed to the totals: ```json title="Response 200" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "subtotal": 18000, "discount_total": 1800, "tax_total": 2700, "shipping_total": 690, "total": 16890, "tax_inclusive": true, "shipping_option_id": "colissimo:01JD8XM5N7Q9S1T3W5Y7A9C1E3" } } } ``` An ID that the carriers no longer quote for this cart answers `422 shipping_option_unavailable` on `/data/attributes/option_id`: list the options again. When the carrier of that option failed to answer, the API answers `503 shipping_provider_unavailable` with a `Retry-After: 5` header instead, since the option may come back. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `shipping_option_unavailable` | The carriers no longer quote this option for the cart | | 422 | `http_error` | The cart has no zone | | 422 | Rule name, such as `required` | `option_id` fails validation | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: complete the cart | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `shipping_provider_unavailable` | The carrier of the option did not answer, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | </Errors> </Endpoint> Changing the currency or the zone of the cart removes its shipping method: list the options and set it again after such a change. ## Payment Methods [#payment-methods] A payment method is the way the customer pays: a card through Stripe, a bank transfer, cash on delivery. The API offers the enabled payment methods of the zone of the cart whose driver is configured, so a Stripe method shows only once its secret key and webhook secret are set. A cart without a zone gets every enabled method with a configured driver. [Payment Methods](/3.x/payment-methods) describes how methods are set up and attached to zones. <Endpoint id="get-store-carts-cartid-payment-methods" method="GET" path="/store/carts/{cartId}/payment-methods" auth="owner"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The cart ID. </Field> </Params> <Params title="Query parameters"> <Field name="fields[payment-methods]" type="string"> Comma-separated attributes to return, such as `title,logo`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request lists the payment methods of the cart: ```bash title="Request" curl http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/payment-methods \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the methods: ```json title="Response 200" { "data": [ { "id": "01JD8XR3T5V7X9Z1B3D5F7H9K1", "type": "payment-methods", "attributes": { "title": "Credit card", "slug": "credit-card", "description": "Visa, Mastercard and American Express.", "instructions": null, "driver": "stripe", "logo": "http://localhost:8000/vendor/shopper/images/payments/stripe.svg" } }, { "id": "01JD8XR3T5V7X9Z1B3D5F7H9K2", "type": "payment-methods", "attributes": { "title": "Bank transfer", "slug": "bank-transfer", "description": "Pay by bank transfer within 7 days.", "instructions": "Transfer the total to IBAN FR76 3000 6000 0112 3456 7890 189 with your order number as the reference.", "driver": "manual", "logo": "http://localhost:8000/vendor/shopper/images/payments/cod.svg" } } ] } ``` The `driver` tells the storefront which flow to run. A `manual` method collects offline: it needs no payment session, and its `instructions` hold what the customer must do, to show on the confirmation page. Any other driver, such as `stripe`, collects online through a payment session. The `logo` is the URL of the logo of the driver, the same for every method of that driver, and `null` for a driver without a logo. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | </Errors> </Endpoint> ## Setting the Payment Method [#setting-the-payment-method] The storefront sends the ID of the method the customer picked. Ask for the `paymentMethod` include to get the method back with the cart. <Endpoint id="post-store-carts-cartid-payment-method" method="POST" path="/store/carts/{cartId}/payment-method" auth="owner" limit="checkout"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The cart ID. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> Related resources to return with the cart, listed in [Reading a Cart](/3.x/store-api/cart#reading-a-cart). </Field> <Field name="fields[carts]" type="string"> Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> <Params title="Body"> <Field name="payment_method_id" type="string" required> The `id` of a payment method listed for the cart. </Field> </Params> This request picks the credit card method of the listing above, and asks for it back with `include=paymentMethod`: ```bash title="Request" curl -X POST "http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/payment-method?include=paymentMethod" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{"payment_method_id": "01JD8XR3T5V7X9Z1B3D5F7H9K1"}' ``` The API answers `200 OK` with the cart, trimmed here to the total and the method: ```json title="Response 200" { "data": { "id": "01JD8Z6Q4M3K2V7R9T5W1XNB0C", "type": "carts", "attributes": { "currency_code": "EUR", "total": 16890 }, "relationships": { "paymentMethod": { "data": { "id": "01JD8XR3T5V7X9Z1B3D5F7H9K1", "type": "payment-methods" } } } }, "included": [ { "id": "01JD8XR3T5V7X9Z1B3D5F7H9K1", "type": "payment-methods", "attributes": { "title": "Credit card", "slug": "credit-card", "description": "Visa, Mastercard and American Express.", "instructions": null, "driver": "stripe", "logo": "http://localhost:8000/vendor/shopper/images/payments/stripe.svg" } } ] } ``` An ID that matches no enabled payment method answers `422 exists` on `/data/attributes/payment_method_id`. An enabled method that the cart does not offer, because of its zone or an unconfigured driver, answers `422 payment_method_unavailable` on the same pointer. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `exists` | No enabled payment method has this ID | | 422 | `payment_method_unavailable` | The cart does not offer this method, because of its zone or an unconfigured driver | | 422 | Rule name, such as `required` | `payment_method_id` fails validation | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The customer already paid: the method can no longer change | | 409 | `payment_session_in_progress` | Another request is changing the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The open payment could not be cancelled, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | </Errors> </Endpoint> Changing the method cancels the payment session opened for the previous one at the provider, so the order never holds a payment of another method. Once the customer has paid, the method can no longer change and the API answers `409 payment_session_collected`. A zone switch removes the payment method of the cart; a currency switch keeps it. ## Opening a Payment Session [#opening-a-payment-session] The payment provider must collect an amount that the server computed, not the browser. The payment session does that: the API prices the lines again, quotes the shipping method again, computes the total, and opens a payment for that total at the provider of the payment method, such as a Stripe PaymentIntent. The response carries what the provider's browser SDK needs to collect the payment. The request has no body. <Endpoint id="post-store-carts-cartid-payment-session" method="POST" path="/store/carts/{cartId}/payment-session" auth="owner" limit="checkout"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The cart ID. </Field> </Params> <Params title="Query parameters"> <Field name="fields[payment-sessions]" type="string"> Comma-separated attributes to return, such as `status,redirect_url`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request opens the payment session of the cart, at the provider of its payment method: ```bash title="Request" curl -X POST http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/payment-session \ -H "Accept: application/vnd.api+json" ``` The API answers `201 Created` with the session. With Stripe, its `id` is the PaymentIntent ID: ```json title="Response 201" { "data": { "id": "pi_3QL2mNLkdIwHu7ix0Ab3Cd4E", "type": "payment-sessions", "attributes": { "driver": "stripe", "status": "pending", "amount": 16890, "currency_code": "EUR", "client_secret": "pi_3QL2mNLkdIwHu7ix0Ab3Cd4E_secret_Z8kQw2nV5rT1yH6pL3mX", "redirect_url": null, "data": { "stripe_status": "requires_payment_method", "publishable_key": "pk_test_51QJ7xYLkdIwHu7ixT9bWm2Qe", "idempotency_key": "cart_01JD8Z6Q4M3K2V7R9T5W1XNB0C_01JD8ZH6K8M0P2R4T6V8X0Z2B4" } } } } ``` <Attributes title="payment-sessions attributes"> <Field name="driver" type="string"> Driver of the payment method, such as `stripe`. </Field> <Field name="status" type="string"> Status of the payment at the provider: `pending`, `requires_action`, `processing`, `authorized`, `captured` or `canceled`. </Field> <Field name="amount" type="integer"> Amount to collect, in cents, the `total` of the cart. </Field> <Field name="currency_code" type="string"> Currency of the cart. </Field> <Field name="client_secret" type="string, null"> Secret the provider's browser SDK confirms the payment with. </Field> <Field name="redirect_url" type="string, null"> Page of the provider to send the customer to, for a driver that collects on its own page. </Field> <Field name="data" type="object, array"> Extra values for the browser: `stripe_status`, `publishable_key` and `idempotency_key` when the driver sets them, an empty array `[]` when it sets none. </Field> </Attributes> <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `payment_method_required` | The cart has no payment method | | 422 | `price_changed` | A price went up | | 422 | `price_missing` | A line has no price in the cart currency anymore | | 422 | `quantity_rule_violated` | A quantity breaks a rule of its price, details in `meta` | | 422 | `shipping_method_required` | The cart has no shipping method | | 422 | `shipping_option_unavailable` | The shipping option is no longer quoted | | 422 | `shipping_price_changed` | The shipping option costs more | | 422 | `cart_nothing_to_collect` | The total is zero | | 409 | `conflict` | The cart is already an order | | 409 | `cart_completed` | The cart was completed during the call | | 409 | `payment_session_in_progress` | Another request holds the cart, retry after `Retry-After` | | 409 | `payment_session_collected` | The payment was collected meanwhile: complete the cart | | 503 | `payment_method_not_configured` | The driver lost its configuration | | 503 | `shipping_provider_unavailable` | The carrier did not answer, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The provider did not answer, retry after `Retry-After` | </Errors> </Endpoint> With Stripe, load Stripe.js with `data.publishable_key`, mount the Payment Element with `client_secret` and confirm the payment with `stripe.confirmPayment()`. The [Stripe](/3.x/payments/stripe) page walks through the browser side, and [Payments](/3.x/payments#payment-sessions) describes sessions for every driver. ### Calling It Again [#calling-it-again] The storefront can call the endpoint again, for example when the payment page reloads. When the amount, the currency and the promotions of the cart have not changed, the API resumes the open session and answers with the same `id` and `client_secret`. A resumed Stripe session carries only `stripe_status` in `data`, so keep the publishable key in the storefront configuration as well. Drivers that cannot read a payment back from the provider open a new session on every call. When the cart changed, the API cancels the open payment at the provider and opens a new one with a new `client_secret`: mount the payment form again with it. Changing the lines, a promotion code, the currency, the zone or the shipping method also cancels the open session right away. A form that still holds the previous client secret cannot confirm the payment, so open a new session after every change to the cart. Once the provider has collected the payment (`authorized`, `captured` or `processing`), the API returns that session as it is and the cart is frozen: every change answers `409 payment_session_collected`. Complete the cart. ### Manual Payment Methods [#manual-payment-methods] A method with the `manual` driver needs no session: complete the cart directly. Opening one anyway answers `201` with a session whose status is `authorized` and whose `id` starts with `manual_`, which collects nothing: its `client_secret` and `redirect_url` are `null` and its `data` is an empty array. ### When the Session Cannot Open [#when-the-session-cannot-open] The API checks the cart before it calls the provider. Each failure answers with a code the storefront can act on: | Code | Status | Pointer | What to do | |------|--------|---------|------------| | `conflict` | 409 | | The cart is already an order: read the order | | `cart_completed` | 409 | | Same, when the cart was completed during the call | | `payment_method_required` | 422 | `/data/attributes/payment_method` | Set a payment method | | `payment_method_not_configured` | 503 | | The driver lost its configuration: offer another method | | `price_changed` | 422 | `/data/attributes/cart` | A price went up: show the new total, then open the session again | | `price_missing` | 422 | `/data/attributes/cart` | A line has no price in the cart currency anymore: remove it | | `quantity_rule_violated` | 422 | `/data/attributes/cart` | A quantity breaks a rule of its price, details in `meta` | | `shipping_method_required` | 422 | `/data/attributes/shipping_method` | Set a shipping method | | `shipping_option_unavailable` | 422 | `/data/attributes/shipping_method` | The option is no longer quoted: choose another one | | `shipping_price_changed` | 422 | `/data/attributes/shipping_method` | The option costs more: set the shipping method again to accept the new price | | `shipping_provider_unavailable` | 503 | | The carrier did not answer: retry after `Retry-After` (5 seconds) | | `cart_nothing_to_collect` | 422 | `/data/attributes/cart` | The total is zero | | `payment_provider_unavailable` | 503 | | The provider did not answer: retry after `Retry-After` (5 seconds) | | `payment_session_in_progress` | 409 | | Another request holds the cart: retry after `Retry-After` (3 seconds) | | `payment_session_collected` | 409 | | The payment was collected meanwhile: complete the cart | A completed cart answers the generic `conflict` code on this endpoint, where every other endpoint answers `cart_completed`: treat both the same way. A cart with a total of zero, after a 100% promotion for example, cannot open a session, and completing it with an online method answers `payment_session_required`: such a cart can only be completed with a `manual` method. ## Completing the Cart [#completing-the-cart] Completing the cart places the order. The API checks the cart one last time, reserves the stock, records the payment session on the order and marks the cart as completed. Call it once the provider has confirmed the payment: with Stripe, on the page Stripe sends the customer back to (`return_url`). For a `manual` method, call it when the customer confirms the order. <Endpoint id="post-store-carts-cartid-complete" method="POST" path="/store/carts/{cartId}/complete" auth="owner" limit="checkout"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The cart ID. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `items` to return the order items with the order. Other paths are ignored. </Field> <Field name="fields[orders]" type="string"> Comma-separated attributes to return, such as `number,status`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request places the order of the cart, and asks for its items with `include=items`: ```bash title="Request" curl -X POST "http://localhost:8000/store/carts/01JD8Z6Q4M3K2V7R9T5W1XNB0C/complete?include=items" \ -H "Accept: application/vnd.api+json" ``` The API answers `201 Created` with the order, and its items when the request asks for `include=items`: ```json title="Response 201" { "data": { "id": "01JD8ZM4P6R8T0V2X4Z6B8D0F2", "type": "orders", "attributes": { "number": "ORD-20261119-000042", "status": "new", "payment_status": "pending", "shipping_status": "unfulfilled", "total": 16200, "tax_amount": 2700, "shipping_amount": 690, "price_amount": 16890, "currency_code": "EUR", "created_at": "2026-11-19T10:24:31+00:00" }, "relationships": { "items": { "data": [ { "id": "01JD8ZM4P6R8T0V2X4Z6B8D0F3", "type": "order-items" } ] } } }, "included": [ { "id": "01JD8ZM4P6R8T0V2X4Z6B8D0F3", "type": "order-items", "attributes": { "name": "Classic Leather Sneakers / 42 / Black", "sku": "CLS-BLK-42", "quantity": 2, "unit_price_amount": 9000, "total": 16200, "metadata": null } } ] } ``` Completing a cart that is already completed answers `200 OK` with the same order. A storefront that loses the response to a timeout calls the endpoint again and gets the order it placed, never a second one. Keep the order `id`: the [Orders](/3.x/store-api/orders) guide reads the order back with it. Only `items` is loaded on this response; other include paths are ignored here. <Attributes title="orders attributes"> <Field name="number" type="string"> Order number to show to the customer, from the `shopper.orders.generator` setting. </Field> <Field name="status" type="string"> `new` when the order is placed. </Field> <Field name="payment_status" type="string"> `pending` until the provider confirms, then `authorized`, `paid`, `partially_refunded`, `refunded` or `voided`. </Field> <Field name="shipping_status" type="string"> `unfulfilled` when the order is placed. </Field> <Field name="total" type="integer"> Sum of the item totals (unit price times quantity, minus discounts), in cents, without shipping. </Field> <Field name="tax_amount" type="integer"> Tax of the order, in cents. </Field> <Field name="shipping_amount" type="integer, null"> Shipping price, in cents. </Field> <Field name="price_amount" type="integer"> Amount charged, in cents: the `total` of the cart. </Field> <Field name="currency_code" type="string"> Currency of the order. </Field> <Field name="email" type="string, null"> Contact email of the order. </Field> <Field name="created_at" type="string"> ISO 8601. </Field> </Attributes> The `total` of an order is not the `total` of the cart: the amount the customer pays is `price_amount`. An `order-items` resource carries `name` (the product name, followed by the variant name for a variant), `sku`, `quantity`, `unit_price_amount`, `total` (unit price times quantity, minus the discount of the item) and `metadata`, copied from the cart line. [Orders](/3.x/orders) describes the statuses. The email of the order is the email of the cart, or the account email of the customer for a customer cart. A guest cart without an email answers `422 email_required` on `/data/attributes/email`: set it with the addresses or with a cart update. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No cart with this ID for this request | | 422 | `cart_empty` | The cart has no line | | 422 | `payment_method_required` | The cart has no payment method | | 422 | `email_required` | A guest cart has no email | | 422 | `shipping_method_required` | The cart has no shipping method | | 422 | `shipping_option_unavailable` | The shipping option is no longer quoted | | 422 | `shipping_price_changed` | The shipping option costs more | | 422 | `payment_session_required` | An online payment method has no payment session | | 422 | `payment_session_mismatch` | The cart changed since the session opened | | 422 | `price_changed` | A price went up | | 422 | `price_missing` | A line has no price | | 422 | `quantity_rule_violated` | A quantity breaks a rule of its price, details in `meta` | | 422 | `stock_insufficient` | Not enough stock for a line | | 422 | `payment_released` | The stock ran out after the payment, and the payment was given back | | 422 | `promotion_not_applicable` | A promotion of the cart no longer applies | | 422 | `promotion_limit_reached` | A promotion reached its usage limit | | 422 | `promotion_budget_reached` | The campaign of a promotion spent its budget | | 409 | `payment_session_in_progress` | Another request holds the cart, retry after `Retry-After` | | 503 | `shipping_provider_unavailable` | The carrier did not answer, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The provider did not answer, retry after `Retry-After` | </Errors> </Endpoint> ### Payment Status After Placement [#payment-status-after-placement] The order starts with `payment_status: "pending"`, and the provider's events, received on the payment webhook, move it. With Stripe, the browser confirms the payment before the storefront completes the cart, so the event often arrives first: the API applies the events that arrived before the order during the complete call, and the response can already show `authorized` or `paid`. When `shopper.payment.reconciliation.pull_on_completion` is on (the default), the API also queues a check of the payment at the provider. A confirmation page shows the order as awaiting payment until the status moves. An order still unpaid 24 hours after it was placed through an online method is cancelled by the hourly `shopper:orders:reclaim` command, which cancels the payment at the provider and puts the stock back on sale. The delay is `shopper.orders.reclaim_pending_after_hours`. Orders paid with a `manual` method are never cancelled this way. ### When the Order Cannot Be Placed [#when-the-order-cannot-be-placed] The complete call runs the checks of the payment session again, and adds its own: | Code | Status | Pointer | What to do | |------|--------|---------|------------| | `cart_empty` | 422 | `/data/attributes/cart` | Add a line | | `payment_method_required` | 422 | `/data/attributes/payment_method` | Set a payment method | | `email_required` | 422 | `/data/attributes/email` | Set an email on the cart | | `shipping_method_required` | 422 | `/data/attributes/shipping_method` | Set a shipping method | | `shipping_option_unavailable` | 422 | `/data/attributes/shipping_method` | Choose another shipping option | | `shipping_price_changed` | 422 | `/data/attributes/shipping_method` | Set the shipping method again to accept the new price | | `shipping_provider_unavailable` | 503 | | Retry after `Retry-After` (5 seconds) | | `payment_session_required` | 422 | `/data/attributes/payment_session` | Open a payment session first | | `payment_session_mismatch` | 422 | `/data/attributes/payment_session` | The cart changed since the session opened: open a new session and pay again | | `price_changed` | 422 | `/data/attributes/cart` | A price went up: show the new total | | `price_missing` | 422 | `/data/attributes/cart` | Remove the line that has no price | | `quantity_rule_violated` | 422 | `/data/attributes/cart` | Fix the quantity, details in `meta` | | `stock_insufficient` | 422 | `/data/attributes/cart` | Lower the quantity or remove the line | | `payment_released` | 422 | `/data/attributes/cart` | The stock ran out after the payment: the payment was given back, update the cart and pay again | | `promotion_not_applicable` | 422 | `/data/attributes/promotion` | A promotion of the cart no longer applies: show the new total | | `promotion_limit_reached` | 422 | `/data/attributes/promotion` | A promotion reached its usage limit | | `promotion_budget_reached` | 422 | `/data/attributes/promotion` | The campaign of a promotion spent its budget | | `payment_session_in_progress` | 409 | | Retry after `Retry-After` (3 seconds) | | `payment_provider_unavailable` | 503 | | Retry after `Retry-After` (5 seconds) | The three promotion errors cancel the open payment session, so the storefront opens a new one for the new total before it completes the cart again. ## Price, Stock and Shipping Changes [#price-stock-and-shipping-changes] Time passes between the basket and the payment: a price changes in the admin panel, the last pair sells, a carrier raises a rate. The API checks the cart when the payment session opens and when the cart completes, and never charges more than the customer saw without telling the storefront first. | Change | Opening the payment session | Completing the cart | |--------|-----------------------------|---------------------| | A price went up | The cart takes the new price, then `422 price_changed` | The cart takes the new price, then `422 price_changed` | | A price went down | The cart takes the new price | The cart takes the new price | | The stock ran out | Not checked | `422 stock_insufficient`, or `422 payment_released` when the payment was collected | | The shipping price went up | `422 shipping_price_changed` | `422 shipping_price_changed` | | The shipping price went down | The cart takes the new price | The cart takes the new price | | The shipping option is gone | `422 shipping_option_unavailable` | `422 shipping_option_unavailable` | On `price_changed`, the cart already holds the new prices: read it again, show the new total to the customer, and open the payment session again once they accept it. On `shipping_price_changed`, the cart keeps the old shipping price until the storefront sets the shipping method again. Once the provider has collected the payment, the order keeps what the customer paid for: the API honors the paid prices and the paid shipping price, and a price change no longer blocks the order. Missing stock still does, and the API then gives the payment back before it answers `payment_released`. ## Retries, Idempotency and Locking [#retries-idempotency-and-locking] Checkout calls reach the payment provider and the carriers, can time out, and can race: a double click, two tabs, a retry. The API holds one lock per cart, so these calls run one at a time and a retry is always safe. Setting the shipping method, setting the payment method, opening the payment session, completing the cart and every change to the lines, addresses, promotions, currency or zone of the cart hold the lock of the cart while they run. A call that waits more than 3 seconds for it answers `409 payment_session_in_progress` with `Retry-After: 3`. A provider or a carrier that does not answer gives `503` with `Retry-After: 5`. Retry the same call after the delay. Each new payment session opens at the provider under its own idempotency key, `cart_{cartId}_{ulid}`, which Stripe sessions return in `data.idempotency_key`, and the payment carries the cart ID in its `cart_id` metadata. Completing the cart is idempotent, as [Completing the cart](#completing-the-cart) explains. A customer can pay and close the tab before the storefront completes the cart. The scheduled `shopper:payments:reconcile` command, which runs every 15 minutes, finds payments collected without an order after 30 minutes (`shopper.payment.reconciliation.orphan_after_minutes`) and completes their cart, as described in [Orphaned Payments](/3.x/payments#orphaned-payments). The storefront still completes the cart itself: the command is a safety net. ## Payment Webhooks [#payment-webhooks] The provider reports the outcome of each payment to Shopper through webhooks: authorized, captured, failed, refunded. The payment status of the order follows those events, so the storefront never reports a payment result itself. Register the route of the driver in the provider's dashboard, such as `https://shop.example.com/store/webhooks/stripe` for Stripe, with the events listed in [Handled Events](/3.x/payments/stripe#handled-events). <Endpoint id="post-store-webhooks-driver" method="POST" path="/store/webhooks/{driver}" auth="webhook" limit="webhook"> <Params title="Path parameters"> <Field name="driver" type="string" required> Code of a registered and configured payment driver, such as `stripe`. </Field> </Params> The webhook routes sit in their own route group, without authentication, limited to 120 requests per minute per IP address. The driver checks each request, such as the `Stripe-Signature` header against the webhook secret, then Shopper records the event once by its provider event ID, so a redelivered event is never applied twice. An event that arrives before the order exists waits until the cart is completed. ```bash title="Request" curl -X POST http://localhost:8000/store/webhooks/stripe \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -H "Stripe-Signature: t=1763547871,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd" \ --data-binary @stripe-event.json ``` The route answers `200 OK`, also for an event the driver ignores: ```json title="Response 200" { "received": true } ``` A payload the driver rejects, such as one with an invalid signature, answers `400 Bad Request` with a plain error body, not a JSON:API error object: ```json title="Response 400" { "error": "Invalid webhook payload." } ``` <Errors> | Status | Code | When | |--------|------|------| | 400 | None, plain body | The driver rejects the payload, such as an invalid signature | | 404 | `not_found` | The driver is not registered or not configured | </Errors> </Endpoint> A driver that is not registered, or not configured, answers `404`. [Payments](/3.x/payments#webhooks) describes how Shopper applies the events. ## Shipping Webhooks [#shipping-webhooks] The `/store/webhooks/shipping/{driver}` route receives tracking updates pushed by a carrier and applies them to the shipment. It answers only for a carrier driver that supports webhooks. None of the bundled carriers (manual, UPS, FedEx, USPS) does, so for them the route answers `404`, and tracking comes from the scheduled `shopper:shipments:sync-tracking` command, every 30 minutes while `shopper.shipping.tracking.sync` is on. The route returns the same `200`, `400` and `404` answers as the payment webhooks. [Carrier Tracking](/3.x/fulfillment#carrier-tracking) describes how tracking reaches the order, and [Carriers](/3.x/carriers) how to add a carrier driver. <Endpoint id="post-store-webhooks-shipping-driver" method="POST" path="/store/webhooks/shipping/{driver}" auth="webhook" limit="webhook"> <Params title="Path parameters"> <Field name="driver" type="string" required> Code of a registered and configured carrier driver whose `supportsWebhooks()` returns `true`. </Field> </Params> This request posts a tracking update to `dhl`, a driver of your own registered as in [Custom Shipping Drivers](/3.x/carriers#custom-shipping-drivers), whose `supportsWebhooks()` returns `true`. The body is the payload of the carrier, in its own format: the `handleWebhook()` method of the driver checks that the carrier sent it and reads the tracking update, as [Driver Capabilities](/3.x/carriers#driver-capabilities) describes. ```bash title="Request" curl -X POST http://localhost:8000/store/webhooks/shipping/dhl \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ --data-binary @dhl-tracking-update.json ``` The route answers `200 OK` once the driver has read the payload, also when it carries nothing to record: ```json title="Response 200" { "received": true } ``` A payload the driver rejects answers `400 Bad Request` with the same plain error body as the payment webhooks: ```json title="Response 400" { "error": "Invalid webhook payload." } ``` A driver that is not registered, not configured or without webhook support, such as the bundled `manual` driver, answers `404` with a JSON:API error object: ```json title="Response 404" { "errors": [ { "status": "404", "code": "not_found", "title": "Not Found", "detail": "Not Found" } ] } ``` <Errors> | Status | Code | When | |--------|------|------| | 400 | None, plain body | The driver rejects the payload, such as a failed signature check | | 404 | `not_found` | The driver is not registered, not configured or does not support webhooks, as for every bundled driver | </Errors> </Endpoint> ## Errors [#errors] Errors use the JSON:API error object, with a `code` a client can branch on, described with every code in [Error codes](/3.x/store-api/errors#error-codes). Validation errors put the field in `source.pointer`, such as `/data/attributes/option_id`, even though request bodies are flat JSON. On top of `401 unauthenticated` for a token without the `store` ability, `404 not_found` for an unknown cart or a customer cart requested without its owner's token, and `429 rate_limited`, the checkout endpoints answer with these codes: | Endpoint | Codes | |----------|-------| | List the shipping options | `http_error` (422, no zone) | | Set the shipping method | `required`, `shipping_option_unavailable`, `shipping_provider_unavailable`, `http_error`, `cart_completed`, `payment_session_collected`, `payment_session_in_progress`, `payment_provider_unavailable` | | List the payment methods | None beyond the common ones | | Set the payment method | `required`, `exists`, `payment_method_unavailable`, `cart_completed`, `payment_session_collected`, `payment_session_in_progress`, `payment_provider_unavailable` | | Open the payment session | The codes of [When the session cannot open](#when-the-session-cannot-open) | | Complete the cart | The codes of [When the order cannot be placed](#when-the-order-cannot-be-placed) | ## Next Steps [#next-steps] The cart is now an order. The orders guide reads it back for the confirmation page and lists the orders of a customer, and the customers guide covers accounts and the transfer of a guest cart. <Cards> <Card title="Orders" href="/3.x/store-api/orders"> Order lookup, order history, shipments and downloads. </Card> <Card title="Customers" href="/3.x/store-api/customers"> Customer accounts and the transfer of a guest cart. </Card> </Cards> # Customers (/3.x/store-api/customers) The account area of a storefront shows who is signed in, lets the customer edit their details, keeps the addresses they ship to, and carries the cart they built as a guest into their account. The endpoints of this page serve that area. The order history and the downloads of an account are on the [Orders](/3.x/store-api/orders) guide. Every endpoint of this page needs the bearer token of a signed-in customer, the one [Logging in](/3.x/store-api/authentication#logging-in) and [Registering a customer](/3.x/store-api/authentication#registering-a-customer) return. The token identifies the customer, so no URL carries a customer ID: `/customers/me` always means the owner of the token. The [Customers](/3.x/customers) page covers the customer model behind these endpoints. ## Endpoints [#endpoints] These routes sit in the authenticated route group. A request without a token, with an expired or revoked token, or with a token that was not issued for the store answers `401`. <Routes> <Route method="GET" path="/store/customers/me" href="#get-store-customers-me">Read the profile</Route> <Route method="PATCH" path="/store/customers/me" href="#patch-store-customers-me">Update the profile</Route> <Route method="POST" path="/store/customers/me/avatar" href="#post-store-customers-me-avatar">Upload a profile picture</Route> <Route method="DELETE" path="/store/customers/me/avatar" href="#delete-store-customers-me-avatar">Remove the profile picture</Route> <Route method="GET" path="/store/customers/me/addresses" href="#get-store-customers-me-addresses">List the saved addresses</Route> <Route method="POST" path="/store/customers/me/addresses" href="#post-store-customers-me-addresses">Save an address</Route> <Route method="PATCH" path="/store/customers/me/addresses/{addressId}" href="#patch-store-customers-me-addresses-addressid">Update an address</Route> <Route method="DELETE" path="/store/customers/me/addresses/{addressId}" href="#delete-store-customers-me-addresses-addressid">Delete an address</Route> <Route method="POST" path="/store/carts/{cartId}/transfer" href="#post-store-carts-cartid-transfer">Attach a guest cart to the customer</Route> </Routes> Request bodies are flat JSON objects, such as `{"opt_in": true}`. The profile picture is the only multipart upload. A missing or rejected token answers `401` with the `unauthenticated` code: ```json title="Response 401" { "errors": [ { "status": "401", "code": "unauthenticated", "title": "Unauthorized", "detail": "Unauthenticated." } ] } ``` The storefront then drops the stored token and sends the customer to the sign-in form. ## Reading the Profile [#reading-the-profile] The storefront reads the profile to greet the customer, fill the account form and show the profile picture. It is also the cheapest way to check that a stored token still works when the storefront starts. <Endpoint id="get-store-customers-me" method="GET" path="/store/customers/me" auth="customer"> <Params title="Query parameters"> <Field name="fields[customers]" type="string"> Comma-separated attributes to return, such as `first_name,last_name`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request reads the profile of the customer the token belongs to: ```bash title="Request" curl http://localhost:8000/store/customers/me \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `200 OK` with a `customers` resource: ```json title="Response 200" { "data": { "id": "01JD9B2K7X4N8R3T6V1Y5Z0QWE", "type": "customers", "attributes": { "first_name": "Camille", "last_name": "Martin", "email": "camille.martin@example.com", "avatar": "http://localhost:8000/storage/avatars/u8jzPde0IgxLd6GncfBAepfJBd0Kh8oOOL8dKLzd.jpg", "avatar_type": "storage", "phone_number": "+33 6 12 34 56 78", "gender": "female", "birth_date": "1992-04-18", "opt_in": true, "email_verified": true, "created_at": "2026-09-03T14:20:11+00:00" } } } ``` <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | </Errors> </Endpoint> <Attributes title="customers attributes"> <Field name="first_name" type="string, null"> First name. </Field> <Field name="last_name" type="string"> Last name. </Field> <Field name="email" type="string"> Email the customer signs in with. </Field> <Field name="avatar" type="string"> URL of the profile picture: the uploaded file, or a generated picture when there is none. </Field> <Field name="avatar_type" type="string"> `storage` when the customer uploaded a picture, `avatar_ui` for the generated one. </Field> <Field name="phone_number" type="string, null"> Phone number, as the customer typed it. </Field> <Field name="gender" type="string, null"> `female` or `male`. </Field> <Field name="birth_date" type="string, null"> Date of birth, `YYYY-MM-DD`. </Field> <Field name="opt_in" type="boolean"> Whether the customer accepts marketing emails. </Field> <Field name="email_verified" type="boolean"> Whether the customer confirmed their email address. </Field> <Field name="created_at" type="string"> When the account was created, ISO 8601. </Field> </Attributes> The customer `id` is a ULID, like the IDs of carts, orders and addresses. ## Updating the Profile [#updating-the-profile] The account form saves the fields the customer changed. Send only those fields: a field left out of the body keeps its value. <Endpoint id="patch-store-customers-me" method="PATCH" path="/store/customers/me" auth="customer"> <Params title="Query parameters"> <Field name="fields[customers]" type="string"> Comma-separated attributes to return, such as `first_name,last_name`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> <Params title="Body"> <Field name="first_name" type="string, null"> First name, up to 255 characters. `null` clears it. </Field> <Field name="last_name" type="string"> Last name, up to 255 characters. It cannot be cleared. </Field> <Field name="phone_number" type="string, null"> Phone number, up to 255 characters. `null` clears it. </Field> <Field name="birth_date" type="string, null"> A date before today, such as `1992-04-18`. `null` clears it. </Field> <Field name="gender" type="string, null"> `female` or `male`. `null` clears it. </Field> <Field name="opt_in" type="boolean"> Whether the customer accepts marketing emails. </Field> </Params> The email address is not part of this endpoint. A body that carries `email` gets no error, and the email stays the same. ```bash title="Request" curl -X PATCH http://localhost:8000/store/customers/me \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" \ -H "Content-Type: application/json" \ -d '{"phone_number": "+33 7 98 76 54 32", "opt_in": false}' ``` The API answers `200 OK` with the whole profile, in the shape of [Reading the profile](#reading-the-profile), so the storefront re-renders the form from the response. A value that fails validation answers `422`, with one error per field. The `code` is the name of the rule that failed, and the pointer names the field: ```json title="Response 422" { "errors": [ { "status": "422", "code": "before", "title": "Unprocessable Content", "detail": "The birth date field must be a date before today.", "source": { "pointer": "/data/attributes/birth_date" } } ] } ``` The [Errors](/3.x/store-api/errors) guide lists every error code. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 422 | Rule name, such as `before` | A field fails validation, the pointer names it | </Errors> </Endpoint> ## Profile Picture [#profile-picture] A customer who uploads a picture sees it in the account area. Without one, `avatar` points to a generated picture, so the storefront always has an image to show. <Endpoint id="post-store-customers-me-avatar" method="POST" path="/store/customers/me/avatar" auth="customer"> <Params title="Query parameters"> <Field name="fields[customers]" type="string"> Comma-separated attributes to return, such as `first_name,last_name`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> <Params title="Body"> <Field name="avatar" type="file" required> The image, sent as `multipart/form-data`, 1,024 KB at most. </Field> </Params> The upload is a multipart request with the image in the `avatar` field. The file must be an image of 1,024 KB at most. ```bash title="Request" curl -X POST http://localhost:8000/store/customers/me/avatar \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" \ -F "avatar=@camille.jpg" ``` The API answers `200 OK` with the profile. `avatar_type` is now `storage`, and `avatar` is the URL of the stored file: ```json title="Response 200" { "data": { "id": "01JD9B2K7X4N8R3T6V1Y5Z0QWE", "type": "customers", "attributes": { "first_name": "Camille", "last_name": "Martin", "email": "camille.martin@example.com", "avatar": "http://localhost:8000/storage/avatars/kD3f9QmZ7xWb2LpR8sTn4VhY6cJe1AuG0oNi5MrK.jpg", "avatar_type": "storage", "phone_number": "+33 7 98 76 54 32", "gender": "female", "birth_date": "1992-04-18", "opt_in": false, "email_verified": true, "created_at": "2026-09-03T14:20:11+00:00" } } } ``` The file goes to the `avatars` folder of the media disk, the `shopper.media.storage.disk_name` setting described in [Media](/3.x/media#storage-disk). A new upload replaces the previous picture and deletes its file. A file that is not an image or is larger than 1,024 KB answers `422` with a pointer on `/data/attributes/avatar`. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 422 | `required` | The request has no file in `avatar` | | 422 | `image_file` | The file is not an image or is larger than 1,024 KB | </Errors> </Endpoint> <Endpoint id="delete-store-customers-me-avatar" method="DELETE" path="/store/customers/me/avatar" auth="customer"> <Params title="Query parameters"> <Field name="fields[customers]" type="string"> Comma-separated attributes to return, such as `first_name,last_name`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> To go back to the generated picture, delete the upload: ```bash title="Request" curl -X DELETE http://localhost:8000/store/customers/me/avatar \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `200 OK` with the profile, where `avatar_type` is `avatar_ui` and `avatar` is the generated URL again. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | </Errors> </Endpoint> ## Addresses [#addresses] Saved addresses spare a returning customer from typing their address at every checkout. The account area lists them, and the checkout offers them as choices. Each address is either a shipping or a billing address, and the customer can mark one address as the default for each. Every address request is scoped to the owner of the token. An address ID that belongs to another customer answers `404 not_found`, the same answer as an ID that does not exist. ### Listing Addresses [#listing-addresses] The list returns every address of the customer, newest first, in one response. It is not paginated. <Endpoint id="get-store-customers-me-addresses" method="GET" path="/store/customers/me/addresses" auth="customer"> <Params title="Query parameters"> <Field name="include" type="string"> `country` adds the country of each address, a `countries` resource described in [Countries](/3.x/store-api/store#countries). </Field> <Field name="fields[addresses]" type="string"> Comma-separated attributes to return, such as `street_address,city,postal_code`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request lists the addresses of the customer: ```bash title="Request" curl http://localhost:8000/store/customers/me/addresses \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `200 OK` with an array of `addresses` resources: ```json title="Response 200" { "data": [ { "id": "01JZ8KA2B3C4D5E6F7G8H9JKMN", "type": "addresses", "attributes": { "first_name": "Camille", "last_name": "Martin", "company_name": null, "street_address": "18 Rue de la Roquette", "street_address_plus": "Apartment 4B", "postal_code": "75011", "city": "Paris", "state": null, "country_code": "FR", "type": "shipping", "phone_number": "+33 6 12 34 56 78", "shipping_default": true, "billing_default": false, "created_at": "2026-11-02T18:05:43+00:00", "updated_at": "2026-11-02T18:05:43+00:00" } } ] } ``` `country_code` is the two-letter ISO code of the country, and `type` is `shipping` or `billing`. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | </Errors> </Endpoint> ### Saving an Address [#saving-an-address] The storefront saves an address from the account area, or after a checkout when the customer ticks a "save this address" box. <Endpoint id="post-store-customers-me-addresses" method="POST" path="/store/customers/me/addresses" auth="customer"> <Params title="Query parameters"> <Field name="include" type="string"> `country` adds the country of the address, a `countries` resource described in [Countries](/3.x/store-api/store#countries). </Field> <Field name="fields[addresses]" type="string"> Comma-separated attributes to return, such as `street_address,city,postal_code`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> <Params title="Body"> <Field name="first_name" type="string" required> First name, up to 255 characters. </Field> <Field name="last_name" type="string" required> Last name, up to 255 characters. </Field> <Field name="company_name" type="string, null"> Company, up to 255 characters. </Field> <Field name="street_address" type="string" required> Street and number, up to 255 characters. </Field> <Field name="street_address_plus" type="string, null"> Second address line, such as an apartment or a floor, up to 255 characters. </Field> <Field name="postal_code" type="string" required> Postal code, up to 255 characters. </Field> <Field name="city" type="string" required> City, up to 255 characters. </Field> <Field name="state" type="string, null"> State or region, such as `NY`, up to 255 characters. </Field> <Field name="country_code" type="string" required> Two-letter ISO code of the country, such as `FR` or `US`. Upper-cased before validation. </Field> <Field name="type" type="string" required> `shipping` or `billing`. </Field> <Field name="phone_number" type="string, null"> Phone number, up to 255 characters. </Field> <Field name="shipping_default" type="boolean"> `true` makes this address the default shipping address of the customer. </Field> <Field name="billing_default" type="boolean"> `true` makes this address the default billing address of the customer. </Field> </Params> This request saves an address in Paris and makes it the default shipping address of the customer: ```bash title="Request" curl -X POST http://localhost:8000/store/customers/me/addresses \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" \ -H "Content-Type: application/json" \ -d '{ "first_name": "Camille", "last_name": "Martin", "street_address": "18 Rue de la Roquette", "street_address_plus": "Apartment 4B", "postal_code": "75011", "city": "Paris", "country_code": "fr", "type": "shipping", "phone_number": "+33 6 12 34 56 78", "shipping_default": true, "billing_default": false }' ``` The API answers `201 Created` with the new address, in the shape of the list above. A flag left out of the body is stored as `false`, but the `201` response shows it as `null`; the list and the update return `false`. An unknown country code answers `422` with the `exists` code on `/data/attributes/country_code`. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 422 | `exists` | `country_code` is not a known country | | 422 | Rule name, such as `required` | Another field fails validation | </Errors> </Endpoint> ### Default Addresses [#default-addresses] A customer has at most one default shipping address and one default billing address. Setting `shipping_default` or `billing_default` to `true` on an address, when saving or updating it, removes that flag from the other addresses of the customer, so the checkout can pick the default without asking. The values `1` and `"1"` count as `true` and move the default the same way. ### Updating and Deleting an Address [#updating-and-deleting-an-address] <Endpoint id="patch-store-customers-me-addresses-addressid" method="PATCH" path="/store/customers/me/addresses/{addressId}" auth="customer"> <Params title="Path parameters"> <Field name="addressId" type="string" required> The `id` of the `addresses` resource. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `country` adds the country of the address, a `countries` resource described in [Countries](/3.x/store-api/store#countries). </Field> <Field name="fields[addresses]" type="string"> Comma-separated attributes to return, such as `street_address,city,postal_code`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> <Params title="Body"> <Field name="first_name" type="string"> First name, up to 255 characters. </Field> <Field name="last_name" type="string"> Last name, up to 255 characters. </Field> <Field name="company_name" type="string, null"> Company, up to 255 characters. </Field> <Field name="street_address" type="string"> Street and number, up to 255 characters. </Field> <Field name="street_address_plus" type="string, null"> Second address line, such as an apartment or a floor, up to 255 characters. </Field> <Field name="postal_code" type="string"> Postal code, up to 255 characters. </Field> <Field name="city" type="string"> City, up to 255 characters. </Field> <Field name="state" type="string, null"> State or region, such as `NY`, up to 255 characters. </Field> <Field name="country_code" type="string"> Two-letter ISO code of the country, such as `FR` or `US`. Upper-cased before validation. </Field> <Field name="type" type="string"> `shipping` or `billing`. </Field> <Field name="phone_number" type="string, null"> Phone number, up to 255 characters. </Field> <Field name="shipping_default" type="boolean"> `true` makes this address the default shipping address of the customer. </Field> <Field name="billing_default" type="boolean"> `true` makes this address the default billing address of the customer. </Field> </Params> An update takes the same fields as [Saving an address](#saving-an-address), all optional. Send only what changed: ```bash title="Request" curl -X PATCH http://localhost:8000/store/customers/me/addresses/01JZ8KB7C8D9E0F1G2H3J4K5M6 \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" \ -H "Content-Type: application/json" \ -d '{"billing_default": true}' ``` The API answers `200 OK` with the updated address. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 404 | `not_found` | The customer has no address with this ID | | 422 | `exists` | `country_code` is not a known country | | 422 | Rule name, such as `boolean` | Another field fails validation | </Errors> </Endpoint> <Endpoint id="delete-store-customers-me-addresses-addressid" method="DELETE" path="/store/customers/me/addresses/{addressId}" auth="customer"> <Params title="Path parameters"> <Field name="addressId" type="string" required> The `id` of the `addresses` resource. </Field> </Params> A delete removes the address for good: ```bash title="Request" curl -X DELETE http://localhost:8000/store/customers/me/addresses/01JZ8KB7C8D9E0F1G2H3J4K5M6 \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `204 No Content`, with no body. Deleting a default address leaves the customer without a default of that kind until another address gets the flag. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 404 | `not_found` | The customer has no address with this ID | </Errors> </Endpoint> ### Using a Saved Address at Checkout [#using-a-saved-address-at-checkout] The cart does not take an address ID: the [Cart](/3.x/store-api/cart) guide sets addresses on a cart as objects. To ship to a saved address, copy its fields into the cart address. Most names are the same; these differ: | Saved address | Cart address | |---------------|--------------| | `company_name` | `company` | | `street_address` | `address_1` | | `street_address_plus` | `address_2` | | `phone_number` | `phone` | `first_name`, `last_name`, `city`, `state`, `postal_code` and `country_code` keep their names. ## Transferring a Guest Cart [#transferring-a-guest-cart] Most visitors fill a cart before they sign in. When they sign in at checkout, the cart they built must follow them into their account, and join the cart they may have left open on another device. The transfer does that: it attaches a guest cart to the signed-in customer and returns the cart the storefront uses from then on. The login and registration requests accept the guest cart ID as `cart_id` and run this same transfer, returning the resulting cart ID in `meta.cart_id`, as [Logging in](/3.x/store-api/authentication#logging-in) shows. The transfer endpoint is for a customer who is already signed in when the guest cart appears, such as a second tab or a token restored from storage. <Endpoint id="post-store-carts-cartid-transfer" method="POST" path="/store/carts/{cartId}/transfer" auth="customer" limit="checkout"> <Params title="Path parameters"> <Field name="cartId" type="string" required> The ID of the guest cart. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> Related resources to return with the cart, listed in [Reading a Cart](/3.x/store-api/cart#reading-a-cart). </Field> <Field name="fields[carts]" type="string"> Comma-separated attributes to return, such as `lines_count,total`. See [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request attaches a guest cart to the customer the token belongs to: ```bash title="Request" curl -X POST http://localhost:8000/store/carts/01JZ9A1B2C3D4E5F6G7H8J9K0M/transfer \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 403 | `forbidden` | The cart belongs to another customer | | 404 | `not_found` | No cart has this ID | | 409 | `cart_completed` | The cart is already an order | | 409 | `payment_session_collected` | The guest cart is already paid at the payment provider | | 409 | `payment_session_in_progress` | Another request is opening a payment session on the cart, retry after `Retry-After` | | 503 | `payment_provider_unavailable` | The payment provider did not answer while the transfer released the payment session, retry after `Retry-After` | | 400 | `bad_request` | An `include` path outside the cart list | </Errors> </Endpoint> ### What the Transfer Does [#what-the-transfer-does] The result depends on the guest cart and on the open carts the customer already has: | Situation | Result | Cart ID to keep | |-----------|--------|-----------------| | The cart already belongs to this customer | Nothing changes, so a retry with the returned ID is safe. | The same ID | | The customer has no open cart | The guest cart becomes a cart of the customer. | The guest cart ID | | The customer has an open cart | The guest lines move into the customer's latest open cart, and the guest cart is deleted. | The customer cart ID | | The guest cart or the customer cart has a payment session open | No merge: the guest cart becomes a cart of the customer, next to the other one. | The guest cart ID | When the carts merge, a product present in both carts becomes one line whose quantity is the sum of both, and the other guest lines move as they are. Promotion codes of the guest cart are added to the customer cart. The shipping option of the customer cart is cleared, because the parcel changed, and the customer picks one again at checkout. The email and addresses of the guest cart are not carried over: the customer cart keeps its own. A merge that cannot be done falls back to the claim, and the guest cart becomes a cart of the customer, unchanged. That happens when a line carries a negotiated price that locks its quantity, when the same product carries different metadata in the two carts, or when a product has no price in the currency of the customer cart. Unless it has a payment session open, the cart that results is priced again from the catalog, and its promotion codes are checked again: a code the customer can no longer use, such as one limited to one use per customer that they already used, is removed. The [Cart](/3.x/cart) page covers how prices and promotions apply. ### The Response [#the-response] The API answers `200 OK` with the resulting cart, in the shape the [Cart](/3.x/store-api/cart) guide describes. `meta.price_changes` lists the lines whose unit price changed in the transfer, with the price before and after, in cents: ```json title="Response 200" { "data": { "id": "01JZ7Q4R5S6T7V8W9X0Y1Z2A3B", "type": "carts", "attributes": { "currency_code": "EUR", "email": null, "promotions": [], "completed_at": null, "metadata": null, "lines_count": 2, "lines_quantity": 3, "subtotal": 25700, "discount_total": 0, "tax_total": 0, "shipping_total": 0, "total": 25700, "tax_inclusive": false, "shipping_option_id": null, "created_at": "2026-11-10T16:42:08+00:00", "updated_at": "2026-11-19T10:21:37+00:00" } }, "meta": { "price_changes": [ { "line": "01JZ9A2C3D4E5F6G7H8J9K0M1N", "from": 12900, "to": 11900 } ] } } ``` Here the guest cart `01JZ9A1B2C3D4E5F6G7H8J9K0M` was merged into the customer cart `01JZ7Q4R5S6T7V8W9X0Y1Z2A3B`. The pair of Classic Leather Sneakers the customer had left in that cart now costs €119.00 instead of €129.00, and the storefront shows that change before the customer pays. `price_changes` is empty when no price moved, and it skips lines that changed currency in a merge. Store the `id` of the response as the cart ID and forget the guest cart ID: after a merge, the guest cart no longer exists and its ID answers `404`. ### Errors [#errors] The transfer shares the checkout rate limit with the cart endpoints that add things, described in [Rate limits](/3.x/store-api#rate-limits). | Status | Code | When | What to do | |--------|------|------|------------| | `401` | `unauthenticated` | The request has no valid customer token. | Sign the customer in, then transfer. | | `403` | `forbidden` | The cart belongs to another customer. | Drop the stored cart ID and use the customer's own cart. | | `404` | `not_found` | No cart has this ID. | Drop the stored cart ID. | | `409` | `cart_completed` | The cart is already an order. | Drop the stored cart ID. | | `409` | `payment_session_collected` | The guest cart is already paid at the payment provider, so its payment session cannot be released. | Complete the checkout of that cart to place the order. | | `409` | `payment_session_in_progress` | Another request is opening a payment session on the cart. The response carries `Retry-After: 3`. | Retry after 3 seconds. | | `503` | `payment_provider_unavailable` | The payment provider did not answer while the transfer released the payment session of the cart. | Retry later. | ## Next Steps [#next-steps] With the customer signed in and their cart attached, the storefront moves on to the checkout, then to the orders of the account. <Cards> <Card title="Orders" href="/3.x/store-api/orders"> Show the order history of the customer, track shipments and download purchased files. </Card> <Card title="Checkout" href="/3.x/store-api/checkout"> Turn the cart into an order with a shipping option and a payment. </Card> <Card title="Cart" href="/3.x/store-api/cart"> Create carts, add lines and set addresses and promotion codes. </Card> </Cards> # Errors (/3.x/store-api/errors) Every error of the Store API, from a missing product to a payment provider outage, answers with an `errors` array and no `data`. Each error carries a `code` that does not change with the language of the request: branch on `code` in your storefront, and show `detail` to the customer. ## Error Object [#error-object] A request for a product that does not exist shows the shape that every error shares: ```bash title="Request" curl "http://localhost:8000/store/products/classic-leather-boots" \ -H "Accept: application/vnd.api+json" ``` The API answers `404 Not Found`: ```json title="Response" { "errors": [ { "status": "404", "code": "not_found", "title": "Not Found", "detail": "Not Found" } ] } ``` Each error object has these members: | Member | Type | Description | |--------|------|-------------| | `status` | string | The HTTP status code, as a string. Every error of one response has the status of the response. | | `code` | string | A code from [Error Codes](#error-codes), or for a validation error the name of the rule that failed. | | `title` | string | The HTTP status text, such as `Not Found`, the same for every error with that status. | | `detail` | string | A message for the customer, in the language of the request. | | `source.pointer` | string | Validation errors only: the field the error is about, as described in [Validation Errors](#validation-errors). | | `meta` | object | Only on the codes that carry extra values, such as `quantity_rule_violated`. | The API answers in this format for every path under the `/store` prefix, with `Content-Type: application/vnd.api+json`. A URL that matches no route answers `404 not_found` with a `detail` such as `The route store/wishlists could not be found.`, and a route called with the wrong HTTP method answers `405 method_not_allowed` with a `detail` that lists the methods the route accepts. An unexpected exception answers `500 Internal Server Error` with the `server_error` code and `Internal Server Error` as `detail`. The body never carries the exception message or a stack trace, even when `APP_DEBUG` is on: read the cause in the log of the Laravel application, `storage/logs/laravel.log` by default. The `detail` follows the `Accept-Language` header, as described in [Language](/3.x/store-api#language). Messages that come from Laravel itself, such as validation messages, the login error and the password reset error, follow the language files of your application. ## Validation Errors [#validation-errors] A request whose body or query parameters fail validation answers `422 Unprocessable Content` with one error object per message. Two fields that fail give two objects, and a field that fails two rules gives two objects with the same pointer. A login without a body fails on both fields: ```bash title="Request" curl -X POST "http://localhost:8000/store/auth/login" \ -H "Accept: application/vnd.api+json" \ -H "Content-Type: application/json" \ -d '{}' ``` The API answers `422 Unprocessable Content`: ```json title="Response" { "errors": [ { "status": "422", "code": "required", "title": "Unprocessable Content", "detail": "The email field is required.", "source": { "pointer": "/data/attributes/email" } }, { "status": "422", "code": "required", "title": "Unprocessable Content", "detail": "The password field is required.", "source": { "pointer": "/data/attributes/password" } } ] } ``` The `code` of a validation error is one of these: - The name of the Laravel rule that failed, in snake case: `required`, `email`, `unique`, `max`. A rule object gives the snake case of its class name, such as `image_file` for `File::image()`. - A code from [Error Codes](#error-codes) when Shopper raises the error itself, such as `credentials_invalid` or `stock_insufficient`. - `invalid` when no rule stands behind the message, such as an error your own route raises with `ValidationException::withMessages()`. ### Reading the Pointer [#reading-the-pointer] Request bodies are flat JSON, while `source.pointer` follows the JSON:API form `/data/attributes/{field}`. Remove the `/data/attributes/` prefix to get the name of the field. A nested field keeps its path with `/` between the segments, so an error on `lines.0.quantity` points at `/data/attributes/lines/0/quantity`. Errors on query parameters use the same form: an unknown currency in `filter[currency]` points at `/data/attributes/filter/currency`, and a forbidden include at `/data/attributes/include`. A few codes point at a name that is not a field of the request. On `POST /carts/{cartId}/complete` and `POST /carts/{cartId}/payment-session`, which take no field, the pointer names the part of the cart that blocks the checkout: `cart`, `email`, `promotion`, `shipping_method`, `payment_method` or `payment_session`. Show these errors at the top of the checkout page instead of next to a field. This function groups the messages of a validation error by field, ready for a form: ```ts title="lib/store-api-errors.ts" type StoreApiError = { status: string; code: string; title: string; detail: string; source?: { pointer: string }; meta?: Record<string, unknown>; }; export function fieldErrors(errors: StoreApiError[]): Record<string, string[]> { const fields: Record<string, string[]> = {}; for (const error of errors) { if (!error.source) { continue; } const field = error.source.pointer.replace('/data/attributes/', '').replaceAll('/', '.'); (fields[field] ??= []).push(error.detail); } return fields; } ``` ### Errors With Meta [#errors-with-meta] Some errors carry a `meta` object with the values a storefront needs to fix the request. A quantity that breaks a quantity rule of its price answers `quantity_rule_violated` with the rule and the quantity that was sent: ```json title="Response" { "errors": [ { "status": "422", "code": "quantity_rule_violated", "title": "Unprocessable Content", "detail": "This item must be ordered in multiples of 2.", "source": { "pointer": "/data/attributes/quantity" }, "meta": { "purchasable_id": "01JD8YQ3H5K7M9P2R4T6V8X0Z1", "quantity": 3, "minimum": 2, "maximum": null, "increment": 2 } } ] } ``` `minimum`, `maximum` and `increment` are `null` when the rule does not set them. Use them to correct the quantity selector, as described in [Cart](/3.x/store-api/cart). ## Rate Limit Errors [#rate-limit-errors] A client that goes past a rate limiter, described in [Rate Limits](/3.x/store-api#rate-limits), gets `429 Too Many Requests` with the `rate_limited` code until the limiter resets: ```json title="Response" { "errors": [ { "status": "429", "code": "rate_limited", "title": "Too Many Requests", "detail": "Too Many Attempts." } ] } ``` The response carries these headers: | Header | Value | |--------|-------| | `X-RateLimit-Limit` | The number of requests the limiter allows per minute, such as `30` for `shopper-api-checkout` | | `X-RateLimit-Remaining` | `0` | | `Retry-After` | The seconds to wait before the next request, such as `42` | | `X-RateLimit-Reset` | The Unix timestamp at which the limiter accepts requests again, such as `1795083912` | Wait for `Retry-After` before sending the request again. A login refused after too many failures, described in [Failed Logins](/3.x/store-api/authentication#failed-logins), also answers `429` with the `rate_limited` code, and a `detail` that gives the wait, such as `Too many login attempts. Please try again in 59 seconds.`. Its `Retry-After` header counts down the lockout of that email. The `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers of that response describe the `shopper-api-auth` limiter of the route, not the lockout, so rely on `Retry-After` alone. ## Error Codes [#error-codes] The codes below are every code the API sets itself, grouped by area. The Pointer column gives the end of `source.pointer`, after `/data/attributes/`, for the codes that answer as validation errors. Four codes carry a `Retry-After` header and can succeed when the same request is sent again later: `rate_limited`, `payment_session_in_progress`, `shipping_provider_unavailable` and `payment_provider_unavailable`. Any other error answers the same until the request or the cart changes. ### General Codes [#general-codes] These codes come from the HTTP status of the response, so any route can answer them: | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `bad_request` | 400 | | An `include`, `filter` or `sort` name outside the allowlist of the endpoint. The `detail` lists the accepted names | Fix the query, see [Allowlists](/3.x/store-api/json-api#allowlists) | | `unauthenticated` | 401 | | A route of the authenticated group called without a token, with an expired or revoked token, or with a token that lacks the `store` ability | Drop the stored token and send the customer to the login page, see [Using the Token](/3.x/store-api/authentication#using-the-token) | | `forbidden` | 403 | | A download link asked for a file of an order that is not paid yet, or a cart transfer on a cart that belongs to another customer | Offer the download once the order is paid. For a transfer, create a new cart | | `not_found` | 404 | | No record with this ID or slug for the request, or no route for the URL. A disabled or unpublished record, and a cart or an order of another customer, count as missing | Check the ID. For a cart the customer owned, see [Using the Token](/3.x/store-api/authentication#using-the-token) | | `method_not_allowed` | 405 | | The route does not accept this HTTP method. The `detail` lists the methods it accepts | Fix the method | | `conflict` | 409 | | `POST /carts/{cartId}/payment-session` on a cart that is already an order | Read the order instead of opening a session | | `invalid` | 422 | Any field | A validation error with no rule behind it | Show the `detail` | | `rate_limited` | 429 | | Too many requests or too many failed logins, see [Rate Limit Errors](#rate-limit-errors) | Wait for `Retry-After` | | `server_error` | 500 or higher | | An unexpected exception on the server | Retry later. The cause is in the application log | | `http_error` | Any other | | Any other status, such as the `422` of `GET /carts/{cartId}/shipping-options` on a cart without a zone, which has no `source` | For a cart without a zone, set its `zone_code`, see [Cart](/3.x/store-api/cart) | ### Authentication [#authentication] These codes come from the login and password reset endpoints described in [Authentication](/3.x/store-api/authentication): | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `credentials_invalid` | 422 | `email` | No customer has this email, or the password is wrong | Show one message for both cases. After 5 failures, the login locks for a minute | | `reset_token_invalid` | 422 | `email` | The reset token expired, was already used, or belongs to another email | Offer to send a new reset link | ### Query Parameters [#query-parameters] These codes come from the query parameters described in [JSON:API Conventions](/3.x/store-api/json-api): | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `include_not_allowed` | 422 | `include` | An include other than `items` on `GET /orders/{orderId}`, the order confirmation lookup | Ask for `items` only, or read the order from the customer's account, see [Orders](/3.x/store-api/orders) | | `filter_too_wide` | 422 | `filter/{name}` | A filter with more than 50 comma-separated values | Split the request | | `currency_required` | 422 | `sort` or `filter/price_min` | `GET /products` sorted by price or filtered by `price_min` or `price_max` when no currency applies: no `filter[currency]`, no zone, and no default currency on the shop | Send `filter[currency]` or the `X-Shopper-Zone` header | | `currency_unknown` | 422 | `filter/currency` | `filter[currency]` names a currency that does not exist or is disabled | Send a code listed by `GET /currencies` | ### Cart Lines and Prices [#cart-lines-and-prices] These codes come from adding and updating lines, changing the currency of a cart, and checking the cart out: | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `purchasable_unavailable` | 422 | `purchasable_id` | No product or variant with this ID can be bought: it does not exist, its product is not published, or the product is external | Refresh the product page | | `variant_required` | 422 | `purchasable_id` | The ID is the one of a product sold through its variants | Send the ID of a variant, with `purchasable_type` set to `variant` | | `price_missing` | 422 | `purchasable_id`, `currency_code` or `cart` | The product has no price in the cart currency: when the line is added, when the cart moves to another currency, or at checkout | Remove the line, or keep the cart in its currency | | `price_changed` | 422 | `cart` | At checkout or when a payment session opens, the price of a line went up since it was added. The cart already holds the new prices; a lower price is applied without an error | Show the new total and ask the customer to confirm | | `stock_insufficient` | 422 | `quantity` or `cart` | Not enough stock for the quantity, when the line changes or at checkout | Lower the quantity or remove the line | | `quantity_rule_violated` | 422 | `quantity` or `cart` | The quantity breaks the minimum, maximum or increment of its price. The rule is in `meta`, see [Errors With Meta](#errors-with-meta) | Correct the quantity | ### Cart State [#cart-state] These codes come from the state of the cart as a whole: | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `cart_empty` | 422 | `cart` | Checkout of a cart without lines | Add a line | | `cart_completed` | 409 | | A change to a cart that is already an order | Read the order, and start a new cart | | `cart_line_locked` | 409 | | A change to a line whose price the merchant set by hand: a new quantity, the same product added again, or a new currency for the cart | Leave the line as it is, or remove it | | `cart_line_metadata_conflict` | 422 | `metadata` | The product is already in the cart with other `metadata` | Update that line, or remove it first | | `cart_nothing_to_collect` | 422 | `cart` | A payment session on a cart whose total is zero | Set a manual payment method, which needs no session, and complete the cart | | `email_required` | 422 | `email` | Checkout of a guest cart without an email. A customer's cart uses the email of the account | Set the email on the cart | ### Promotions [#promotions] These codes come from applying a promotion code and from checking out a cart that has promotions: | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `promotion_not_applicable` | 422 | `code` or `promotion` | The code does not exist, is not active or does not apply to the cart. At checkout, a promotion of the cart that no longer applies. The `detail` never says why, so that codes cannot be guessed | Show the `detail`. At checkout, show the new total | | `promotion_limit_reached` | 422 | `promotion` | At checkout, a promotion of the cart reached its usage limit | Show the new total | | `promotion_budget_reached` | 422 | `promotion` | At checkout, the campaign of a promotion spent its budget | Show the new total | When checkout fails on a promotion, the API cancels the payment session of the cart and computes its totals again before it answers: show the new total, then open a new payment session. ### Shipping [#shipping] These codes come from choosing a shipping option and from checking out a cart that has products to ship: | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `shipping_method_required` | 422 | `shipping_method` | Checkout or a payment session on a cart with products to ship and no shipping option | Set a shipping method | | `shipping_option_unavailable` | 422 | `option_id` or `shipping_method` | The option is not among the options quoted for the cart, or no longer is at checkout | List the shipping options again and choose another one | | `shipping_price_changed` | 422 | `shipping_method` | At checkout, the carrier quotes the chosen option higher than when it was set | Set the shipping method again to accept the new price | | `shipping_provider_unavailable` | 503 | | The carrier of the chosen option did not answer | Retry after `Retry-After` (5 seconds) | ### Payment [#payment] These codes come from choosing a payment method, opening a payment session and completing the cart, described in [Checkout](/3.x/store-api/checkout): | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `payment_method_required` | 422 | `payment_method` | Checkout or a payment session on a cart without a payment method | Set a payment method | | `payment_method_unavailable` | 422 | `payment_method_id` | The payment method is not offered for the cart | Choose a method listed by `GET /carts/{cartId}/payment-methods` | | `payment_method_not_configured` | 503 | | The driver of the payment method has no configuration on the server | Offer another payment method | | `payment_provider_unavailable` | 503 | | The payment provider did not answer when the session opened, or when a change to the cart had to cancel the open payment | Retry after `Retry-After` (5 seconds) | | `payment_session_in_progress` | 409 | | Another request holds the payment session of the cart, such as a second click on the pay button | Retry after `Retry-After` (3 seconds) | | `payment_session_collected` | 409 | | A change to the cart, or a new payment session, after the payment of the cart was collected | Complete the cart | | `payment_session_required` | 422 | `payment_session` | Checkout with a payment method that needs a session, before one was opened | Open a payment session | | `payment_session_mismatch` | 422 | `payment_session` | Checkout of a cart whose total changed since the payment session opened | Open a new payment session and pay again | | `payment_released` | 422 | `cart` | At checkout, a product ran out of stock after the payment was collected. The payment is refunded and the session cleared | Update the cart and pay again | ### Account [#account] This code comes from the customer account endpoints described in [Customers](/3.x/store-api/customers): | Code | Status | Pointer | When it happens | What to do | |------|--------|---------|-----------------|------------| | `avatar_invalid` | 422 | `avatar` | The avatar upload passed validation but holds no file | Send the image as a `multipart/form-data` part named `avatar` | ## Errors From Your Own Routes [#errors-from-your-own-routes] A route you add under the prefix, as described in [Adding Your Own Routes](/3.x/store-api#adding-your-own-routes), answers its errors in the same format. A failed `$request->validate()` gives one object per message with the rule as `code`, and `abort(403, 'This wishlist is private.')` gives `forbidden` with your message as `detail`. To answer with a code of the table, throw the exceptions the API uses: ```php title="app/Http/Controllers/Store/WishlistController.php" use Shopper\Http\Enum\ErrorCode; use Shopper\Http\Exceptions\ApiException; use Shopper\Http\Exceptions\ApiValidationException; throw new ApiException(409, ErrorCode::Conflict, 'This product is already in the wishlist.'); throw ApiValidationException::withCode(ErrorCode::PurchasableUnavailable, [ 'product_id' => 'This product cannot be added to a wishlist.', ]); ``` `ApiValidationException::withCode()` answers `422` with the field as pointer, and takes a `meta` array as its third argument. The codes come from the `ErrorCode` enum, so a storefront only ever meets the codes of this page. ## Next Steps [#next-steps] The cart and checkout guides show where each of these codes comes up in the storefront flow. <Cards> <Card title="Cart" href="/3.x/store-api/cart"> Add lines, apply promotions and handle the errors of each change. </Card> <Card title="Checkout" href="/3.x/store-api/checkout"> Choose shipping and payment, then complete the cart into an order. </Card> <Card title="JSON:API Conventions" href="/3.x/store-api/json-api"> The includes, filters, sorts and pagination that every endpoint reads. </Card> </Cards> # Store API (/3.x/store-api) The Store API is the HTTP interface of Shopper for storefronts that run outside your Laravel application: a Next.js or Nuxt site, a mobile app, a kiosk. It serves the catalog, the cart and checkout, customer accounts and orders as [JSON:API](https://jsonapi.org) documents. It runs inside the same Laravel application as the admin panel and reads the same database, so a product published in the admin panel is on the API at once. A storefront rendered by your Laravel application itself, with Blade, Livewire or Inertia, reads the Shopper models directly and does not need the API. The [Storefront](/3.x/storefront) page compares both approaches. ## Installation [#installation] The API ships in its own Composer package, `shopper/api`, which needs an installed Shopper application. Follow the [Installation](/3.x/installation) guide first, then add the package and run its installer: ```bash composer require shopper/api:"^3.0" php artisan shopper:api:install ``` The installer runs these steps: 1. Publishes the Laravel Sanctum migration, which creates the `personal_access_tokens` table that stores the customer tokens. 2. Publishes the Shopper configuration files, among them `config/shopper/api.php` and `config/shopper/http.php`. A file that already exists is kept as it is. 3. Offers to add Sanctum's `HasApiTokens` trait to the user model set in `auth.providers.users.model`. When you answer no, or when the file is not writable, it prints the line to add instead. 4. Warns when the model does not use the `InteractsWithShopper` trait, which the customer endpoints need. 5. Asks whether to run the migrations. Once installed, the user model carries both traits: ```php title="app/Models/User.php" use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; use Shopper\Models\Contracts\ShopperUser; use Shopper\Traits\InteractsWithShopper; class User extends Authenticatable implements ShopperUser { use HasApiTokens; use InteractsWithShopper; use Notifiable; } ``` The routes register themselves when the package boots, so there is nothing to add to your route files. The package also schedules `sanctum:prune-expired --hours=24` once a day to delete expired customer tokens, which only runs when the [scheduler runs](/3.x/installation#run-the-scheduler-and-a-queue-worker). The installer ends with a few next steps, among them the install command of the [JavaScript SDK](/3.x/sdk), `@shopperlabs/shopper-sdk`. The guides of this section use plain HTTP requests, so they apply to any client. ## Base URL [#base-url] Every Store API route sits under one path prefix, `store` by default. With `php artisan serve`, the base URL is: ``` http://localhost:8000/store ``` Set `SHOPPER_API_PREFIX` in your `.env` file to serve the API under another prefix, such as `api/store`. The `admin` prefix is reserved for a future admin API. The package appends `<prefix>/*` to the `paths` of `config/cors.php`, so a browser can call the API from the storefront domain; the allowed origins come from that same file. Every route under the prefix answers with `Content-Type: application/vnd.api+json`, errors included, as described on the [JSON:API Conventions](/3.x/store-api/json-api) and [Errors](/3.x/store-api/errors) pages. ## Route Groups [#route-groups] The routes fall into three groups. Each group is a Laravel middleware group, which decides who can call the route and which rate limit counts it. | Group | Middleware group | Who calls it | Routes | |-------|------------------|--------------|--------| | Public | `shopper:store` | Any visitor. A customer token is optional | `/settings`, `/legals`, the catalog, `/countries`, `/zones`, `/currencies`, `/auth/*`, `/carts/*`, `/orders/{orderId}`, `/shipments/{shipmentId}`, `/files/{fileId}` | | Authenticated | `shopper:store-auth` | A logged-in customer with a bearer token | `/auth/logout`, `/carts/{cartId}/transfer`, `/customers/me` and everything under it | | Webhooks | `shopper:store-webhook` | Payment and carrier providers | `/webhooks/{driver}`, `/webhooks/shipping/{driver}` | A route of the authenticated group answers `401 Unauthorized` without a valid token. The [Authentication](/3.x/store-api/authentication) guide covers the token. ### Adding Your Own Routes [#adding-your-own-routes] The `ShopperApi` facade registers routes in one of these groups, so they get the prefix, the rate limit, the zone, the channel and the error format of the built-in routes. Register them in the `then` callback of `withRouting`, which keeps them out of the `web` middleware group and its CSRF check: ```php title="bootstrap/app.php" use App\Http\Controllers\Store\StoreLocatorController; use App\Http\Controllers\Store\WishlistController; use Illuminate\Support\Facades\Route; use Shopper\Http\Facades\ShopperApi; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', then: function (): void { ShopperApi::store(function (): void { Route::get('/store-locations', StoreLocatorController::class); }); ShopperApi::authenticated(function (): void { Route::get('/customers/me/wishlist', WishlistController::class); }); }, ) // ... ``` The groups do not include `SubstituteBindings`, so route parameters reach your controller as strings: look the record up yourself, by its public ID or its slug as the Shopper controllers do. The current customer, zone and channel are request attributes: `$request->attributes->get('shopper_customer')`, `shopper_zone` and `shopper_channel`, each `null` when nothing resolved. An add-on registers its routes with the same facade, from the `boot()` method of its add-on class, as [Extending the Store API](/3.x/addons/store-api#registering-routes) shows. ## Request Headers [#request-headers] The API reads a few request headers to know the response format, the pricing zone, the sales channel and the language. None of them is required: without them, the API falls back to the defaults of the shop. | Header | Value | Purpose | |--------|-------|---------| | `Accept` | `application/vnd.api+json` | The API answers JSON:API whatever you send, so this header is informative | | `Content-Type` | `application/json` | Required on requests with a body. Bodies are flat JSON objects, such as `{"quantity": 2}`. `application/vnd.api+json` works too | | `Authorization` | `Bearer <token>` | The customer token returned at login or registration | | `X-Shopper-Zone` | A zone code, such as `EU` | The pricing zone: currency, shipping options and payment methods | | `X-Shopper-Channel` | A channel slug, such as `web-store` | The sales channel: which products the catalog shows | | `Accept-Language` | A language, such as `fr-FR` | The language of translated content and of error messages | Responses carry `Vary: X-Shopper-Channel, X-Shopper-Zone`, so a CDN or HTTP cache in front of the API stores one copy per zone and channel. Product responses that include customer prices also vary on `Authorization`. ### Zone [#zone] A zone groups countries that share a currency, shipping options and payment methods, as the [Zones](/3.x/zones) page explains. The storefront picks one per request with `X-Shopper-Zone`, set to the `code` of an enabled zone. The zone sets the currency of product prices and of new carts, and the options offered at checkout. When the header is missing, or names no enabled zone, the API uses the zone whose code is in `SHOPPER_API_DEFAULT_ZONE`. When that is empty too, the request runs without a zone: prices fall back to the default currency of the shop, and the shipping options of a cart created without a zone answer `422`. An unknown code is not an error, so check the zone codes your storefront sends against [`GET /store/zones`](/3.x/store-api/store). Zones found by code are cached for 60 seconds (`zone.cache_ttl`), and the cache is cleared when a zone is saved or deleted in the admin panel. To pick the zone another way, such as from the visitor's country, bind your own resolver in `zone.resolver`. It implements `Shopper\Http\Contracts\ZoneResolver`: ```php title="app/Http/CountryZoneResolver.php" namespace App\Http; use Illuminate\Http\Request; use Shopper\Core\Models\Contracts\Zone as ZoneContract; use Shopper\Core\Models\Zone; use Shopper\Http\Contracts\ZoneResolver; final class CountryZoneResolver implements ZoneResolver { public function resolve(Request $request): ?ZoneContract { $country = $request->header('CF-IPCountry'); if (blank($country)) { return null; } return Zone::query() ->with('currency') ->where('is_enabled', true) ->whereRelation('countries', 'cca2', $country) ->first(); } } ``` ### Sales Channel [#sales-channel] A sales channel decides where a product is sold, as described on the [Channels](/3.x/channels) page. Send the `slug` of an enabled channel in `X-Shopper-Channel` and the catalog endpoints only return the products published in that channel; new carts record the channel too. When the header is missing or unknown, the API uses the channel whose slug is in `SHOPPER_API_DEFAULT_CHANNEL`. When nothing resolves, the catalog is not filtered by channel. The resolver is cached and swappable the same way as the zone resolver, through `channel.resolver` and `Shopper\Http\Contracts\ChannelResolver`. ### Language [#language] The API negotiates `Accept-Language` against the locales of the shop, the keys of `locales` in `config/shopper/admin.php` (`en` and `fr` by default). A regional value matches its base language, so `fr-FR` selects `fr`. A header that matches no locale selects the first one of the list, and a request without the header keeps the application locale. Products, categories and the other catalog records store their content in one language, so their names and descriptions do not change with the header. The negotiated locale changes the `translated_name` of countries (`Allemagne` for Germany in French, while `name` stays `Germany`), the content of add-ons that translate their own records, and the `detail` of error messages. The API's own messages ship in English, French, Spanish and Swedish. Laravel ships its validation messages in English only: publish them with `php artisan lang:publish` and add a translated copy, such as `lang/fr/validation.php`, to answer validation errors in the visitor's language. ## Rate Limits [#rate-limits] Every route counts against one or two named Laravel rate limiters, so that a single client cannot exhaust the shop. The limits are requests per minute, set in `rate_limiters` of `config/shopper/http.php`: | Limiter | Per minute | Applies to | Counted per | |---------|-----------|------------|-------------| | `shopper-api` | 120 | Every public and authenticated route | IP address on public routes, customer on authenticated routes | | `shopper-api-auth` | 20 | `/auth/register`, `/auth/login`, `/auth/forgot-password`, `/auth/reset-password` | IP address | | `shopper-api-checkout` | 30 | `POST /carts`, `POST /carts/{cartId}/lines`, `POST` and `DELETE /carts/{cartId}/promotion`, `POST /carts/{cartId}/payment-method`, `/payment-session`, `/complete` and `/transfer` | IP address on public routes, customer on `/transfer` | | `shopper-api-webhook` | 120 | The webhook routes | IP address | A route with two limiters counts the request against both. On public routes the count is per IP address even when the request carries a customer token. Each response carries `X-RateLimit-Limit` and `X-RateLimit-Remaining`. When two limiters apply, these headers report the one with the fewest requests left. Past the limit, the API answers `429 Too Many Requests` with `Retry-After` (seconds) and `X-RateLimit-Reset` (a Unix timestamp), as shown in [Rate Limit Errors](/3.x/store-api/errors#rate-limit-errors). Failed logins have their own, stricter count, described in [Failed Logins](/3.x/store-api/authentication#failed-logins). ### Behind a Server-Side Storefront [#behind-a-server-side-storefront] The limits count per IP address, which is the visitor's address when the browser calls the API. When your storefront calls the API from its own server, such as a Next.js server component or a Nuxt server route, every request comes from the server's address and all visitors share one quota. Forward the visitor's IP address in the `X-Forwarded-For` header from the storefront server, and trust that server in the Laravel application, so Laravel reads the forwarded address: ```php title="bootstrap/app.php" ->withMiddleware(function (Middleware $middleware): void { $middleware->trustProxies(at: ['10.0.0.12']); }) ``` Replace `10.0.0.12` with the address of your storefront server. Never trust every proxy (`at: '*'`) on an API open to the internet: any client could then send a fake `X-Forwarded-For` and pick its own quota. ## Configuration [#configuration] Two configuration files hold the Store API settings. `config/shopper/http.php` covers the HTTP layer: prefix, rate limits, zone, channel and middleware. | Key | Default | Purpose | |-----|---------|---------| | `prefix` | `env('SHOPPER_API_PREFIX', 'store')` | The path prefix of every route | | `rate_limiters` | 120, 20, 30, 120 | Requests per minute of each limiter, see [Rate Limits](#rate-limits) | | `login_failures` | `5` | Failed logins allowed per email and IP address within a minute | | `zone.header` | `X-Shopper-Zone` | The header the zone resolver reads | | `zone.default_code` | `env('SHOPPER_API_DEFAULT_ZONE')` | The zone used when the header names none | | `zone.resolver` | `DefaultZoneResolver` | The class that resolves the zone | | `zone.cache_ttl` | `60` | Seconds a zone stays cached. `0` turns the cache off | | `channel.header` | `X-Shopper-Channel` | The header the channel resolver reads | | `channel.default_slug` | `env('SHOPPER_API_DEFAULT_CHANNEL')` | The channel used when the header names none | | `channel.resolver` | `DefaultChannelResolver` | The class that resolves the channel | | `channel.cache_ttl` | `60` | Seconds a channel stays cached | | `middleware.store` | `[]` | Extra middleware appended to the public group | | `middleware.authenticated` | `[]` | Extra middleware appended to the authenticated group | | `middleware.webhook` | `[]` | Extra middleware appended to the webhook group | The `store` and `authenticated` middleware lists are separate: a middleware listed under `store` does not run on the authenticated routes, so list it in both when it must run everywhere. `config/shopper/api.php` covers what the endpoints return: | Key | Default | Purpose | |-----|---------|---------| | `pagination.per_page` | `env('SHOPPER_API_PER_PAGE', 15)` | Items per page when the request sends no `page[size]` | | `pagination.max_per_page` | `100` | The largest `page[size]` accepted | | `pagination.max_page` | `100` | The deepest `page[number]` accepted | | `token_expiration` | `env('SHOPPER_API_TOKEN_EXPIRATION', 43200)` | Lifetime of a customer token in minutes (30 days). `null` or `0` means no expiry | | `settings.expose` | Store name, contact, address, logo, currencies | The shop settings `GET /store/settings` returns | | `settings.max_age` | `300` | Seconds a client may cache the settings response | | `reviews.latest_limit` | `20` | The number of reviews `GET /store/reviews` returns | The filters, sorts and includes each listing accepts are not in this file: each resource class declares them, as [Extending the Allowlists](/3.x/store-api/json-api#extending-the-allowlists) explains. ## Your First Request [#your-first-request] The currencies endpoint needs no token and no body, which makes it a good first call to check that the API answers. This request lists the euro and the US dollar: ```bash title="Request" curl -g "http://localhost:8000/store/currencies?filter[code]=EUR,USD" \ -H "Accept: application/vnd.api+json" ``` The `-g` flag stops curl from reading the square brackets as a URL pattern. The API answers `200 OK` with the enabled currencies that match, one page at a time: ```json title="Response" { "data": [ { "id": "01JD3Z8M4K7Q2W9E5R6T1Y0H3B", "type": "currencies", "attributes": { "name": "Euro", "code": "EUR", "symbol": "€", "format": "1.0,00 €", "exchange_rate": 0 } }, { "id": "01JD3Z8M4N2C6V8X1P5G7S9A4F", "type": "currencies", "attributes": { "name": "US Dollar", "code": "USD", "symbol": "$", "format": "$1,0.00", "exchange_rate": 0 } } ], "links": { "first": "http://localhost:8000/store/currencies?filter%5Bcode%5D=EUR%2CUSD&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/currencies?filter%5Bcode%5D=EUR%2CUSD&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/currencies?filter%5Bcode%5D=EUR%2CUSD&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/currencies", "per_page": 15, "to": 2, "total": 2 } } ``` An empty `data` array means that no enabled currency has these codes. The [JSON:API Conventions](/3.x/store-api/json-api) page explains every member of this document. ## Next Steps [#next-steps] Each guide follows one part of the storefront flow, from the shared conventions to the order confirmation. <Cards> <Card title="Authentication" href="/3.x/store-api/authentication"> Register and log in customers, send their token, and reset passwords. </Card> <Card title="JSON:API Conventions" href="/3.x/store-api/json-api"> Read the document shape and use includes, sparse fieldsets, filters, sorting and pagination. </Card> <Card title="Errors" href="/3.x/store-api/errors"> Read the error object and react to every error code the API returns. </Card> <Card title="Catalog" href="/3.x/store-api/catalog"> List and filter products, categories, collections, brands, tags, attributes and reviews. </Card> <Card title="Store and Regions" href="/3.x/store-api/store"> Read the shop settings, the legal pages, and the countries, zones and currencies a storefront picks from. </Card> <Card title="Cart" href="/3.x/store-api/cart"> Create a cart, add products and variants, set addresses and apply promotion codes. </Card> <Card title="Checkout" href="/3.x/store-api/checkout"> Choose shipping and payment, open a payment session and turn the cart into an order. </Card> <Card title="Customers" href="/3.x/store-api/customers"> Manage the logged-in customer's profile, avatar and addresses. </Card> <Card title="Orders" href="/3.x/store-api/orders"> Show the order confirmation, the order history, shipments and digital downloads. </Card> </Cards> # JSON:API Conventions (/3.x/store-api/json-api) The Store API answers with [JSON:API](https://jsonapi.org) documents, built on Laravel's JSON:API resources. This page covers what every endpoint shares: the shape of a document, the query parameters that change a response, how amounts and languages come back, and the allowlists of the resource classes that decide which filters, sorts and includes a client may request. Each guide lists the values its own endpoints accept. JSON:API applies to responses only. Request bodies are flat JSON objects, such as `{"quantity": 2}`, sent with `Content-Type: application/json`: the API never reads a `data.attributes` envelope. ## Document Structure [#document-structure] A successful response is a JSON object served as `application/vnd.api+json`. Its top-level members are: | Member | Content | |--------|---------| | `data` | One resource object, or an array of them on a listing | | `included` | The related resources requested with `include`, each one listed once | | `links` | The pagination links of a listing | | `meta` | The pagination details of a listing, and values specific to an endpoint, such as `meta.currency` on the product listing | Each resource object carries an `id`, a `type` and its `attributes`, plus `relationships` when the request includes related resources. The `id` is always a string. For most resources, such as products, carts, orders, customers and zones, it is the public ID of the record, a ULID such as `01JD3ZA2B4C6D8E0F2G4H6J8K0`. A few resources differ: a legal page carries its database key, such as `"1"`, and is read by its slug; the store settings carry `"store"`; a shipping option or a payment session carries the ID its shipping or payment driver gives it, such as `manual:01JD9C4E6G8J0K2M4N6P8R0S2T`. The `type` is a plural, lowercase name with hyphens, such as `products`, `cart-lines` or `order-items`. A member with nothing to show is left out: a resource read without `include` has no `relationships`, and a document without related resources has no `included`. The API does not add a `jsonapi` member. Dates are ISO 8601 strings with their offset, such as `2026-11-02T09:15:00+00:00`, in the timezone of the application. This request reads the zone `EU` and includes its currency: ```bash title="Request" curl "http://localhost:8000/store/zones/EU?include=currency" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK`. The zone points to its currency in `relationships`, and the currency itself comes in `included`: ```json title="Response" { "data": { "id": "01JD3ZA2B4C6D8E0F2G4H6J8K0", "type": "zones", "attributes": { "name": "Europe", "slug": "europe", "code": "EU", "currency_code": "EUR", "metadata": null, "created_at": "2026-11-02T09:15:00+00:00", "updated_at": "2026-11-02T09:15:00+00:00" }, "relationships": { "currency": { "data": { "id": "01JD3Z8M4K7Q2W9E5R6T1Y0H3B", "type": "currencies" } } } }, "included": [ { "id": "01JD3Z8M4K7Q2W9E5R6T1Y0H3B", "type": "currencies", "attributes": { "name": "Euro", "code": "EUR", "symbol": "€", "format": "1.0,00 €", "exchange_rate": 0 } } ] } ``` To read a relationship, find the object in `included` whose `type` and `id` match the identifier in `relationships`. A to-one relationship holds one identifier, a to-many relationship an array of them. ## Includes [#includes] Related resources are left out by default, so that a listing stays small. The `include` parameter names the relationships to add, separated by commas. Each one adds a `relationships` entry to the resources of `data`, and the related resources to `included`, once each even when several resources share them: ```bash title="Request" curl "http://localhost:8000/store/products?include=brand,categories" \ -H "Accept: application/vnd.api+json" ``` A dot path includes a relationship of an included resource, such as `lines.purchasable.product` on a cart: the lines, the variant or product of each line, and the parent product of each variant. A path works only when it is listed for the resource, as the cart lists it. The names are case-sensitive and keep the case of the allowlist, such as `relatedProducts` or `paymentMethod`. Included catalog resources only hold what a visitor may see: a disabled brand, a hidden category or an unpublished collection stays out of `included`, and so do unpublished products. A few includes add values instead of related resources: | Resource | Include | Adds | |----------|---------|------| | Products | `rating` | The `rating` attribute, the average of the approved reviews rounded to one decimal (`null` without reviews), and `reviews_count` | | Products | `options` | The `options` attribute: the enabled attributes of the product, such as a color or a size, each with the values the product uses | | Products | `price_range` | On the listing, `meta.price_range`: the lowest and highest price of all the products that match the filters other than `price_min` and `price_max`, so that a price slider keeps its bounds | | Categories | `products_count` | The `products_count` attribute: the products of the category and of its subcategories | An include that is not in the allowlist of the resource answers `400 Bad Request` with the `bad_request` code. The `detail` names the includes the endpoint accepts: ```json title="Response" { "errors": [ { "status": "400", "code": "bad_request", "title": "Bad Request", "detail": "Requested include(s) `shippingOptions` are not allowed. Allowed include(s) are `currency, countries`." } ] } ``` ## Sparse Fieldsets [#sparse-fieldsets] A product carries its description, images, SEO fields and prices. A product grid needs a few of them. The `fields[<type>]` parameter keeps only the listed attributes for the resources of that type, in `data` and in `included` alike. The key is the resource `type`, such as `products` or `brands`: ```bash title="Request" curl -g "http://localhost:8000/store/products?include=brand&fields[products]=name,slug,price_range&fields[brands]=name&page[size]=1" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK`. This response leaves out `links` and `meta`: ```json title="Response" { "data": [ { "id": "01JD8YQ1A2B3C4D5E6F7G8H9JK", "type": "products", "attributes": { "name": "Classic Leather Sneakers", "slug": "classic-leather-sneakers", "price_range": { "currency_code": "EUR", "min": 9000, "max": 9500 } }, "relationships": { "brand": { "data": { "id": "01JD8XV1C3E5G7J9K1M3P5R7T9", "type": "brands" } } } } ], "included": [ { "id": "01JD8XV1C3E5G7J9K1M3P5R7T9", "type": "brands", "attributes": { "name": "Maison Cuir" } } ] } ``` `id`, `type` and `relationships` stay. An attribute name that the resource does not have is ignored, without an error. A fieldset trims the response but does not add anything: an attribute that comes with an include, such as `rating`, still needs that include. On two listings, four includes do not accept a fieldset for their own type: `variants` and `tags` on `/products`, `currency` and `countries` on `/zones`. A listing request that pairs one of them with `fields[variants]`, `fields[tags]`, `fields[currencies]` or `fields[countries]` answers `400 Bad Request` with the `bad_request` code. Every other include of a listing accepts a fieldset, and so does every include of a single resource, such as `/products/{slug}?include=variants&fields[variants]=name` or `/zones/{code}?include=countries&fields[countries]=name,cca2`. ## Filters [#filters] A listing narrows its results with `filter[<name>]=<value>`. The names a listing accepts come from its allowlist, and each one matches in one of three ways: | Kind | Matches | Example | |------|---------|---------| | Partial | Records whose column contains the value, ignoring case | `filter[name]=sneak` | | Exact | Records whose column equals the value | `filter[code]=EUR` | | Scope | Records selected by logic of its own, described in the guide of the endpoint | `filter[in_stock]=true` | A comma inside one filter means OR, and separate filters combine with AND. This request lists the countries of the zone `EU` whose name contains "fra" or "bel": ```bash title="Request" curl -g "http://localhost:8000/store/countries?filter[zone]=EU&filter[name]=fra,bel" \ -H "Accept: application/vnd.api+json" ``` The values `true` and `false` are read as booleans, as in `filter[featured]=true`. Some endpoints accept filters of their own on top of their allowlist, such as the price and currency filters of the product listing, described in the [Catalog](/3.x/store-api/catalog) guide. A filter accepts at most 50 values. Past that, the API answers `422` with the `filter_too_wide` code, and `source.pointer` names the filter, such as `/data/attributes/filter/category`. A filter name outside the allowlist answers `400 Bad Request` with the `bad_request` code, and a `detail` such as "Requested filter(s) \`color\` are not allowed. Allowed filter(s) are \`name, code\`.". Both are described in [Errors](/3.x/store-api/errors#error-codes). ## Sorting [#sorting] The `sort` parameter orders a listing by one of the sort names of its allowlist, in ascending order. A `-` prefix reverses it, and a comma separates several keys, applied in order: ```bash title="Request" curl "http://localhost:8000/store/products?sort=-published_at,name" \ -H "Accept: application/vnd.api+json" ``` The API always adds the record's creation order as the last sort key, so records with the same value come in a stable order and never move between two pages. Without `sort`, product reviews and the customer's orders come newest first, and the other listings come in the order the records were created. A sort name outside the allowlist answers `400 Bad Request` with the `bad_request` code. ## Pagination [#pagination] Every listing is paginated, except the few that return all their records at once: the category tree, the latest reviews, the shipping options and payment methods of a cart, and the customer's addresses. A listing returns 15 records per page by default, set by `SHOPPER_API_PER_PAGE`. It offers two kinds of pagination: by page number, the default, and by cursor. | Parameter | Default | Effect | |-----------|---------|--------| | `page[size]` | `15` | The number of records per page, from 1 to 100 (`pagination.max_per_page`). A larger value returns 100 records, without an error | | `page[number]` | `1` | The page to return, from 1 to 100 (`pagination.max_page`). A larger value returns page 100, without an error | | `page[cursor]` | None | Switches to cursor pagination. An empty value returns the first page | ### Page Numbers [#page-numbers] Page numbers suit a classic paged catalog, with the total count and a link per page. This request reads the first page of brands, two per page: ```bash title="Request" curl -g "http://localhost:8000/store/brands?sort=name&page[size]=2&page[number]=1" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK`. After `data`, the document carries these `links` and `meta`: ```json title="Response" { "links": { "first": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=3", "prev": null, "next": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 3, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=2", "label": "2", "page": 2, "active": false }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=3", "label": "3", "page": 3, "active": false }, { "url": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bnumber%5D=1&page%5Bnumber%5D=2", "label": "Next »", "page": 2, "active": false } ], "path": "http://localhost:8000/store/brands", "per_page": 2, "to": 2, "total": 5 } } ``` `meta.links` lists one entry per page, ready for a pager. On a long listing, it replaces the pages in the middle with one entry labeled `...`, whose `url` is `null` and that has no `page`. The link URLs keep the filters, sorts and includes of the request. When the request carries `page[number]`, they also repeat it before the new one, as in `page%5Bnumber%5D=1&page%5Bnumber%5D=2`. The API reads the last value, so requesting a link URL as it is returns the right page. Do not read the page number from a link URL with `URLSearchParams.get()`, which returns the first value: use the `page` of each `meta.links` entry and `meta.current_page` instead. The page number stops at 100 so that a request can never scan the whole table. To walk further, such as to export a large catalog, use a cursor. ### Cursors [#cursors] A cursor marks a position in the sorted results, so reading the next page costs the same at any depth. Send `page[cursor]` with an empty value to start, then follow `links.next` until it is `null`: ```bash title="Request" curl -g "http://localhost:8000/store/brands?sort=name&page[size]=2&page[cursor]=" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK`. A cursor page has no total and no page numbers: ```json title="Response" { "links": { "first": null, "last": null, "prev": null, "next": "http://localhost:8000/store/brands?sort=name&page%5Bsize%5D=2&page%5Bcursor%5D=eyJuYW1lIjoiTWFpc29uIEN1aXIiLCJzaF9icmFuZHMuaWQiOjMsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0" }, "meta": { "path": "http://localhost:8000/store/brands", "per_page": 2, "next_cursor": "eyJuYW1lIjoiTWFpc29uIEN1aXIiLCJzaF9icmFuZHMuaWQiOjMsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0", "prev_cursor": null } } ``` Treat the cursor as an opaque string. From the second page on, `links.next` and `links.prev` repeat the cursor of the request before the new one, like the page links, and the API reads the last value. When you build the next URL yourself, send `meta.next_cursor` as `page[cursor]` with the same filters and sort as the first request: a cursor only applies to the sort that produced it. ## Prices and Money [#prices-and-money] Every amount is an integer in cents, or in whole units for a [zero-decimal currency](/3.x/money#zero-decimal-currencies), next to the code of its currency. A product priced at €19.90 carries `1990`. Divide by 100, or use the currency's own number of decimals, before you display an amount. The [Money](/3.x/money#amounts-in-the-store-api) page lists the amount attributes of each resource and shows how to format them in JavaScript. The `prices` of a product or a variant list one entry per enabled currency, with the `amount`, the `compare_amount` (the crossed-out price, or `null`) and the `currency_code`. `calculated_price` and `price_range` use one currency, picked in this order: the `filter[currency]` parameter, then the currency of the zone sent in `X-Shopper-Zone`, then the default currency of the shop. `meta.currency` on the product endpoints gives the code that was picked. A `filter[currency]` that names an unknown or disabled currency answers `422` with the `currency_unknown` code. An enabled currency that the products have no price in still resolves: `calculated_price` and `price_range` are then `null`. The [Pricing](/3.x/pricing#from-a-storefront) page explains how `calculated_price` is resolved. A calculated price can depend on the customer, so product responses that carry one add `Authorization` to their `Vary` header. A cache in front of the API then keeps one copy per token. ## Locale [#locale] The `Accept-Language` header selects the language of the response among the locales of the shop, as described in [Request headers](/3.x/store-api#request-headers). It changes the `translated_name` of countries and the `detail` of error messages. Product names, descriptions and other catalog content are stored in one language and come back the same whatever the header. ## Allowlists [#allowlists] A client may only filter, sort and include what the shop allows. Each resource class of `Shopper\Api\Http\Resources` declares its allowlists in three static methods: `filters()`, `sorts()` and `includes()`. Filters and sorts apply to the listing of a resource, includes to its listing and to its show endpoint: | Resource | Endpoints | Filters | Sorts | Includes | |----------|-----------|---------|-------|----------| | `ProductResource` | `/products`, `/products/{slug}` | `name`, `sku`, `q`, `featured`, `in_stock`, `category`, `category_tree`, `collection`, `brand`, `tag`, `option` | `name`, `created_at`, `published_at`, `price` | `brand`, `variants`, `categories`, `collections`, `options`, `tags`, `relatedProducts`, `rating`, `price_range` | | `CategoryResource` | `/categories`, `/categories/{slug}` | `name` | `name`, `position` | `parent`, `children`, `ancestors`, `products`, `products_count` | | `CollectionResource` | `/collections`, `/collections/{slug}` | `name` | `name` | `products` | | `BrandResource` | `/brands`, `/brands/{slug}` | `name` | `name`, `position` | `products` | | `AttributeResource` | `/attributes` | `name` | `name` | None | | `TagResource` | `/tags` | `name` | `name` | `products` | | `CountryResource` | `/countries`, `/countries/{code}` | `name`, `cca2`, `cca3`, `region`, `zone` | `name` | `zones` | | `ZoneResource` | `/zones`, `/zones/{code}` | `name`, `code` | `name` | `currency`, `countries` | | `CurrencyResource` | `/currencies`, `/currencies/{code}` | `name`, `code` | `name`, `code` | None | | `CartResource` | The cart endpoints that answer with the cart | None | None | `lines`, `lines.purchasable`, `lines.purchasable.product`, `addresses`, `paymentMethod` | | `OrderResource` | `/customers/me/orders`, `/customers/me/orders/{orderId}` | `status` | `created_at` | `items`, `shippingAddress`, `billingAddress`, `paymentMethod`, `shippings`, `shippings.events`, `refund` | | `ReviewResource` | `/products/{slug}/reviews` | `rating` | `created_at`, `rating` | None | | `LegalResource` | `/legals`, `/legals/{slug}` | `title` | `title`, `updated_at` | None | `GET /store/reviews` returns the 20 latest reviews, and `reviews.latest_limit` in `config/shopper/api.php` changes that number. The guides describe what each filter and include does. ## Extending the Allowlists [#extending-the-allowlists] A storefront sometimes needs a filter, a sort or an include the shop does not allow yet, such as looking a product up by its barcode. To add one, extend the resource class, override the static method of the list and register your class with the `ApiResource` facade. The endpoints of that resource then read the lists from your class: the filters and sorts on the listing, the includes on the listing and on the show endpoint. This class adds an exact `barcode` filter to the products. It spreads `parent::filters()` first, so the default filters stay, including those a later Shopper release adds: ```php title="app/Http/Resources/StoreProductResource.php" namespace App\Http\Resources; use Shopper\Api\Http\Resources\ProductResource; use Spatie\QueryBuilder\AllowedFilter; class StoreProductResource extends ProductResource { public static function filters(): array { return [ ...parent::filters(), AllowedFilter::exact('barcode'), ]; } } ``` This `boot` method of a service provider makes the Store API use your class in place of `ProductResource`: ```php title="app/Providers/AppServiceProvider.php" use App\Http\Resources\StoreProductResource; use Shopper\Api\Facades\ApiResource; use Shopper\Api\Http\Resources\ProductResource; public function boot(): void { ApiResource::replace(ProductResource::class, StoreProductResource::class); } ``` This request looks the product up by its barcode: ```bash title="Request" curl -g "http://localhost:8000/store/products?filter[barcode]=3700123456789" \ -H "Accept: application/vnd.api+json" ``` The lists hold the objects of [Laravel Query Builder](https://spatie.be/docs/laravel-query-builder/v7/introduction), which the Store API runs its queries with. The default lists use these forms: | Entry | Effect | |-------|--------| | `AllowedFilter::partial('name')` in `filters()` | Filter: the column contains the value, ignoring case | | `AllowedFilter::exact('sku')` in `filters()` | Filter: the column equals the value | | `AllowedFilter::exact('zone', 'zones.code')` in `filters()` | Filter: a column of a relation equals the value | | `AllowedFilter::scope('category')` in `filters()` | Filter: calls the `category` query scope of the model | | `AllowedFilter::scope('in_stock', 'availability')` in `filters()` | Filter: calls a scope with another name, here `availability` | | `'name'` in `sorts()` | Sort: by the column of that name | | `AllowedSort::field('price', 'min_price')` in `sorts()` | Sort: by another column or select alias, here the lowest price | | `'tags'` in `includes()` | Include: loads the relation with all its rows | | `AllowedInclude::custom('brand', new EnabledRelation)` in `includes()` | Include: runs an include class, which keeps only the public rows | | `'categories' => ['categories.parent']` in `includeLoads()` | Loads these relations too when the include is requested, so that the response does not query each record | A plain include loads every related row, enabled or not. For a relation that holds drafts or disabled records, pass one of the include classes of `Shopper\Api\Http\Includes` to `AllowedInclude::custom()`: `EnabledRelation` and `PublishedRelation` apply the `enabled` and `published` scopes of the related model. An include class implements `Spatie\QueryBuilder\Includes\IncludeInterface`, so you can write your own. To remove a default entry, return a list without it instead of spreading the parent list. An include you add also needs its relationship in `toRelationships()`, as [Replacing a Resource](#replacing-a-resource) explains. ### Replacing a Resource [#replacing-a-resource] The allowlists decide what a client may request, not what a document contains. To add an attribute or a relationship to a resource, extend its resource class and register the replacement with the `ApiResource` facade. This class adds a `care_instructions` column that your application added to the products table: ```php title="app/Http/Resources/StoreProductResource.php" namespace App\Http\Resources; use Illuminate\Http\Request; use Shopper\Api\Http\Resources\ProductResource; class StoreProductResource extends ProductResource { public function toAttributes(Request $request): array { return [ ...parent::toAttributes($request), 'care_instructions' => $this->care_instructions, ]; } } ``` Register it in the `boot` method of a service provider: ```php title="app/Providers/AppServiceProvider.php" use App\Http\Resources\StoreProductResource; use Shopper\Api\Facades\ApiResource; use Shopper\Api\Http\Resources\ProductResource; public function boot(): void { ApiResource::replace(ProductResource::class, StoreProductResource::class); } ``` Every endpoint then serializes products with your class, in `data`, in listings and in `included`, and reads the allowlists and the relations to load from it. `replace()` also takes an array that maps several stock classes to their replacements. A replacement must extend the class it replaces, or `replace()` throws an `InvalidArgumentException`. The `type` of a resource cannot change. One class can both change the allowlists and add attributes: a resource takes one replacement only, and the last `replace()` call wins. A new include also needs its relationship declared in `toRelationships()` of the resource. Laravel's JSON:API resource leaves out the relationships a resource does not declare, so an include that is in `includes()` but missing from `toRelationships()` answers `200` without the relation. Override `toRelationships()` in the replacement and add your relation to the array the parent method returns. ### Loading Relations [#loading-relations] An attribute that reads a relation, such as the names of the tags of a product, runs one query per product: 24 queries on a listing of 24 products. The static `eagerLoads()` method lists the relations the Store API loads together with the records of a resource, on every query that serializes it. `ProductResource` loads `prices.currency` and `media` this way. This replacement sends the names of the tags of each product, and adds `tags` to the relations it loads, so a listing reads the tags of all its products in one query: ```php title="app/Http/Resources/StoreProductResource.php" namespace App\Http\Resources; use Illuminate\Http\Request; use Shopper\Api\Http\Resources\ProductResource; class StoreProductResource extends ProductResource { public static function eagerLoads(): array { return [...parent::eagerLoads(), 'tags']; } public function toAttributes(Request $request): array { return [ ...parent::toAttributes($request), 'tag_names' => $this->tags->pluck('name'), ]; } } ``` An add-on does not replace the resource, since the store keeps that replacement for itself. It registers its relations with `ApiResource::eagerLoad()` on the stock class, and the Store API loads them for the replacement too, as [Extending the Store API](/3.x/addons/store-api#loading-the-relations) shows. ## Next Steps [#next-steps] These conventions apply to every guide that follows, starting with the errors the parameters can cause. <Cards> <Card title="Errors" href="/3.x/store-api/errors"> Read the error object and react to each error code. </Card> <Card title="Catalog" href="/3.x/store-api/catalog"> The filters, sorts and includes of the product, category, collection and brand listings. </Card> <Card title="Cart" href="/3.x/store-api/cart"> Create a cart and include its lines and their products. </Card> </Cards> # Orders (/3.x/store-api/orders) Once the checkout places an order, the storefront shows it at three moments: on the confirmation page right after payment, in the order history of the account, and on a tracking page while the parcel travels. A digital product adds a fourth: the download of the files the customer paid for. This guide follows those moments in order. Orders are read-only in the Store API. The storefront never changes an order: the merchant updates it in the admin panel, and payment and carrier webhooks move its statuses. The [Orders](/3.x/orders) page covers the order model and its life cycle. ## Endpoints [#endpoints] The confirmation lookup and the shipment tracking sit in the public route group and work without a token. The account endpoints need the bearer token of a signed-in customer, described in [Logging in](/3.x/store-api/authentication#logging-in). <Routes> <Route method="GET" path="/store/orders/{orderId}" href="#get-store-orders-orderid">Order confirmation</Route> <Route method="GET" path="/store/customers/me/orders" href="#get-store-customers-me-orders">Order history</Route> <Route method="GET" path="/store/customers/me/orders/{orderId}" href="#get-store-customers-me-orders-orderid">Order details</Route> <Route method="GET" path="/store/shipments/{shipmentId}" href="#get-store-shipments-shipmentid">Shipment tracking</Route> <Route method="GET" path="/store/customers/me/orders/{orderId}/items/{itemId}/files/{fileId}" href="#get-store-customers-me-orders-orderid-items-itemid-files-fileid">Download link of a purchased file</Route> <Route method="GET" path="/store/files/{fileId}" href="#get-store-files-fileid">The file itself, through a signed link</Route> </Routes> ## Order Confirmation [#order-confirmation] The confirmation page thanks the customer and recaps what they bought, for guests and customers alike. The checkout returns the ID of the new order, as the [Checkout](/3.x/store-api/checkout) guide shows, and the storefront reads the order with it. <Endpoint id="get-store-orders-orderid" method="GET" path="/store/orders/{orderId}" auth="owner"> <Params title="Path parameters"> <Field name="orderId" type="string" required> The order ID, the `id` of the order the checkout returns. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `items` only, as [Who Can Read an Order](#who-can-read-an-order) explains. </Field> <Field name="fields[orders]" type="string"> Attributes to return, comma-separated, such as `number,status`. See [Sparse Fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This order belongs to a signed-in customer, so the request carries their token, as [Who Can Read an Order](#who-can-read-an-order) explains: ```bash title="Request" curl "http://localhost:8000/store/orders/01JQ8Z6N4W2T5V3K9R7M1H0XAB?include=items" \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `200 OK` with the order and its lines in `included`: ```json title="Response 200" { "data": { "id": "01JQ8Z6N4W2T5V3K9R7M1H0XAB", "type": "orders", "attributes": { "number": "ORD-20261117-000042", "status": "new", "payment_status": "pending", "shipping_status": "unfulfilled", "total": 13800, "tax_amount": 2398, "shipping_amount": 590, "price_amount": 14390, "currency_code": "EUR", "email": "camille.martin@example.com", "created_at": "2026-11-17T09:42:12+00:00" }, "relationships": { "items": { "data": [ { "id": "01JQ8Z6N5D9F3E5G7H2K4M6N8Q", "type": "order-items" }, { "id": "01JQ8Z6N5C8E2D4F6G1J3K5M7P", "type": "order-items" } ] } } }, "included": [ { "id": "01JQ8Z6N5D9F3E5G7H2K4M6N8Q", "type": "order-items", "attributes": { "name": "Classic Leather Sneakers", "sku": "CLS-BLK-42", "quantity": 1, "unit_price_amount": 12900, "total": 12900, "metadata": null } }, { "id": "01JQ8Z6N5C8E2D4F6G1J3K5M7P", "type": "order-items", "attributes": { "name": "Sneaker Care Guide", "sku": "SCG-PDF", "quantity": 1, "unit_price_amount": 900, "total": 900, "metadata": null } } ] } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No order with this ID, or a customer order read without that customer's token | | 422 | `include_not_allowed` | An include other than `items` | </Errors> </Endpoint> ### Who Can Read an Order [#who-can-read-an-order] The confirmation lookup needs no token, so a guest can see the order they just placed. Access follows from who placed the order: | Order placed | Who can read it here | |--------------|----------------------| | As a guest, without a token | Anyone holding the order ID | | By a signed-in customer | Only requests with that customer's token | The order ID is a ULID, 26 characters with 80 random bits, so it cannot be guessed, but for a guest order it works like a password. Keep it in the confirmation URL or the session of the visitor, and out of logs and analytics events. A customer order read without the token, or with the token of another customer, answers `404 not_found`, the same answer as an ID that does not exist, so the API never confirms that an order exists. Because a guest order is readable by its ID alone, this endpoint returns less than the account endpoints: - `items` is the only relationship you can include. Addresses, the payment method, shipments and refunds are on the [Order details](#order-details) endpoint, for signed-in customers. - The items carry no `files`, even for a paid order: downloads go through the account, as [Downloading purchased files](#downloading-purchased-files) describes. Any other include answers `422` with the `include_not_allowed` code: ```json title="Response 422" { "errors": [ { "status": "422", "code": "include_not_allowed", "title": "Unprocessable Content", "detail": "Only `items` can be included on the order confirmation lookup. Use the account order endpoint for the full order.", "source": { "pointer": "/data/attributes/include" } } ] } ``` The account endpoints answer an include outside their list with `400 bad_request` instead, so handle both codes if your storefront builds include lists dynamically. ## The Order Resource [#the-order-resource] The confirmation, the history and the details all return the same `orders` resource. Its attributes summarize the order; the lines, addresses and shipments come through includes. <Attributes title="orders attributes"> <Field name="number" type="string"> The number the customer sees, such as `ORD-20261117-000042`. The format is set in the shop configuration, as [Orders](/3.x/orders#order-number-generation) describes. </Field> <Field name="status" type="string"> Where the order stands for the merchant. </Field> <Field name="payment_status" type="string"> Where the payment stands. </Field> <Field name="shipping_status" type="string"> Where the delivery stands, across every package. </Field> <Field name="total" type="integer"> Sum of the lines in cents, after line discounts, without shipping. </Field> <Field name="tax_amount" type="integer"> Tax of the order in cents. </Field> <Field name="shipping_amount" type="integer, null"> Shipping cost in cents. </Field> <Field name="price_amount" type="integer"> What the customer paid, in cents. </Field> <Field name="currency_code" type="string"> ISO code of the order currency, such as `EUR`. </Field> <Field name="email" type="string, null"> Email the order was placed with. </Field> <Field name="created_at" type="string"> When the order was placed, ISO 8601. </Field> </Attributes> ### Amounts [#amounts] Every amount is an integer in cents: `14390` is €143.90. The [Money](/3.x/money) page covers cents and formatting. Show `price_amount` as the amount paid. It is the sum of the lines, minus discounts, plus shipping, plus taxes when prices exclude tax. `total` covers the lines only, so it fits a "Subtotal" row, not the amount charged. In the example above, the lines sum to €138.00, shipping adds €5.90, and the customer paid €143.90, of which €23.98 is VAT included in the prices. The [Orders](/3.x/orders#order-total) page details how the totals are computed. ### Statuses [#statuses] An order carries three statuses, each moved by a different part of the shop. The [Orders](/3.x/orders#order-status) page describes each value and when it changes. | Attribute | Values | |-----------|--------| | `status` | `new`, `processing`, `completed`, `cancelled`, `archived` | | `payment_status` | `pending`, `authorized`, `paid`, `partially_refunded`, `refunded`, `voided` | | `shipping_status` | `unfulfilled`, `partially_shipped`, `shipped`, `partially_delivered`, `delivered`, `partially_returned`, `returned` | ### Relationships [#relationships] These relationships appear when you include them. On the confirmation lookup, only `items` is available. | Relationship | Type | Attributes | |--------------|------|------------| | `items` | `order-items` | `name`, `sku`, `quantity`, `unit_price_amount`, `total` (unit price times quantity, minus the line discount), `metadata`, and `files` for a downloadable product on the order details | | `shippingAddress`, `billingAddress` | `order-addresses` | `first_name`, `last_name`, `full_name`, `company`, `street_address`, `street_address_plus`, `city`, `state`, `postal_code`, `phone`, `country_name` | | `paymentMethod` | `payment-methods` | `title`, `slug`, `description`, `instructions`, `driver`, `logo` | | `shippings` | `order-shippings` | The packages of the order, as [Tracking a shipment](#tracking-a-shipment) describes | | `refund` | `order-refunds` | `status`, `amount` in cents, `currency`, `reason`, `created_at` | The order keeps a copy of the addresses and of each line as they were at checkout, so later changes to the customer's saved addresses or to the catalog do not alter a past order. ## Order History [#order-history] The account area lists the orders of the customer, newest first, with their number, statuses and amount. The list returns only the orders of the token owner. <Endpoint id="get-store-customers-me-orders" method="GET" path="/store/customers/me/orders" auth="customer"> The list accepts these query parameters, described in [JSON:API Conventions](/3.x/store-api/json-api): <Params title="Query parameters"> <Field name="filter[status]" type="string"> One order status or several, comma-separated, such as `processing` or `new,processing`. Keeps the orders in those statuses. See [Filters](/3.x/store-api/json-api#filters). </Field> <Field name="sort" type="string" default="-created_at"> `created_at` or `-created_at`: oldest or newest first. See [Sorting](/3.x/store-api/json-api#sorting). </Field> <Field name="include" type="string"> Relationships to add, comma-separated: `items`, `shippingAddress`, `billingAddress`, `paymentMethod`, `shippings`, `shippings.events`, `refund`. See [Includes](/3.x/store-api/json-api#includes). </Field> <Field name="page[size]" type="integer" default="15"> Orders per page, 1 to 100. </Field> <Field name="page[number]" type="integer"> Page to return, 1 to 100. </Field> <Field name="page[cursor]" type="string"> The cursor of a previous page. Switches to cursor pagination. See [Pagination](/3.x/store-api/json-api#pagination). </Field> <Field name="fields[orders]" type="string"> Attributes to return, comma-separated, such as `number,status`. See [Sparse Fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request lists the orders of the customer the token belongs to: ```bash title="Request" curl http://localhost:8000/store/customers/me/orders \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `200 OK` with a page of orders, the pagination links and the page details: ```json title="Response 200" { "data": [ { "id": "01JQ8Z6N4W2T5V3K9R7M1H0XAB", "type": "orders", "attributes": { "number": "ORD-20261117-000042", "status": "processing", "payment_status": "paid", "shipping_status": "shipped", "total": 13800, "tax_amount": 2398, "shipping_amount": 590, "price_amount": 14390, "currency_code": "EUR", "email": "camille.martin@example.com", "created_at": "2026-11-17T09:42:12+00:00" } }, { "id": "01JP3M7R2X5K8N1Q4T6W9Y0ZAB", "type": "orders", "attributes": { "number": "ORD-20261002-000017", "status": "completed", "payment_status": "paid", "shipping_status": "delivered", "total": 4800, "tax_amount": 900, "shipping_amount": 590, "price_amount": 5390, "currency_code": "EUR", "email": "camille.martin@example.com", "created_at": "2026-10-02T17:11:40+00:00" } } ], "links": { "first": "http://localhost:8000/store/customers/me/orders?page%5Bnumber%5D=1", "last": "http://localhost:8000/store/customers/me/orders?page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/customers/me/orders?page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/customers/me/orders", "per_page": 15, "to": 2, "total": 2 } } ``` <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 400 | `bad_request` | A filter, sort or include outside the list | | 422 | `filter_too_wide` | `filter[status]` lists more than 50 values | </Errors> </Endpoint> The list carries the order summaries only. Open one order with [Order details](#order-details) to show its lines and shipments, or add includes to the list when the history page shows more than the summary. ### Filters, Sorting and Includes [#filters-sorting-and-includes] The parameters of the [order list](#get-store-customers-me-orders) combine, so each tab of the history page is one request. `filter[status]` takes one [status](#statuses) or several, comma-separated, such as `new,processing`. `sort=created_at` lists the oldest orders first, and `include` adds the relationships the page shows, such as `items` for the order lines. For a tab that shows the orders still on their way: ```bash title="Request" curl -g "http://localhost:8000/store/customers/me/orders?filter[status]=processing&page[size]=10" \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` ## Order Details [#order-details] The order page of the account shows everything the customer may need after buying: the lines, where the parcel goes, how they paid, the packages and their tracking, and a refund when there is one. <Endpoint id="get-store-customers-me-orders-orderid" method="GET" path="/store/customers/me/orders/{orderId}" auth="customer"> <Params title="Path parameters"> <Field name="orderId" type="string" required> The order ID, the `id` of an order of the history. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> Relationships to add, comma-separated: `items`, `shippingAddress`, `billingAddress`, `paymentMethod`, `shippings`, `shippings.events`, `refund`. See [Includes](/3.x/store-api/json-api#includes). </Field> <Field name="fields[orders]" type="string"> Attributes to return, comma-separated, such as `number,status`. See [Sparse Fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> Ask for what the page shows with `include`: ```bash title="Request" curl "http://localhost:8000/store/customers/me/orders/01JQ8Z6N4W2T5V3K9R7M1H0XAB?include=items,shippingAddress,shippings.events" \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` The API answers `200 OK` with the order and the included resources. This order is paid, so the item of the Sneaker Care Guide, a downloadable product, lists its files: ```json title="Response 200" { "data": { "id": "01JQ8Z6N4W2T5V3K9R7M1H0XAB", "type": "orders", "attributes": { "number": "ORD-20261117-000042", "status": "processing", "payment_status": "paid", "shipping_status": "shipped", "total": 13800, "tax_amount": 2398, "shipping_amount": 590, "price_amount": 14390, "currency_code": "EUR", "email": "camille.martin@example.com", "created_at": "2026-11-17T09:42:12+00:00" }, "relationships": { "items": { "data": [ { "id": "01JQ8Z6N5D9F3E5G7H2K4M6N8Q", "type": "order-items" }, { "id": "01JQ8Z6N5C8E2D4F6G1J3K5M7P", "type": "order-items" } ] }, "shippingAddress": { "data": { "id": "01JQ8Z6N5E1G3H5J7K9M1N3P5Q", "type": "order-addresses" } }, "shippings": { "data": [ { "id": "01JQ9B2C4D6E8F0G1H3J5K7M9N", "type": "order-shippings" } ] } } }, "included": [ { "id": "01JQ8Z6N5D9F3E5G7H2K4M6N8Q", "type": "order-items", "attributes": { "name": "Classic Leather Sneakers", "sku": "CLS-BLK-42", "quantity": 1, "unit_price_amount": 12900, "total": 12900, "metadata": null } }, { "id": "01JQ8Z6N5C8E2D4F6G1J3K5M7P", "type": "order-items", "attributes": { "name": "Sneaker Care Guide", "sku": "SCG-PDF", "quantity": 1, "unit_price_amount": 900, "total": 900, "metadata": null, "files": [ { "id": "4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13", "name": "sneaker-care-guide", "extension": "pdf", "size": 2483012 } ] } }, { "id": "01JQ8Z6N5E1G3H5J7K9M1N3P5Q", "type": "order-addresses", "attributes": { "first_name": "Camille", "last_name": "Martin", "full_name": "Camille Martin", "company": null, "street_address": "18 Rue de la Roquette", "street_address_plus": "Apartment 4B", "city": "Paris", "state": null, "postal_code": "75011", "phone": "+33 6 12 34 56 78", "country_name": "France" } }, { "id": "01JQ9B2C4D6E8F0G1H3J5K7M9N", "type": "order-shippings", "attributes": { "status": "in_transit", "carrier_name": "Colissimo", "tracking_number": "6A12345678901", "tracking_url": "https://www.laposte.fr/outils/suivre-vos-envois?code=6A12345678901", "shipped_at": "2026-11-18T08:30:00+00:00", "received_at": null, "returned_at": null }, "relationships": { "events": { "data": [ { "id": "01JQ9B3D5F7H9K1M3P5R7T9V1X", "type": "order-shipping-events" }, { "id": "01JQ9C4E6G8J0K2M4N6P8R0S2T", "type": "order-shipping-events" } ] } } }, { "id": "01JQ9B3D5F7H9K1M3P5R7T9V1X", "type": "order-shipping-events", "attributes": { "status": "picked_up", "description": "Parcel picked up by the carrier", "location": "Paris, FR", "latitude": "48.8566000", "longitude": "2.3522000", "occurred_at": "2026-11-18T08:30:00+00:00", "created_at": "2026-11-18T08:31:04+00:00" } }, { "id": "01JQ9C4E6G8J0K2M4N6P8R0S2T", "type": "order-shipping-events", "attributes": { "status": "in_transit", "description": "Parcel in transit to the sorting center", "location": "Wissous, FR", "latitude": "48.7311000", "longitude": "2.3263000", "occurred_at": "2026-11-18T19:05:00+00:00", "created_at": "2026-11-18T19:06:12+00:00" } } ] } ``` The includes are the ones of the [order history](#get-store-customers-me-orders). Without `include`, the response carries the attributes only. Events included through `shippings.events` come in no set order: sort them by `occurred_at` before you draw a timeline. The [shipment endpoint](#tracking-a-shipment) returns them sorted. An order of another customer answers `404 not_found`, like an ID that does not exist. An include outside the list answers `400 bad_request`. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 404 | `not_found` | No order with this ID among the orders of the customer | | 400 | `bad_request` | An include outside the list | </Errors> </Endpoint> ## Tracking a Shipment [#tracking-a-shipment] A tracking page shows where a package is, without asking the customer to sign in, so it works from a link in a shipping email. An order can ship in several packages; each one is a shipment with its own ID, carrier and tracking number. The storefront gets the shipment ID from `include=shippings` on the [order details](#order-details), where each `order-shippings` resource is one package. A guest has no account to read, so pass the ID in the email you send when the package ships: the `shipment.*` webhooks carry it as the `id` of the package, as [Webhooks](/3.x/webhooks#shipment-data) describes. <Endpoint id="get-store-shipments-shipmentid" method="GET" path="/store/shipments/{shipmentId}" auth="public"> <Params title="Path parameters"> <Field name="shipmentId" type="string" required> The shipment ID, the `id` of an `order-shippings` resource or of the package in a `shipment.*` webhook. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `events` only. </Field> <Field name="fields[order-shippings]" type="string"> Attributes to return, comma-separated, such as `status,tracking_url`. See [Sparse Fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> This request reads a shipment, and asks for its tracking events with `include=events`: ```bash title="Request" curl "http://localhost:8000/store/shipments/01JQ9B2C4D6E8F0G1H3J5K7M9N?include=events" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the shipment and its tracking events, oldest first: ```json title="Response 200" { "data": { "id": "01JQ9B2C4D6E8F0G1H3J5K7M9N", "type": "order-shippings", "attributes": { "status": "in_transit", "carrier_name": "Colissimo", "tracking_number": "6A12345678901", "tracking_url": "https://www.laposte.fr/outils/suivre-vos-envois?code=6A12345678901", "shipped_at": "2026-11-18T08:30:00+00:00", "received_at": null, "returned_at": null }, "relationships": { "events": { "data": [ { "id": "01JQ9B3D5F7H9K1M3P5R7T9V1X", "type": "order-shipping-events" }, { "id": "01JQ9C4E6G8J0K2M4N6P8R0S2T", "type": "order-shipping-events" } ] } } }, "included": [ { "id": "01JQ9B3D5F7H9K1M3P5R7T9V1X", "type": "order-shipping-events", "attributes": { "status": "picked_up", "description": "Parcel picked up by the carrier", "location": "Paris, FR", "latitude": "48.8566000", "longitude": "2.3522000", "occurred_at": "2026-11-18T08:30:00+00:00", "created_at": "2026-11-18T08:31:04+00:00" } }, { "id": "01JQ9C4E6G8J0K2M4N6P8R0S2T", "type": "order-shipping-events", "attributes": { "status": "in_transit", "description": "Parcel in transit to the sorting center", "location": "Wissous, FR", "latitude": "48.7311000", "longitude": "2.3263000", "occurred_at": "2026-11-18T19:05:00+00:00", "created_at": "2026-11-18T19:06:12+00:00" } } ] } ``` <Attributes title="order-shippings attributes"> <Field name="status" type="string, null"> Where the package stands: `pending`, `picked_up`, `in_transit`, `at_sorting_center`, `out_for_delivery`, `delivered`, `delivery_failed` or `returned`. </Field> <Field name="carrier_name" type="string, null"> Name of the carrier, or `null` when the package has none. </Field> <Field name="tracking_number" type="string, null"> The carrier reference, to show to the customer. </Field> <Field name="tracking_url" type="string, null"> The carrier's own tracking page, to link to. </Field> <Field name="shipped_at" type="string, null"> When the package left, ISO 8601, or `null`. </Field> <Field name="received_at" type="string, null"> When the package was delivered, ISO 8601, or `null`. </Field> <Field name="returned_at" type="string, null"> When the package came back, ISO 8601, or `null`. </Field> </Attributes> Each event has a `status` from the same list, a `description` and a `location` from the carrier, `latitude` and `longitude` as strings with seven decimals (or `null`), and `occurred_at`, the time the carrier reported. The [Fulfillment](/3.x/fulfillment#shipment-status-package-level) page describes the shipment statuses and how carriers report events. `events` is the only include of this endpoint; any other answers `400 bad_request`. An unknown shipment ID answers `404 not_found`. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No shipment with this ID | | 400 | `bad_request` | An include other than `events` | </Errors> </Endpoint> ## Downloading Purchased Files [#downloading-purchased-files] A customer who buys a digital product, such as a PDF guide or a font pack, downloads its files from their account. The files sit on a private disk with no public URL, so the storefront asks the API for a short-lived link each time the customer clicks **Download**. <Endpoint id="get-store-customers-me-orders-orderid-items-itemid-files-fileid" method="GET" path="/store/customers/me/orders/{orderId}/items/{itemId}/files/{fileId}" auth="customer"> <Params title="Path parameters"> <Field name="orderId" type="string" required> The order ID. </Field> <Field name="itemId" type="string" required> The `id` of the `order-items` resource. </Field> <Field name="fileId" type="string" required> The `id` of one of the `files` of the item. </Field> </Params> <Steps> <Step title="Read the order with its items"> Request the [order details](#order-details) with `include=items`. Once the payment status of the order is `paid` or `partially_refunded`, each item of a downloadable product carries `files`, with the `id`, `name`, `extension` and `size` in bytes of each file. Show one **Download** button per file. </Step> <Step title="Ask for a link when the customer clicks"> Call the file endpoint with the order ID, the item ID and the file `id`: ```bash title="Request" curl http://localhost:8000/store/customers/me/orders/01JQ8Z6N4W2T5V3K9R7M1H0XAB/items/01JQ8Z6N5C8E2D4F6G1J3K5M7P/files/4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13 \ -H "Accept: application/vnd.api+json" \ -H "Authorization: Bearer 1|customer-token" ``` </Step> <Step title="Send the browser to the link"> Redirect the browser, or open a new tab, to the `url` of the response right away. The file comes back as an attachment named after the file, such as `sneaker-care-guide.pdf`. </Step> </Steps> The API answers `200 OK` with the link and the moment it expires. This response is a plain `data` object, not a JSON:API resource: ```json title="Response 200" { "data": { "url": "http://localhost:8000/store/files/4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13?expires=1794995232&signature=b7e3c1f0a9d24e6b8c5f1a7d3e9b2c4f6a8d0e2b4c6f8a1d3e5b7c9f0a2d4e6b", "expires_at": "2026-11-18T09:47:12+00:00" } } ``` The link works for five minutes. Ask for a new one at every click rather than storing it, and never put it in an email: anyone holding the link downloads the file until it expires. The API keeps no count of links or downloads per customer: only the general [rate limit](/3.x/store-api#rate-limits) of the Store API applies. <Errors> | Status | Code | When | |--------|------|------| | 401 | `unauthenticated` | The request has no valid customer token | | 403 | `forbidden` | The order is not paid yet: "The files of this order are available once it is paid." | | 404 | `not_found` | The order is not one of the customer's, the item is not in the order, or the file does not belong to the product of the item | </Errors> </Endpoint> The shape of the link depends on the disk that holds the files, the `shopper.media.storage.files_disk` setting described in [Products](/3.x/products#downloadable-files): - On an S3 disk, the link is a temporary URL of the bucket, and the download goes straight to S3. - On any other disk, such as the default `local` disk, the link points to `GET /store/files/{fileId}`, a route signed by your app, which streams the file. A link that was altered or has expired answers `403`. <Endpoint id="get-store-files-fileid" method="GET" path="/store/files/{fileId}" auth="signed"> <Params title="Path parameters"> <Field name="fileId" type="string" required> The file `id`, set by the API in the `url` of the download link. </Field> </Params> <Params title="Query parameters"> <Field name="expires" type="integer" required> Unix time at which the link expires, set by the API. </Field> <Field name="signature" type="string" required> Signature of the URL, set by the API. </Field> </Params> The request needs no token: the signature grants access. Call the `url` of the download link as it is. With `-OJ`, curl saves the file under the name the API sends: ```bash title="Request" curl -OJ "http://localhost:8000/store/files/4b1f0c2e-8d6a-4f3e-9a51-6c2d7e9b0a13?expires=1794995232&signature=b7e3c1f0a9d24e6b8c5f1a7d3e9b2c4f6a8d0e2b4c6f8a1d3e5b7c9f0a2d4e6b" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` and streams the file as an attachment named after the file. The body is the file itself; the headers below are trimmed to the ones about the file: ```text title="Response 200" HTTP/1.1 200 OK Content-Disposition: attachment; filename=sneaker-care-guide.pdf Content-Type: application/pdf Content-Length: 2483012 Cache-Control: no-cache, private ``` A link without its signature, with a changed parameter, or past its expiry answers `403` with the `forbidden` code: ```json title="Response 403" { "errors": [ { "status": "403", "code": "forbidden", "title": "Forbidden", "detail": "Invalid signature." } ] } ``` <Errors> | Status | Code | When | |--------|------|------| | 403 | `forbidden` | The signature is missing, altered or expired | | 404 | `not_found` | No file with this ID | </Errors> </Endpoint> Downloads go through the account only. A guest order has no file endpoint, so a store that sells digital products asks buyers to create an account, or sends the files another way. When the files move to another disk with the `shopper:files:secure` command, each file gets a new `id`. Read the order again rather than reusing a file `id` stored earlier. ## Next Steps [#next-steps] The order pages build on the account of the customer and on the error codes shared by every endpoint. <Cards> <Card title="Customers" href="/3.x/store-api/customers"> Manage the profile and the saved addresses of the account. </Card> <Card title="Errors" href="/3.x/store-api/errors"> Every error code the Store API returns, and what the client should do. </Card> <Card title="Webhooks" href="/3.x/webhooks"> Send shipping emails with the shipment ID when a package moves. </Card> </Cards> # Store and Regions (/3.x/store-api/store) A storefront needs the identity of the shop on every page (its name, logo and contact details), the legal pages for the footer and the checkout, and the regions it sells to. The region matters most: the zone of a request decides the currency of every price the catalog and the cart return. These endpoints are public and read-only. They answer `GET` requests without a customer token, and the responses follow the [JSON:API conventions](/3.x/store-api/json-api), except where this page says otherwise. ## Endpoints [#endpoints] All these routes sit in the public route group. A show endpoint answers `404` with the code `not_found` for a record that does not exist or that the merchant disabled. <Routes> <Route method="GET" path="/store/settings" href="#get-store-settings">Read the public store settings</Route> <Route method="GET" path="/store/legals" href="#get-store-legals">List the enabled legal pages</Route> <Route method="GET" path="/store/legals/{slug}" href="#get-store-legals-slug">Read one legal page</Route> <Route method="GET" path="/store/countries" href="#get-store-countries">List countries</Route> <Route method="GET" path="/store/countries/{code}" href="#get-store-countries-code">Read one country by its two-letter or three-letter ISO code</Route> <Route method="GET" path="/store/zones" href="#get-store-zones">List the enabled zones</Route> <Route method="GET" path="/store/zones/{code}" href="#get-store-zones-code">Read one zone by its code</Route> <Route method="GET" path="/store/currencies" href="#get-store-currencies">List the enabled currencies</Route> <Route method="GET" path="/store/currencies/{code}" href="#get-store-currencies-code">Read one currency by its ISO code</Route> </Routes> ## Reading the Store Settings [#reading-the-store-settings] The header, the footer and the contact page show the shop name, the logo, the address and the social links. <Endpoint id="get-store-settings" method="GET" path="/store/settings" auth="public"> <Params title="Query parameters"> <Field name="fields[settings]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> `/store/settings` returns them in one call, along with the default currency and the languages of the shop: ```bash title="Request" curl http://localhost:8000/store/settings \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with a single `settings` resource whose `id` is always `store`: ```json title="Response 200" { "data": { "id": "store", "type": "settings", "attributes": { "name": "Classic Apparel", "legal_name": "Classic Apparel LLC", "about": "<p>Organic cotton basics, made to last.</p>", "email": "hello@classic-apparel.com", "phone_number": "+33142685300", "street_address": "12 Rue de la Paix", "city": "Paris", "postal_code": "75002", "state": null, "country": { "code": "FR", "name": "France" }, "logo": { "url": "https://classic-apparel.com/storage/01JD8XQ6S9W3T4N5V6B7C8D9EF.png" }, "cover": null, "social_links": [ { "platform": "instagram", "url": "https://instagram.com/classicapparel", "label": "Instagram" } ], "default_currency": "EUR", "currencies": ["EUR", "USD"], "default_locale": "en", "supported_locales": [ { "code": "en", "label": "English" }, { "code": "fr", "label": "Français" } ] } } } ``` The endpoint returns only the keys listed under `settings.expose` in `config/shopper/api.php`, because the same table holds keys meant for the admin panel only. A key the merchant never filled in comes back as `null`. Some keys come back in a shape a storefront can use directly: <Attributes title="settings attributes"> <Field name="name" type="string, null"> The shop name, as entered in the admin panel. </Field> <Field name="legal_name" type="string, null"> The legal name of the business, as entered in the admin panel. </Field> <Field name="about" type="string, null"> The shop description, as entered in the admin panel. HTML. </Field> <Field name="email" type="string, null"> The contact email, as entered in the admin panel. </Field> <Field name="phone_number" type="string, null"> The contact phone number, as entered in the admin panel. </Field> <Field name="street_address" type="string, null"> The street of the shop address. </Field> <Field name="city" type="string, null"> The city of the shop address. </Field> <Field name="postal_code" type="string, null"> The postal code of the shop address. </Field> <Field name="state" type="string, null"> The state or region of the shop address. </Field> <Field name="country" type="object, null"> The shop country. <Field name="code" type="string"> ISO 3166-1 alpha-2 code, such as `FR`. </Field> <Field name="name" type="string"> Name of the country, in the language of the request. </Field> </Field> <Field name="logo" type="object, null"> The shop logo, or `null`. <Field name="url" type="string"> Absolute URL of the image. </Field> </Field> <Field name="cover" type="object, null"> The cover image of the shop, or `null`. <Field name="url" type="string"> Absolute URL of the image. </Field> </Field> <Field name="social_links" type="array"> The social links of the shop. Links with an unknown platform or an empty URL are left out. <Field name="platform" type="string"> The platform, such as `instagram`. </Field> <Field name="url" type="string"> The link to the shop page on that platform. </Field> <Field name="label" type="string"> The label of the platform, such as `Instagram`. </Field> </Field> <Field name="default_currency" type="string"> The code of the default currency of the shop. </Field> <Field name="currencies" type="array"> The codes of the currencies the merchant sells in, sorted by currency name. Disabled currencies are left out. </Field> <Field name="default_locale" type="string"> The language the response is written in. </Field> <Field name="supported_locales" type="array"> The languages of the shop. <Field name="code" type="string"> The locale code, such as `fr`. </Field> <Field name="label" type="string"> The name of the language, such as `Français`. </Field> </Field> </Attributes> </Endpoint> The [Settings](/3.x/settings#store-api) page explains how to expose a setting of your own. ### Caching the Settings [#caching-the-settings] A storefront reads the settings on nearly every page render, so the response is built to be cached by the browser, a CDN or your own server. It is public, with `max-age` and `s-maxage` set to `settings.max_age` in `config/shopper/api.php` (300 seconds by default), and it carries an `ETag` and `Vary: Accept-Language`. To revalidate a cached copy, send its ETag back in `If-None-Match`: ```bash title="Request" curl -i http://localhost:8000/store/settings \ -H "Accept: application/vnd.api+json" \ -H 'If-None-Match: "5d41c7a2e9b04f1d8c3e6a7b2f9d0e14"' ``` While nothing changed, the API answers `304 Not Modified` with an empty body, and the storefront keeps its copy. A change the merchant makes in the admin panel reaches visitors at most `max_age` seconds later, once every cache has expired its copy. ### Language [#language] The `Accept-Language` header picks the language of the response among the `supported_locales`, which come from `locales` in `config/shopper/admin.php`. A language the shop does not support falls back to the first locale of that list, and a request without the header gets the default locale of the Laravel app. `default_locale` tells the storefront which language it got. The language changes the country names: `country.name` in the settings, and `translated_name` on [countries](#countries). A storefront that shows a language switcher sends the visitor's choice in `Accept-Language` on every request. ## Legal Pages [#legal-pages] The footer links to the refund, privacy, terms and shipping policies, and the checkout often asks the customer to accept the terms. Shopper creates four pages at install, with the slugs `refund`, `privacy`, `terms` and `shipping`, and the merchant writes their content in the admin panel. The API returns the enabled ones only. <Endpoint id="get-store-legals" method="GET" path="/store/legals" auth="public"> <Params title="Query parameters"> <Field name="filter[title]" type="string"> Pages whose title contains the value. </Field> <Field name="sort" type="string"> `title` or `updated_at`. Prefix with `-` for descending order. </Field> <Field name="page[size]" type="integer" default="15"> Legal pages per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> The page to return, from 1 to 100. </Field> <Field name="page[cursor]" type="string"> Switches to cursor pagination. An empty value returns the first page. </Field> <Field name="fields[legals]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> `/store/legals` lists them, for the footer links. It accepts `filter[title]` (partial match), `sort=title` or `sort=updated_at`, and the [pagination](/3.x/store-api/json-api#pagination) parameters. ```bash title="Request" curl -g "http://localhost:8000/store/legals?fields[legals]=title,slug" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the enabled pages, here with their `title` and `slug` only, and the pagination details: ```json title="Response 200" { "data": [ { "id": "1", "type": "legals", "attributes": { "title": "Refund policy", "slug": "refund" } }, { "id": "2", "type": "legals", "attributes": { "title": "Privacy policy", "slug": "privacy" } }, { "id": "3", "type": "legals", "attributes": { "title": "Terms of use", "slug": "terms" } }, { "id": "4", "type": "legals", "attributes": { "title": "Shipping policy", "slug": "shipping" } } ], "links": { "first": "http://localhost:8000/store/legals?fields%5Blegals%5D=title%2Cslug&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/legals?fields%5Blegals%5D=title%2Cslug&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/legals?fields%5Blegals%5D=title%2Cslug&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/legals", "per_page": 15, "to": 4, "total": 4 } } ``` <Errors> | Status | Code | When | |--------|------|------| | 400 | `bad_request` | A filter or sort outside the allowlist, or any `include` | | 422 | `filter_too_wide` | `filter[title]` with more than 50 values | </Errors> </Endpoint> <Endpoint id="get-store-legals-slug" method="GET" path="/store/legals/{slug}" auth="public"> <Params title="Path parameters"> <Field name="slug" type="string" required> The slug of the page, such as `refund`, `privacy`, `terms` or `shipping`. </Field> </Params> <Params title="Query parameters"> <Field name="fields[legals]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> To render one page, read it by slug: ```bash title="Request" curl http://localhost:8000/store/legals/privacy \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the page: ```json title="Response 200" { "data": { "id": "2", "type": "legals", "attributes": { "title": "Privacy policy", "slug": "privacy", "content": "<p>We collect your name, email address and shipping address to process and deliver your orders.</p>", "updated_at": "2026-10-02T09:30:00+00:00" } } } ``` `content` is HTML, or `null` when the merchant has not written the page yet. `updated_at` is the date to show as "Last updated". A page the merchant disabled answers `404` with the code `not_found`, so a storefront hides the link instead of showing an empty page. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No enabled legal page with this slug | | 400 | `bad_request` | Any `include`: a legal page has no related resources | </Errors> </Endpoint> The [Legal](/3.x/legal#from-a-storefront) page covers how the merchant edits these pages. ## Countries [#countries] Address forms need a country list, and a storefront that guesses the visitor's region needs to know which zone a country belongs to. `/store/countries` returns every country of the world, about 250, whether or not the shop sells there. For the countries the shop sells to, read the countries of its [zones](#zones) instead. <Endpoint id="get-store-countries" method="GET" path="/store/countries" auth="public"> The listing is paginated, 15 countries per page by default and 100 at most. It accepts these parameters: <Params title="Query parameters"> <Field name="filter[name]" type="string"> Countries whose English name contains the value. </Field> <Field name="filter[cca2]" type="string"> Exact ISO 3166-1 alpha-2 code, such as `FR` or `US`. </Field> <Field name="filter[cca3]" type="string"> Exact ISO 3166-1 alpha-3 code, such as `FRA` or `USA`. </Field> <Field name="filter[region]" type="string"> Exact region, such as `Europe` or `Americas`. </Field> <Field name="filter[zone]" type="string"> Code of a zone the country belongs to, such as `EU`. Disabled zones match too. </Field> <Field name="sort" type="string"> `name`. Prefix with `-` for descending order. </Field> <Field name="include" type="string"> `zones`: the enabled zones the country belongs to. </Field> <Field name="page[size]" type="integer" default="15"> Countries per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> The page to return, from 1 to 100. </Field> <Field name="page[cursor]" type="string"> Switches to cursor pagination. An empty value returns the first page. </Field> <Field name="fields[countries]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="fields[zones]" type="string"> Attributes to keep on the included zones. </Field> </Params> This request lists the countries of Europe by name: ```bash title="Request" curl -g "http://localhost:8000/store/countries?filter[region]=Europe&sort=name" \ -H "Accept: application/vnd.api+json" ``` <Errors> | Status | Code | When | |--------|------|------| | 400 | `bad_request` | A filter, sort or include outside the allowlist | | 422 | `filter_too_wide` | A filter with more than 50 values | </Errors> </Endpoint> <Endpoint id="get-store-countries-code" method="GET" path="/store/countries/{code}" auth="public"> <Params title="Path parameters"> <Field name="code" type="string" required> ISO 3166-1 alpha-2 or alpha-3 code of the country, in any case, such as `US` or `usa`. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `zones`: the enabled zones the country belongs to. </Field> <Field name="fields[countries]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="fields[zones]" type="string"> Attributes to keep on the included zones. </Field> </Params> To read one country, pass its two-letter or three-letter ISO code in any case. This request reads the United States with its zones, in French: ```bash title="Request" curl -g "http://localhost:8000/store/countries/usa?include=zones&fields[countries]=name,translated_name,cca2,flag" \ -H "Accept: application/vnd.api+json" \ -H "Accept-Language: fr" ``` The API answers `200 OK` with the country and its zones in `included`: ```json title="Response 200" { "data": { "id": "01JD8X9C3D4E5F6G7H8J9K0M1N", "type": "countries", "attributes": { "name": "United States", "translated_name": "États-Unis", "cca2": "US", "flag": "http://localhost:8000/vendor/shopper/images/flags/us.svg" }, "relationships": { "zones": { "data": [ { "id": "01JD8XZ2F4H6K8M0Q2S4V6X8Z0", "type": "zones" } ] } } }, "included": [ { "id": "01JD8XZ2F4H6K8M0Q2S4V6X8Z0", "type": "zones", "attributes": { "name": "United States", "slug": "united-states", "code": "US", "currency_code": "USD", "metadata": null, "created_at": "2026-09-12T10:00:00+00:00", "updated_at": "2026-09-12T10:00:00+00:00" } } ] } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No country with this code | | 400 | `bad_request` | An `include` other than `zones` | </Errors> </Endpoint> A country carries `name` (the common English name), `translated_name` (the name in the language of the request, or the English name when no translation exists), `name_official`, `region`, `subregion`, `cca2`, `flag` (the URL of an SVG flag served by your app), `latitude` and `longitude`. The three-letter code works in the path and in `filter[cca3]`, but the resource does not return it. ## Zones [#zones] A zone is a region of the shop, such as "Europe" or "United States", with its own currency, carriers and payment methods. A storefront sends the code of the visitor's zone in the `X-Shopper-Zone` header, and the API prices the catalog and the cart for that zone. The [Zones](/3.x/zones#what-the-zone-changes) page lists everything a zone changes. <Endpoint id="get-store-zones" method="GET" path="/store/zones" auth="public"> The listing accepts these parameters: <Params title="Query parameters"> <Field name="filter[name]" type="string"> Zones whose name contains the value. </Field> <Field name="filter[code]" type="string"> Exact zone code, such as `EU` or `US`. </Field> <Field name="sort" type="string"> `name`. Prefix with `-` for descending order. </Field> <Field name="include" type="string"> `currency` and `countries`: the zone currency as a `currencies` resource, and every country of the zone. </Field> <Field name="page[size]" type="integer" default="15"> Zones per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> The page to return, from 1 to 100. </Field> <Field name="page[cursor]" type="string"> Switches to cursor pagination. An empty value returns the first page. </Field> <Field name="fields[zones]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> To match visitors to zones, list the enabled zones with their countries: ```bash title="Request" curl "http://localhost:8000/store/zones?include=countries" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with a page of zones, their countries in `included`, and the pagination details: ```json title="Response 200" { "data": [ { "id": "01JD8XZ1E3G5J7K9M1P3R5T7V9", "type": "zones", "attributes": { "name": "Europe", "slug": "europe", "code": "EU", "currency_code": "EUR", "metadata": null, "created_at": "2026-09-12T09:55:00+00:00", "updated_at": "2026-09-12T09:55:00+00:00" }, "relationships": { "countries": { "data": [ { "id": "01JD8X9A1B2C3D4E5F6G7H8J9K", "type": "countries" }, { "id": "01JD8X9B2C3D4E5F6G7H8J9K0M", "type": "countries" } ] } } }, { "id": "01JD8XZ2F4H6K8M0Q2S4V6X8Z0", "type": "zones", "attributes": { "name": "United States", "slug": "united-states", "code": "US", "currency_code": "USD", "metadata": null, "created_at": "2026-09-12T10:00:00+00:00", "updated_at": "2026-09-12T10:00:00+00:00" }, "relationships": { "countries": { "data": [ { "id": "01JD8X9C3D4E5F6G7H8J9K0M1N", "type": "countries" } ] } } } ], "links": { "first": "http://localhost:8000/store/zones?include=countries&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/zones?include=countries&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/zones?include=countries&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/zones", "per_page": 15, "to": 2, "total": 2 }, "included": [ { "id": "01JD8X9A1B2C3D4E5F6G7H8J9K", "type": "countries", "attributes": { "name": "France", "translated_name": "France", "name_official": "French Republic", "region": "Europe", "subregion": "Western Europe", "cca2": "FR", "flag": "http://localhost:8000/vendor/shopper/images/flags/fr.svg", "latitude": 46, "longitude": 2 } }, { "id": "01JD8X9B2C3D4E5F6G7H8J9K0M", "type": "countries", "attributes": { "name": "Germany", "translated_name": "Germany", "name_official": "Federal Republic of Germany", "region": "Europe", "subregion": "Western Europe", "cca2": "DE", "flag": "http://localhost:8000/vendor/shopper/images/flags/de.svg", "latitude": 51, "longitude": 9 } }, { "id": "01JD8X9C3D4E5F6G7H8J9K0M1N", "type": "countries", "attributes": { "name": "United States", "translated_name": "United States", "name_official": "United States of America", "region": "Americas", "subregion": "North America", "cca2": "US", "flag": "http://localhost:8000/vendor/shopper/images/flags/us.svg", "latitude": 38, "longitude": -97 } } ] } ``` `code` is the value to send in `X-Shopper-Zone`. `currency_code` is the code of the zone currency, or `null` when the merchant disabled that currency; prices then fall back to the default currency of the shop. `metadata` holds your own data. The listing does not accept a fieldset for the included countries: `fields[countries]` answers `400 Bad Request`, so each country comes with all its attributes. <Errors> | Status | Code | When | |--------|------|------| | 400 | `bad_request` | A filter, sort or include outside the allowlist | | 422 | `filter_too_wide` | A filter with more than 50 values | </Errors> </Endpoint> <Endpoint id="get-store-zones-code" method="GET" path="/store/zones/{code}" auth="public"> <Params title="Path parameters"> <Field name="code" type="string" required> The zone code, such as `EU`. </Field> </Params> <Params title="Query parameters"> <Field name="include" type="string"> `currency` and `countries`: the zone currency as a `currencies` resource, and every country of the zone. </Field> <Field name="fields[zones]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> <Field name="fields[currencies]" type="string"> Attributes to keep on the included currency. </Field> <Field name="fields[countries]" type="string"> Attributes to keep on the included countries. </Field> </Params> To read one zone, pass its code in the path, such as `/store/zones/EU`. Unlike countries and currencies, the API does not uppercase a zone code, so send it exactly as the merchant wrote it. ```bash title="Request" curl "http://localhost:8000/store/zones/EU?include=currency" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the zone and its currency in `included`: ```json title="Response 200" { "data": { "id": "01JD8XZ1E3G5J7K9M1P3R5T7V9", "type": "zones", "attributes": { "name": "Europe", "slug": "europe", "code": "EU", "currency_code": "EUR", "metadata": null, "created_at": "2026-09-12T09:55:00+00:00", "updated_at": "2026-09-12T09:55:00+00:00" }, "relationships": { "currency": { "data": { "id": "01JD8X8E1R2T3V4W5X6Y7Z8A9B", "type": "currencies" } } } }, "included": [ { "id": "01JD8X8E1R2T3V4W5X6Y7Z8A9B", "type": "currencies", "attributes": { "name": "Euro", "code": "EUR", "symbol": "€", "format": "1.0,00 €", "exchange_rate": 0 } } ] } ``` A disabled zone answers `404`. <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No enabled zone with this code | | 400 | `bad_request` | An `include` other than `currency` and `countries` | </Errors> </Endpoint> ## Currencies [#currencies] A currency switcher needs the codes the shop sells in, and a price label needs the symbol of the currency. The codes come from `currencies` in the [settings](#reading-the-store-settings). `/store/currencies` returns every enabled currency, and Shopper enables all 158 currencies at install, so the listing holds far more codes than the shop sells in. <Endpoint id="get-store-currencies" method="GET" path="/store/currencies" auth="public"> <Params title="Query parameters"> <Field name="filter[name]" type="string"> Currencies whose name contains the value. </Field> <Field name="filter[code]" type="string"> Exact ISO code, comma-separated for several, such as `EUR,USD`. </Field> <Field name="sort" type="string"> `name` or `code`. Prefix with `-` for descending order. </Field> <Field name="page[size]" type="integer" default="15"> Currencies per page, from 1 to 100. </Field> <Field name="page[number]" type="integer" default="1"> The page to return, from 1 to 100. </Field> <Field name="page[cursor]" type="string"> Switches to cursor pagination. An empty value returns the first page. </Field> <Field name="fields[currencies]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> A cart accepts only the codes of the settings and answers `422` for any other, so filter the listing by those codes: ```bash title="Request" curl -g "http://localhost:8000/store/currencies?filter[code]=EUR,USD" \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with a page of currencies: ```json title="Response 200" { "data": [ { "id": "01JD8X8E1R2T3V4W5X6Y7Z8A9B", "type": "currencies", "attributes": { "name": "Euro", "code": "EUR", "symbol": "€", "format": "1.0,00 €", "exchange_rate": 0 } }, { "id": "01JD8X8D1S2T3V4W5X6Y7Z8A9C", "type": "currencies", "attributes": { "name": "US Dollar", "code": "USD", "symbol": "$", "format": "$1,0.00", "exchange_rate": 0 } } ], "links": { "first": "http://localhost:8000/store/currencies?filter%5Bcode%5D=EUR%2CUSD&page%5Bnumber%5D=1", "last": "http://localhost:8000/store/currencies?filter%5Bcode%5D=EUR%2CUSD&page%5Bnumber%5D=1", "prev": null, "next": null }, "meta": { "current_page": 1, "from": 1, "last_page": 1, "links": [ { "url": null, "label": "« Previous", "page": null, "active": false }, { "url": "http://localhost:8000/store/currencies?filter%5Bcode%5D=EUR%2CUSD&page%5Bnumber%5D=1", "label": "1", "page": 1, "active": true }, { "url": null, "label": "Next »", "page": null, "active": false } ], "path": "http://localhost:8000/store/currencies", "per_page": 15, "to": 2, "total": 2 } } ``` `format` is the display pattern stored with the currency. `exchange_rate` is the rate the merchant entered, and the API never uses it: every price comes from an amount the merchant set in that currency. To format amounts in the browser, the [Money](/3.x/money#formatting-in-javascript) page shows how to use `Intl.NumberFormat` with the currency code. The listing accepts `filter[name]` (partial match), `filter[code]` (exact, comma-separated for several), `sort=name` or `sort=code`, and the pagination parameters. <Errors> | Status | Code | When | |--------|------|------| | 400 | `bad_request` | A filter or sort outside the allowlist, or any `include` | | 422 | `filter_too_wide` | A filter with more than 50 values | </Errors> </Endpoint> <Endpoint id="get-store-currencies-code" method="GET" path="/store/currencies/{code}" auth="public"> <Params title="Path parameters"> <Field name="code" type="string" required> ISO 4217 code of the currency, in any case, such as `EUR` or `eur`. </Field> </Params> <Params title="Query parameters"> <Field name="fields[currencies]" type="string"> Comma-separated attributes to keep, as described in [Sparse fieldsets](/3.x/store-api/json-api#sparse-fieldsets). </Field> </Params> `/store/currencies/{code}` reads one currency, with the code in any case, and answers `404` for a disabled one. ```bash title="Request" curl http://localhost:8000/store/currencies/eur \ -H "Accept: application/vnd.api+json" ``` The API answers `200 OK` with the currency: ```json title="Response 200" { "data": { "id": "01JD8X8E1R2T3V4W5X6Y7Z8A9B", "type": "currencies", "attributes": { "name": "Euro", "code": "EUR", "symbol": "€", "format": "1.0,00 €", "exchange_rate": 0 } } } ``` <Errors> | Status | Code | When | |--------|------|------| | 404 | `not_found` | No enabled currency with this code | | 400 | `bad_request` | Any `include`: a currency has no related resources | </Errors> </Endpoint> The [Currencies](/3.x/currencies#from-a-storefront) page covers how the merchant enables currencies. ## Picking a Zone and a Currency [#picking-a-zone-and-a-currency] The API never guesses where a visitor is. The storefront decides the zone, sends it with every request, and the API prices everything for it. A typical flow on the first visit: <Steps> <Step title="Read the store settings"> Call `/store/settings` once and cache it. `default_currency` is the currency of a visitor outside every zone, and `currencies` lists the codes for a currency switcher. </Step> <Step title="Load the zones and their countries"> Call `/store/zones?include=countries` and keep a map from each country code (`cca2`) to its zone `code`. Add `page[size]=100` when the shop has more than 15 zones. Zones change rarely, so cache the map with the settings. </Step> <Step title="Find the visitor's country"> Take the country from your CDN or hosting provider's geolocation header, from a country selector, or from the shipping address of a returning customer. Look it up in the map. A country outside every zone gets no zone, and a cart without a zone answers `422` when it asks for shipping options, so send the default zone or tell the visitor the shop does not deliver to their country. </Step> <Step title="Send the zone with every request"> Send the zone code in `X-Shopper-Zone` on every catalog and cart request, and store it in a cookie so the next visit skips the lookup: ```bash title="Request" curl http://localhost:8000/store/products \ -H "Accept: application/vnd.api+json" \ -H "X-Shopper-Zone: US" ``` Prices then come in the zone currency, and `meta.currency` confirms it: `USD` for this request. Every response lists `X-Shopper-Zone` in `Vary`, so a shared cache keeps one copy per zone. </Step> <Step title="Let the visitor switch currency"> To show prices in another currency of the shop without changing the zone, add `filter[currency]` to the catalog requests, as described in [Prices, currency and stock](/3.x/store-api/catalog). The cart takes its own currency, set when it is created or updated: see [Cart](/3.x/store-api/cart). </Step> </Steps> The API does not reject a zone code it cannot find. An unknown or disabled code falls back to the default zone, whose code is set in `SHOPPER_API_DEFAULT_ZONE`, or to no zone at all when that variable is empty, and prices then come in the default currency of the shop. A typo in the header therefore shows the wrong currency instead of an error: compare `meta.currency` with the currency you expect while you build the storefront. The API caches each zone it resolves, with its currency, for 60 seconds (`zone.cache_ttl` in `config/shopper/http.php`), and clears that cache when the zone is saved or deleted. A change to the currency itself, such as disabling it, can take up to a minute to reach the API. A cart created with `X-Shopper-Zone` keeps that zone and takes its currency, unless the request sets another `currency_code`. The sales channel works the same way through the `X-Shopper-Channel` header, and decides which products the catalog returns. See [Request headers](/3.x/store-api#request-headers) and the [Channels](/3.x/channels#the-store-api) page. The [Zones](/3.x/zones#resolving-a-zone) page covers the resolution order and the `zone` settings of `config/shopper/http.php`, including the `resolver` class you can replace with your own. ## Next Steps [#next-steps] With the zone and the currency in place, the storefront can list products and fill a cart with the right prices. <Cards> <Card title="Catalog" href="/3.x/store-api/catalog"> List and filter products, and read categories, brands and reviews. </Card> <Card title="Cart" href="/3.x/store-api/cart"> Create a cart in the visitor's zone and currency. </Card> </Cards> # Storefront (/3.x/storefront) The storefront is the customer side of a Shopper store: the pages where customers browse products, fill a cart, pay and follow their orders. Shopper ships the admin panel and the commerce models, and leaves the storefront to you. You build it in one of two places: inside the Laravel application that runs Shopper, or as a separate front end that calls the Store API. ## Choosing an Approach [#choosing-an-approach] A storefront inside your Laravel application renders its pages with Blade, Livewire or Inertia and reads the Shopper models directly in PHP. One application serves the admin panel and the store, and customers log in with a Laravel session. The fastest way to start is a [starter kit](/3.x/starter-kits), a complete storefront that the installer copies into your application. A separate front end runs on its own server or device, such as a Next.js or Nuxt site or a mobile app. It reads and writes everything through the [Store API](/3.x/store-api), an HTTP API that the `shopper/api` package adds to your Laravel application. Customers log in with a bearer token, and you deploy the front end apart from the Laravel application that serves the admin panel and the API. | | Inside Laravel | Separate front end | |---|---|---| | Built with | Blade, Livewire, or Inertia with React or Vue | Any framework or platform that sends HTTP requests | | Reads store data | Shopper models, in PHP | Store API, as JSON:API documents | | Customer login | Laravel session | Sanctum bearer token | | Deployment | One Laravel application | The Laravel application, plus the front end | | Starting point | A starter kit | The Store API guides and the JavaScript SDK | Start from a starter kit when your team works in Laravel and wants a store running quickly: the catalog, the cart, a Stripe checkout and the customer account are already written, and you change the code from there. Build on the Store API when the store has to run outside Laravel: a front end your team already builds in another framework, a mobile app, or several clients sharing the same catalog and carts. Both approaches work on the same data. A product published in the admin panel appears in a starter kit and on the Store API at once, and an order placed through either one shows in the admin panel. ## Starter Kits [#starter-kits] Shopper maintains three starter kits. They cover the same pages (home, catalog, product, cart, checkout with Stripe, customer account) and differ in their front-end stack. The [Starter Kits](/3.x/starter-kits) page explains how the installer works and how to build a kit of your own. <Cards className="@lg:grid-cols-3"> <Card title="Livewire" href="/3.x/livewire-starter-kit"> Livewire components and Flux UI, rendered with Blade. </Card> <Card title="React" href="/3.x/react-starter-kit"> Inertia pages in React and TypeScript, with shadcn/ui. </Card> <Card title="Vue" href="/3.x/vue-starter-kit"> Inertia pages in Vue and TypeScript, with shadcn-vue. </Card> </Cards> ## Store API [#store-api] The Store API serves the catalog, carts, checkout, customer accounts and orders. A visitor browses and checks out as a guest without credentials; a customer account adds saved addresses, an order history and carts that follow the customer across devices. The [JavaScript SDK](/3.x/sdk), `@shopperlabs/shopper-sdk`, wraps the API in a typed client for front ends written in JavaScript or TypeScript. <Cards> <Card title="Store API" href="/3.x/store-api"> Install the API, then read its base URL, route groups, headers and rate limits. </Card> <Card title="Authentication" href="/3.x/store-api/authentication"> Register and log in customers, and send their bearer token. </Card> <Card title="Checkout" href="/3.x/store-api/checkout"> Choose shipping and payment, open a payment session and turn the cart into an order. </Card> <Card title="JavaScript SDK" href="/3.x/sdk"> Install the typed client and call the catalog, the cart and the checkout from JavaScript. </Card> </Cards> # Vue Starter Kit (/3.x/vue-starter-kit) The Vue Starter Kit is a storefront for Shopper built with [Inertia](https://inertiajs.com/) and [Vue 3](https://vuejs.org/). Laravel controllers query the Shopper models and pass the data to Vue pages as Inertia props, so the kit does not go through the [Store API](/3.x/store-api) and there is no separate API layer to maintain. The interface uses [shadcn-vue](https://www.shadcn-vue.com/) components and [Tailwind CSS v4](https://tailwindcss.com/), and [Laravel Wayfinder](https://github.com/laravel/wayfinder) and a PHP-to-TypeScript transformer give the pages typed routes and typed data. The kit is installed once, with the [starter kit installer](/3.x/starter-kits#how-it-works). Every file it copies belongs to your project afterwards. ## Prerequisites [#prerequisites] The installer checks the PHP, Laravel and Shopper versions of the kit's manifest before it copies anything, and the kit's Vite version needs the Node.js versions below. Shopper must already be [installed](/3.x/installation) in the application. | Requirement | Version | |-------------|---------| | PHP | 8.3+ | | Laravel | 12.68+ or 13.27+ | | Shopper | 3.0+ | | Node.js | 20.19+ or 22.12+ | ## Installation [#installation] Run the installer in a Laravel application where Shopper is installed, with the package name of the kit. [Installing a Starter Kit](/3.x/starter-kits#installing-a-starter-kit) lists the steps from a new Laravel application. ```bash php artisan shopper:kit:install shopperlabs/vue-starter-kit ``` The installer downloads the kit, reads its [manifest](/3.x/starter-kits/creating#the-manifest) and copies the storefront files into your project. On a new Laravel application, the kit replaces 14 files of the skeleton, such as `routes/web.php`, `bootstrap/app.php`, `app/Models/User.php`, `package.json`, `resources/css/app.css` and `config/shopper/models.php`, and the installer asks before overwriting each of them. It then installs these Composer packages: | Package | Purpose | |---------|---------| | `inertiajs/inertia-laravel` | Inertia server-side adapter for Laravel | | `laravel/fortify` | Authentication backend (login, register, password reset, two-factor authentication) | | `laravel/wayfinder` | Typed route functions generated from your routes | | `spatie/laravel-typescript-transformer` | TypeScript types generated from the PHP DTOs | | `shopper/stripe` | Stripe payment driver | It also installs `laravel/boost` and `laravel/pao` as development dependencies. Once you confirm them, the installer runs the kit's post-install commands: `php artisan migrate`, `php artisan storage:link`, `npm install` and `npm run build`. It then writes a `.shopper-kit` file that lists every copied file and removes the kit package from your `composer.json`. ## First Run [#first-run] Start the development server from the root of your project: ```bash php artisan serve ``` The home page, the catalog, the categories, the search, the cart and the login and register pages answer at `http://localhost:8000`. The checkout, account and settings pages send guests to the login page. The post-install commands built the assets once. While you work on the Vue pages, run Vite in a second terminal, so the browser reloads each change and Wayfinder regenerates the route functions when you add a route: ```bash npm run dev ``` Run `npm run build` again before you deploy. ### Store Data [#store-data] A new store has no products, so every listing renders empty until you add a catalog. Sign in to the [admin panel](/3.x/installation#access-the-admin-panel), complete the [setup wizard](/3.x/setup-store#setup-wizard), then create the data a purchase goes through: 1. A [zone](/3.x/zones) with the countries you sell to and their [currency](/3.x/currencies), such as a North America zone with the United States and Canada in USD. Enable a payment method on it, such as the cash on delivery method that Shopper seeds, and a [carrier](/3.x/carriers) with at least one shipping option, such as "Standard shipping" at `500` cents. 2. A [category](/3.x/categories) for the storefront navigation. 3. A [product](/3.x/products) that is published, with a price in the zone's currency and stock in an [inventory location](/3.x/locations). A canvas tote bag at `2500` cents ($25.00) works. Mark it as featured to show it on the home page. With this data, a customer picks the United States in the country dialog that opens on their first visit, adds two tote bags to the cart, registers, and checks out with cash on delivery: the two bags and the standard shipping make an order of `5500` cents. ### Stripe [#stripe] The installer added the `shopper/stripe` package, and the payment step of the kit's checkout renders the Stripe Payment Element. Add the keys of your Stripe account to `.env`, using the test keys while you build the store: ```bash title=".env" STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... ``` Until the secret key and the webhook secret are set, the checkout does not list the payment methods that use Stripe. Manual methods, such as cash on delivery, work without any key. The payment step reads the publishable key to load the Payment Element. [Configuration](/3.x/payments/stripe#configuration) describes each variable, and [Payment Method Setup](/3.x/payments/stripe#payment-method-setup) shows how to create a Stripe payment method and enable it on your zones. ## Project Structure [#project-structure] The starter kit publishes files into standard Laravel directories. Here is the structure it adds to your project. ```text app/ ├── Actions/ │ ├── Cart/ │ │ └── AddToCart.php │ ├── Checkout/ │ │ ├── BuildShippingPackages.php │ │ ├── CompleteCheckout.php │ │ ├── CreatePaymentSession.php │ │ ├── FetchDeliveryRates.php │ │ └── FetchPaymentMethods.php │ ├── Fortify/ │ │ ├── CreateNewUser.php │ │ └── ResetUserPassword.php │ ├── Product/ │ │ ├── BuildVariantOptions.php │ │ └── ResolveVariantAvailability.php │ ├── GetCountriesByZone.php │ └── ZoneSessionManager.php ├── Concerns/ │ ├── InteractsWithStorefrontMedia.php │ ├── PasswordValidationRules.php │ └── ProfileValidationRules.php ├── DTO/ │ ├── AddressData.php │ ├── CountryByZoneData.php │ ├── PriceData.php │ └── ProductReviewsData.php ├── Exceptions/ │ └── CheckoutException.php ├── Http/ │ ├── Controllers/ │ │ ├── Account/ │ │ ├── Settings/ │ │ ├── Shop/ │ │ ├── PaymentWebhookController.php │ │ └── StripeReturnController.php │ ├── Middleware/ │ │ ├── HandleAppearance.php │ │ └── HandleInertiaRequests.php │ └── Requests/Settings/ ├── Models/ │ ├── Category.php │ ├── Channel.php │ ├── Collection.php │ ├── Product.php │ ├── ProductVariant.php │ └── User.php ├── Providers/ │ ├── AppServiceProvider.php │ ├── FortifyServiceProvider.php │ └── TypeScriptTransformerServiceProvider.php ├── Traits/ │ └── HasProductPricing.php └── helpers.php resources/js/ ├── components/ │ ├── account/ │ ├── shop/ │ └── ui/ ├── composables/ ├── layouts/ ├── lib/ ├── pages/ │ ├── account/ │ ├── auth/ │ ├── settings/ │ ├── shop/ │ └── dashboard.vue ├── types/ └── app.ts routes/ ├── settings.php ├── web.php └── webhooks.php tests/ ├── Feature/Auth/ ├── Feature/Settings/ ├── Feature/Shop/ └── Unit/ ``` The `Account`, `Settings` and `Shop` controllers render the matching folders of `resources/js/pages`. The `components/shop` folder holds the product cards, the price display, the zone selector and the Stripe form, and `components/ui` the shadcn-vue primitives. The `composables` folder holds `useCart`, `useShop`, `useStripeElements` and `useAppearance`, among others. ## Routing [#routing] The starter kit defines the storefront routes in `routes/web.php`, the account settings routes in `routes/settings.php` and the payment webhook route in `routes/webhooks.php`. Each page is rendered by a controller that returns an Inertia response, and every route is named so your Vue components can call it through Wayfinder. ### Public Routes [#public-routes] These routes are open to guests. | Route | Controller | Description | |-------|-----------|-------------| | `GET /` | `Shop\HomeController` | Homepage with featured collections, products, and categories | | `GET /shop` | `Shop\ProductController@index` | Product catalog with search, a category filter and sorting | | `GET /shop/{product:slug}` | `Shop\ProductController@show` | Product detail with variant selection | | `GET /categories` | `Shop\CategoryController@index` | All categories | | `GET /categories/{category:slug}` | `Shop\CategoryController@show` | Products in a category | | `GET /collections/{collection:slug}` | `Shop\CollectionController@show` | Products in a collection | | `GET /search` | `Shop\SearchController` | Search products by name, from 2 characters | | `GET /cart` | `Shop\CartController@index` | Shopping cart | Cart mutations have their own endpoints, limited to 60 requests per minute: `POST /cart` adds a line, `PATCH /cart/{line}` updates a quantity, `DELETE /cart/{line}` removes a line, and `DELETE /cart` clears the cart. `POST /cart/coupon` applies a discount code, with at most 5 attempts per minute for each customer, and `DELETE /cart/coupon/{code}` removes it. `PATCH /zone` changes the country of the visitor, and `GET /search` answers 30 requests per minute. ### Authenticated Routes [#authenticated-routes] These routes require the user to be logged in. They also carry Laravel's `verified` middleware, which only checks the email address when the `User` model implements `MustVerifyEmail`. The kit's model does not, so a customer can check out right after registering. The profile settings page requires the login only. | Route | Controller | Description | |-------|-----------|-------------| | `GET /checkout` | `Shop\CheckoutController@index` | Multi-step checkout flow | | `GET /checkout/stripe-return` | `StripeReturnController` | Return URL of a Stripe payment, creates the order | | `GET /checkout/success/{order}` | `Shop\CheckoutSuccessController` | Order confirmation | | `GET /account/orders` | `Account\OrderController@index` | Order history | | `GET /account/orders/{order}` | `Account\OrderController@show` | Order detail | | `GET /account/addresses` | `Account\AddressController@index` | Address management | | `GET /dashboard` | Inertia page | Page Fortify redirects to after a login with no page to return to | | `GET /settings/profile` | `Settings\ProfileController@edit` | Profile settings | | `GET /settings/appearance` | Inertia page | Light and dark appearance | | `GET /settings/security` | `Settings\SecurityController@edit` | Password and two-factor authentication, after the password confirmation | The checkout posts each step to its own endpoint: `checkout/shipping-address`, `checkout/shipping-option`, `checkout/prepare-payment` and `checkout/place-order`. Payment providers send their webhooks to `POST /webhooks/{driver}`, such as `/webhooks/stripe`, limited to 300 requests per minute. `bootstrap/app.php` loads this route outside the `web` middleware group, so it has no session and no CSRF check. ## Architecture [#architecture] The starter kit separates business logic in Action classes, data structures in DTOs, HTTP handling in controllers, and the interface in Vue components. You can change one part of the storefront without touching the others. ### Actions [#actions] Actions are single-responsibility classes that hold the business logic. They are resolved from the container, so you can swap an implementation or add dependencies to it. Each one receives the product, the cart or the zone it works on: ```php use App\Actions\Cart\AddToCart; use App\Actions\Checkout\CompleteCheckout; use App\Actions\Checkout\FetchDeliveryRates; resolve(AddToCart::class)->handle($product, $variant, quantity: 2); resolve(FetchDeliveryRates::class)->handle($cart); resolve(CompleteCheckout::class)->handle($cart); ``` The checkout uses five actions. | Action | Responsibility | |--------|---------------| | `BuildShippingPackages` | Packs the cart lines into one package, with their total weight and the largest dimensions, for carrier rate requests | | `FetchDeliveryRates` | Quotes the carriers of the cart's zone and keeps the options in the cart's currency, with a warning for each carrier that fails | | `FetchPaymentMethods` | Lists the payment methods enabled on a zone that the storefront can check out with: manual methods and Stripe | | `CreatePaymentSession` | Opens a payment session with the provider for the cart total, or resumes the open one when the amount and currency are unchanged | | `CompleteCheckout` | Turns the cart into an order | `CompleteCheckout` checks that the payment method is still available on the zone, quotes the delivery option again, and refuses the order when the option is gone or its price went up. It then converts the cart into an order and records the initiated payment. Called again on the same cart, it returns the order it already created, so a double submit or a refreshed Stripe return never creates two orders. ### DTOs [#dtos] Data Transfer Objects give a typed shape to the data passed from the backend to the Vue pages. Each one carries the `#[TypeScript]` attribute, so the TypeScript Transformer turns it into a type your components can import. | DTO | Purpose | |-----|---------| | `AddressData` | Structured address data for forms and checkout | | `CountryByZoneData` | Selected zone and country (zone ID, code and name, country ID, name, code and flag, currency code) | | `PriceData` | Price with its comparison price and discount percentage | | `ProductReviewsData` | Product reviews with the average rating and the review count | ### Controllers [#controllers] Each storefront page is rendered by a controller in `app/Http/Controllers/`. Controllers query the Shopper models and return an Inertia response that renders the matching page component. The `show` method of the product page returns a 404 for an unpublished product, then loads the brand, the media, the related products and the variants, each with its prices in the current currency, before it renders `shop/product`: ```php title="app/Http/Controllers/Shop/ProductController.php" $currencyCode = current_currency(); $priceConstraint = fn ($q) => $q->whereRelation('currency', 'code', $currencyCode); $product->load([ 'brand', 'media', 'prices' => $priceConstraint, 'relatedProducts.brand', 'relatedProducts.media', 'relatedProducts.prices' => $priceConstraint, 'variants.media', 'variants.values.attribute', 'variants.prices' => $priceConstraint, ]); ``` To change what a page receives, edit its controller. To change how it looks, edit the matching page component in `resources/js/pages/`. ### Inertia Shared Data [#inertia-shared-data] The `HandleInertiaRequests` middleware shares data with every page, so your components can read the authenticated user and the current shop state without fetching them. The `shop` prop carries the cart count, the selected zone, the active currency, the enabled channels, the countries a visitor can pick, the tax label, and the categories of the header and footer navigation. ```php title="app/Http/Middleware/HandleInertiaRequests.php" return [ 'cart_count' => $cart?->lines->sum('quantity') ?? 0, 'zone' => $zone ? [ 'country_code' => $zone->countryCode, 'country_name' => $zone->countryName, 'currency_code' => $zone->currencyCode, 'zone_id' => $zone->zoneId, ] : null, 'currency' => current_currency(), 'channels' => Channel::query() ->scopes('enabled') ->select('id', 'name', 'slug') ->get() ->toArray(), 'available_zones' => fn (): array => resolve(GetCountriesByZone::class)->handle()->values()->toArray(), 'tax_label' => current_tax_label(), 'nav_categories' => $this->topCategories(4, 'nav'), 'footer_categories' => $this->topCategories(6, 'footer'), ]; ``` On the frontend, the `useShop` composable reads this shared data and changes the country with `changeZone`, and `useCart` exposes the `add`, `update`, `remove` and `clear` cart actions. ### Models [#models] The starter kit publishes models that extend the Shopper models. `Category`, `Channel`, `Collection`, `Product` and `ProductVariant` are registered in `config/shopper/models.php`, so that Shopper and its admin panel use them too. The kit also ships its own `User` model. ```php title="app/Models/Product.php" namespace App\Models; use App\Concerns\InteractsWithStorefrontMedia; use App\Traits\HasProductPricing; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Shopper\Models\Product as Model; final class Product extends Model { use HasProductPricing; use InteractsWithStorefrontMedia; #[Scope] protected function withCurrentPrices(Builder $query): Builder { return $query->with([ 'prices' => fn ($q) => $q->whereRelation('currency', 'code', current_currency())->with('currency'), ]); } } ``` `HasProductPricing` resolves the price of a product or variant in the current currency, for the logged-in customer and the selected zone. The `withCurrentPrices` scope loads only the prices in the current currency, for the listings. The `InteractsWithStorefrontMedia` trait appends `thumbnail` and `images` attributes to every JSON response, so your Vue components receive media URLs ready to render. ### Helpers [#helpers] The `app/helpers.php` file defines four global functions used across the storefront. | Function | Purpose | |----------|---------| | `cartSession()` | Returns the current cart or creates one with the active currency, the default channel and the selected zone | | `current_currency()` | Returns the currency code for the selected zone, or the store default from `shopper_currency()` | | `current_tax_label()` | Returns the tax label ("TTC" or "HT") from the tax zone of the selected country, or an empty string when no country is selected | | `cart_context()` | Returns the cart totals the pages display: subtotal, discount, tax, shipping and total, whether prices include tax, and the subtotal of each line | ### Type Safety [#type-safety] Three tools give your Vue components the shape of the backend data, so they never guess it. | Tool | What it provides | |------|------------------| | Wayfinder | Typed functions for the named routes and the controller actions, generated into `resources/js/routes` and `resources/js/actions` by its Vite plugin when the assets build | | TypeScript Transformer | TypeScript definitions of the PHP DTOs, written to `resources/js/types/generated.d.ts` | | `@shopperlabs/shopper-types` | Shared domain types (Address, Cart, Order, Product, Zone and more) published as an npm package | The `TypeScriptTransformerServiceProvider` configures the transformer. After you change a DTO, regenerate the types: ```bash php artisan typescript:transform ``` ## Checkout Flow [#checkout-flow] The checkout is a multi-step process handled by `CheckoutController`. Each step posts to its own endpoint, validates its data and saves it on the cart through Shopper's `CartManager`, so a customer who comes back to the checkout resumes at the step they reached. **Step 1 - Shipping Address.** The customer enters a new address or selects one of their saved addresses in the countries of their zone. The address is saved on the cart as the shipping and the billing address, with the country selected in the storefront. **Step 2 - Delivery Options.** `FetchDeliveryRates` builds the package with `BuildShippingPackages` and quotes the [carriers](/3.x/carriers) of the cart's zone for that address, from the default inventory location. The customer selects a delivery option. **Step 3 - Payment.** `FetchPaymentMethods` lists the [payment methods](/3.x/payments) enabled on the cart's zone. For a manual method, such as cash on delivery, placing the order runs `CompleteCheckout`, then starts the payment through Shopper's `PaymentProcessingService` and shows the confirmation page. For Stripe payments, choosing the method runs `CreatePaymentSession`, which opens a Stripe PaymentIntent for the cart total without creating an order, and the payment step renders the Stripe Payment Element through the `StripePaymentForm` component and the `useStripeElements` composable. Once Stripe confirms the payment, it sends the customer back to `/checkout/stripe-return`. The `StripeReturnController` retrieves the PaymentIntent and runs `CompleteCheckout` when the payment is authorized, captured or processing. When the order cannot be created, it cancels the authorization or refunds the capture. The payment status of the order comes from the provider's webhooks, which `PaymentWebhookController` hands to Shopper. The route answers `404` until the Stripe driver is configured. The [Stripe](/3.x/payments/stripe) page covers the keys and the [events](/3.x/payments/stripe#handled-events) to select for the endpoint `https://your-store.test/webhooks/stripe`. Keep the scheduler running, as described in [Run the Scheduler and a Queue Worker](/3.x/installation#run-the-scheduler-and-a-queue-worker): Shopper applies the events that arrived before their order existed on a schedule. ## Zones and Currency [#zones-and-currency] The starter kit uses Shopper's [zones](/3.x/zones) for multi-currency and regional pricing. The `ZoneSelector` component in the footer lets customers pick their country among the countries of the enabled zones. The `ZoneSessionManager` then stores the country code in the session and resolves it to a `CountryByZoneData` DTO with the zone, the country and its currency. Prices across the storefront follow the zone's currency through the shared `shop` prop. When a customer changes country, `ZoneSessionManager` moves the cart to the new zone. It removes the lines that have no price in the new currency and tells the customer, prices the other lines in the new currency, and resets the delivery option, the payment method and any open payment session. When no country is selected, the storefront uses the default currency of your store from `shopper_currency()`, and the cart has no zone, so the checkout offers no delivery option or payment method. The `current_tax_label()` helper reads the tax zone of the selected country to display "TTC" (tax-inclusive) or "HT" (tax-exclusive) next to prices. To let customers pick a country, create at least one enabled zone in the admin panel. ## Customization [#customization] Once installed, every file belongs to your project. The frontend lives in `resources/js` and the storefront logic in `app/`. These are the places you will change most often. ### Styling [#styling] All pages use shadcn-vue components and Tailwind CSS v4. The colors are CSS variables in `resources/css/app.css`: one set under `:root` for the light appearance and one under `.dark`. Change `--primary` in both to give the storefront your brand color. The UI primitives live in `resources/js/components/ui/`, the storefront components such as the product card in `resources/js/components/shop/`, and the header and footer in `resources/js/layouts/storefront/`. The kit's `components.json` configures the shadcn-vue CLI, so a component you add lands in `resources/js/components/ui/` next to the others: ```bash npx shadcn-vue@latest add switch ``` ### Pages [#pages] Each page is a Vue single-file component in `resources/js/pages/`. Edit a `.vue` file to change the layout or content of its page. To change the data a page receives, edit its controller in `app/Http/Controllers/`. Pages do not declare their layout: the `layout` callback of `resources/js/app.ts` picks it from the page name. | Page name | Layout | |-----------|--------| | `shop/*` | Storefront header and footer, from `layouts/storefront-layout.vue` | | `account/*` and `dashboard` | Storefront layout with the account navigation of `layouts/account-layout.vue` | | `settings/*` | Account layout with the settings navigation of `layouts/settings-sub-layout.vue` | | `auth/*` | Authentication layout, from `layouts/auth-layout.vue` | | Any other name | Sidebar application layout, from `layouts/app-layout.vue` | To give a group of pages another layout, add a case to that callback. ### Checkout [#checkout] The checkout actions live in `app/Actions/Checkout/`. Each one handles one concern, so you can change how shipping rates are calculated without touching the payment logic. The checkout page itself is `resources/js/pages/shop/checkout.vue`, and the Stripe form `resources/js/components/shop/stripe-payment-form.vue`. To add a payment provider, implement it with Shopper's [payment system](/3.x/payments), register it in the admin panel, and enable it on the zones where customers can use it. `FetchPaymentMethods` only lists the drivers of its `SUPPORTED_DRIVERS` constant, `manual` and `stripe`, so add the new driver there once its payment step and return page exist. ### Adding Pages [#adding-pages] A new page takes a controller, a named route in `routes/web.php`, and a Vue component under `resources/js/pages/`. Name the page under `shop/` so it renders with the storefront header and footer. This controller renders the `shop/about` page: ```php title="app/Http/Controllers/AboutController.php" namespace App\Http\Controllers; use Inertia\Inertia; use Inertia\Response; final class AboutController extends Controller { public function __invoke(): Response { return Inertia::render('shop/about'); } } ``` This route serves the page at `/about`, under the name `about`: ```php title="routes/web.php" use App\Http\Controllers\AboutController; Route::get('about', AboutController::class)->name('about'); ``` This component renders the title of the page inside the `Container` of the storefront: ```vue title="resources/js/pages/shop/about.vue" <script setup lang="ts"> import { Head } from '@inertiajs/vue3'; import Container from '@/components/shop/container.vue'; </script> <template> <Head title="About Us" /> <Container class="py-8 sm:py-12"> <h1>About Us</h1> </Container> </template> ``` Wayfinder adds an `about` function to `@/routes` the next time Vite runs, so a link in the footer reads `<Link :href="about.url()">About</Link>`, the way `resources/js/layouts/storefront/store-footer.vue` links to `home`. ### Models [#models-1] Add methods, scopes, or relationships directly to the models in `app/Models/`. They extend the Shopper models, so everything Shopper defines on them keeps working. ```php title="app/Models/Product.php" use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; final class Product extends Model { #[Scope] protected function featured(Builder $query): Builder { return $query->where('featured', true); } } ``` # Reference (/3.x/reference) Reference lists what Shopper exposes, one table per kind, each row checked against the 3.x code. Until a table is published here, the [2.x TypeScript types](/2.x/reference/typescript-types) page covers the types as they were in 2.x. # User Guide (/3.x/user-guide) The User Guide is for the people who run the store. Its groups follow the admin menu: Getting Started, Store Setup, Catalog, Sales, Marketing and Administration. Until a screen is covered here, the [2.x User Guide](/2.x/user-guide/getting-started/introduction) describes the screens that already existed in 2.x.