# Community Add-ons
Source: https://docs.lunarphp.com/1.x/addons/community/overview
Third-party packages built by the Lunar community.
The Lunar community has built a growing collection of third-party packages that extend the platform's functionality. These packages are independently maintained by their authors and are not officially supported by Lunar.
> [!NOTE]
>
> Have an add-on to share? [Open a PR on the docs repository](https://github.com/lunarphp/docs) to add it to this page.
## API
| Package | Description |
| - | - |
| [dystcz/lunar-api](https://github.com/dystcz/lunar-api) | A JSON:API-compliant API layer that connects the Lunar backend with SPAs, mobile apps, and other applications. Built on Laravel JSON:API. |
## Payments
| Package | Description |
| - | - |
| [webcraft/lunar-mollie](https://github.com/webcraft/lunar-mollie) | Mollie payment driver supporting credit cards, iDEAL, PayPal, Apple Pay, Bancontact, and more. Includes a Livewire checkout component. |
| [wychoong/lunarphp-mpgs](https://github.com/wychoong/lunarphp-mpgs) | Mastercard Payment Gateway Services (MPGS) Hosted Checkout integration with Livewire support. |
| [wakqasahmed/agentic-payment-x402-lunar](https://github.com/wakqasahmed/agentic-payment-x402-lunar) | x402 crypto payment driver for stablecoin checkout (USDC on Base and other EVM chains), built for agent-driven and human checkout alike. |
## Products
| Package | Description |
| - | - |
| [armezit/lunarphp-virtual-product](https://github.com/armezit/lunarphp-virtual-product) | Adds support for virtual and digital products such as subscriptions, memberships, and downloadable goods. |
| [armezit/lunarphp-purchase-limit](https://github.com/armezit/lunarphp-purchase-limit) | Allows defining purchase limitation rules based on quantity, amount, or both, scoped to products, variants, customers, or customer groups. |
## Disclaimer
Community add-ons are maintained by their respective authors. Lunar does not guarantee compatibility, security, or ongoing maintenance of these packages. Always review the source code and test thoroughly before using any third-party package in production.
# Opayo
Source: https://docs.lunarphp.com/1.x/addons/payments/opayo
Accept payments using Opayo with Lunar.
Lunar's Opayo addon integrates with Opayo's (formerly SagePay) payment API to handle card payments, including 3D Secure authentication and saved card tokens.
> [!WARNING]
>
> This addon is currently in alpha. While every step is taken to ensure it works as intended, it will not be considered out of alpha until additional tests have been added.
## Installation
### Require the Composer package
```sh theme={null}
composer require lunarphp/opayo
```
### Configure the service
Add the Opayo credentials to `config/services.php`.
```php theme={null}
'opayo' => [
'vendor' => env('OPAYO_VENDOR'),
'env' => env('OPAYO_ENV', 'test'),
'key' => env('OPAYO_KEY'),
'password' => env('OPAYO_PASSWORD'),
],
```
### Publish the configuration
This will publish the configuration under `config/lunar/opayo.php`.
```sh theme={null}
php artisan vendor:publish --tag=lunar.opayo.config
```
### Publish the views (optional)
The Opayo addon includes Blade and Livewire components for checkout. To customize these views, publish them.
```sh theme={null}
php artisan vendor:publish --tag=lunar.opayo.components
```
### Enable the driver
Set the driver in `config/lunar/payments.php`.
```php theme={null}
[
'card' => [
// ...
'driver' => 'opayo',
],
],
];
```
## Configuration
The following options are available in `config/lunar/opayo.php`.
| Key | Default | Description |
| - | - | - |
| `policy` | `automatic` | Determines the capture policy. `automatic` captures payment immediately; `deferred` authorizes first and captures later |
The Opayo API endpoint is determined by the `services.opayo.env` value.
| Environment | API Base URL |
| - | - |
| `test` | `https://sandbox.opayo.eu.elavon.com/api/v1/` |
| `live` | `https://live.opayo.eu.elavon.com/api/v1/` |
## Backend Usage
### Get a merchant session key
A merchant session key is required before tokenizing card details on the client side.
```php theme={null}
use Lunar\Opayo\Facades\Opayo;
$merchantKey = Opayo::getMerchantKey();
```
### Authorize a payment
```php theme={null}
use Lunar\Facades\Payments;
use Lunar\Facades\CartSession;
$response = Payments::driver('opayo')->cart(
CartSession::current()->calculate()
)->withData([
'merchant_key' => $request->get('merchantSessionKey'),
'card_identifier' => $request->get('cardToken'),
'browserLanguage' => $request->get('browserLanguage'),
'challengeWindowSize' => $request->get('challengeWindowSize'),
'browserIP' => $request->ip(),
'browserAcceptHeader' => $request->header('accept'),
'browserUserAgent' => $request->get('browserUserAgent'),
'browserJavaEnabled' => $request->get('browserJavaEnabled', false),
'browserColorDepth' => $request->get('browserColorDepth'),
'browserScreenHeight' => $request->get('browserScreenHeight'),
'browserScreenWidth' => $request->get('browserScreenWidth'),
'browserTZ' => $request->get('browserTZ'),
'status' => 'payment-received',
])->authorize();
```
### Capture a deferred payment
When using the `deferred` policy, payments must be captured separately after authorization.
```php theme={null}
use Lunar\Facades\Payments;
Payments::driver('opayo')->capture($transaction, $amount);
```
### Refund a payment
```php theme={null}
use Lunar\Facades\Payments;
Payments::driver('opayo')->refund($transaction, $amount, $notes);
```
### Retrieve a transaction
Fetch transaction details from the Opayo API. This method includes retry logic with up to 4 attempts.
```php theme={null}
use Lunar\Opayo\Facades\Opayo;
$transaction = Opayo::getTransaction($transactionId);
```
## 3D Secure Authentication
When authorizing a payment, Opayo may require 3D Secure (3DS) authentication. The authorization response indicates whether a challenge is needed.
### Handling the 3DS response
```php theme={null}
use Lunar\Opayo\Responses\ThreeDSecureResponse;
$response = Payments::driver('opayo')->cart($cart)->withData([
// ...
])->authorize();
if ($response instanceof ThreeDSecureResponse) {
return response()->json([
'requires_auth' => true,
'data' => $response,
]);
}
```
The `ThreeDSecureResponse` contains the following properties:
| Property | Type | Description |
| - | - | - |
| `success` | `bool` | Whether the initial authorization was successful |
| `status` | `string` `nullable` | The 3DS status |
| `acsUrl` | `string` `nullable` | The Access Control Server URL for the challenge |
| `acsTransId` | `string` `nullable` | The ACS transaction ID |
| `dsTransId` | `string` `nullable` | The Directory Server transaction ID |
| `cReq` | `string` `nullable` | The challenge request (3DS 2.x) |
| `paReq` | `string` `nullable` | The payer authentication request (3DS 1.x) |
| `transactionId` | `string` `nullable` | The Opayo transaction ID |
| `message` | `string` `nullable` | An optional message with additional details |
### Completing the 3DS challenge
After the customer completes the 3DS challenge on the storefront, authorize the payment again with the challenge response data.
For 3DS 2.x:
```php theme={null}
use Lunar\Facades\Payments;
$response = Payments::driver('opayo')->cart($cart)->withData([
'cres' => $request->get('cres'),
'transaction_id' => $request->get('transaction_id'),
])->threedsecure();
if (! $response->success) {
// Handle authentication failure
}
```
For 3DS 1.x:
```php theme={null}
$response = Payments::driver('opayo')->cart($cart)->withData([
'pares' => $request->get('pares'),
'transaction_id' => $request->get('transaction_id'),
])->threedsecure();
```
For more information on 3D Secure with Opayo, see:
* [3-D Secure explained](https://www.elavon.co.uk/resource-center/help-with-your-solutions/opayo/fraud-prevention/3D-Secure.html)
* [3D Secure Transactions](https://developer.elavon.com/products/opayo-direct/v1/3d-secure-transactions)
## Saved Cards
Authenticated users can save their card details for future purchases. The addon stores card tokens (not actual card details) in the `opayo_tokens` table.
> [!NOTE]
>
> Saved payments must be enabled on the Opayo account before this feature can be used.
### Saving a card
Pass the `saveCard` data key when authorizing a payment.
```php theme={null}
use Lunar\Facades\Payments;
$response = Payments::driver('opayo')->cart($cart)->withData([
// ...
'saveCard' => true,
])->authorize();
```
After a successful authorization, a new entry is created in the `opayo_tokens` table associated with the authenticated user. If a token already exists with the same last four digits for that user, it is replaced.
### Using a saved card
To pay with a previously saved card, pass the token as the `card_identifier` and set `reusable` to `true`.
```php theme={null}
use Lunar\Facades\Payments;
$response = Payments::driver('opayo')->cart($cart)->withData([
// ...
'card_identifier' => $savedToken->token,
'reusable' => true,
])->authorize();
```
Responses are then handled the same as any other transaction, including 3D Secure challenges if required.
### HasOpayoTokens trait
Add the `HasOpayoTokens` trait to the User model to access saved card tokens.
```php theme={null}
use Lunar\Opayo\Concerns\HasOpayoTokens;
class User extends Authenticatable
{
use HasOpayoTokens;
}
```
This provides an `opayoTokens` relationship.
```php theme={null}
$tokens = $user->opayoTokens;
```
### Token fields
| Field | Type | Description |
| - | - | - |
| `id` | `id` | Primary key |
| `user_id` | `foreignId` | The associated user |
| `card_type` | `string` | The card type (e.g., visa, mastercard) |
| `last_four` | `string` | The last four digits of the card number |
| `token` | `string` | The Opayo card identifier token |
| `auth_code` | `string` `nullable` | The authentication code for recurring transactions |
| `expires_at` | `timestamp` | The card expiration date |
| `created_at` | `timestamp` | |
| `updated_at` | `timestamp` | |
## Livewire Component
The addon includes a Livewire payment form component that handles merchant key retrieval, card tokenization, and 3D Secure challenges.
```blade theme={null}
Showing page {{ $results->page }} of {{ $results->totalPages }} ({{ $results->count }} results)
``` ## TypeScript Integration If [Spatie TypeScript Transformer](https://spatie.be/docs/typescript-transformer) is being used, add the data path to the `typescript-transformer.php` config to generate TypeScript types for the search response classes: ```php theme={null} return [ // ... 'auto_discover_types' => [ // ... \Lunar\Search\data_path(), ], ]; ``` The generated types are available under the `Lunar.Search` namespace: ```ts theme={null} defineProps<{ results: Lunar.Search.SearchResults }>() ``` # Table Rate Shipping Source: https://docs.lunarphp.com/1.x/addons/table-rate-shipping Zone-based shipping rates with multiple driver types for Lunar storefronts. ## Overview The Table Rate Shipping add-on provides a flexible, zone-based shipping system for Lunar. It integrates with the core shipping modifier pipeline, allowing storefronts to offer multiple shipping methods with pricing that varies by zone, cart total, weight, or other criteria. Key concepts: * **Shipping Zones** define geographic regions (unrestricted, by country, state, or postcode). * **Shipping Methods** represent the types of delivery available (e.g., standard, express, collection). * **Shipping Rates** link a method to a zone with tiered pricing. * **Shipping Exclusion Lists** prevent specific products from being shipped to certain zones. ## Installation Install via Composer: ```bash theme={null} composer require lunarphp/table-rate-shipping ``` Then register the admin panel plugin in a service provider: ```php theme={null} use Filament\Panel; use Lunar\Admin\Support\Facades\LunarPanel; use Lunar\Shipping\ShippingPlugin; public function register(): void { LunarPanel::panel(function (Panel $panel) { return $panel->plugin(new ShippingPlugin()); })->register(); } ``` ## Configuration The configuration file is published at `config/lunar/shipping-tables.php`. ```php theme={null} return [ 'enabled' => env('LUNAR_SHIPPING_TABLES_ENABLED', true), // 'default' uses the system-wide default tax class. // 'highest' selects the highest tax rate from items in the cart. 'shipping_rate_tax_calculation' => 'default', ]; ``` | Option | Default | Description | | :- | :- | :- | | `enabled` | `true` | Enable or disable the shipping tables add-on. | | `shipping_rate_tax_calculation` | `'default'` | Tax class strategy for shipping rates. Use `'default'` for the system default tax class, `'highest'` to use the highest tax rate found among cart items, or a callable (e.g., `[App\Shipping\TaxRateCalculator::class, 'calculate']`) for custom logic. Callables receive the `Lunar\Shipping\Models\ShippingRate` and the cart, and should return a `Lunar\Models\TaxClass`. | ## Permissions The add-on registers a `shipping:manage` permission and enforces it on the Shipping Methods, Shipping Zones, and Shipping Exclusion Lists resources in the admin panel. Staff members need this permission (either directly or via a role) to view or manage shipping configuration. The permission is created automatically by a migration when the add-on is installed. See [Access Control](/1.x/admin/extending/access-control) for guidance on assigning permissions to roles and staff. ## Models ### ShippingZone ```php theme={null} Lunar\Shipping\Models\ShippingZone ``` A shipping zone represents a geographic area that shipping rates apply to. Zones can be unrestricted (apply everywhere) or limited to specific countries, states, or postcodes. | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | name | `string` | | | type | `string` | `unrestricted`, `countries`, `states`, or `postcodes` | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | #### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | rates | HasMany | `ShippingRate` | Shipping rates for this zone | | shippingMethods | HasMany | `ShippingMethod` | Shipping methods available in this zone | | countries | BelongsToMany | `Lunar\Models\Country` | Countries included in this zone | | states | BelongsToMany | `Lunar\Models\State` | States included in this zone | | postcodes | HasMany | `ShippingZonePostcode` | Postcodes included in this zone | | orders | BelongsToMany | `Lunar\Models\Order` | Orders assigned to this zone | | shippingExclusions | BelongsToMany | `ShippingExclusionList` | Product exclusion lists associated with this zone | *** ### ShippingMethod ```php theme={null} Lunar\Shipping\Models\ShippingMethod ``` A shipping method represents a type of delivery, such as flat rate, weight-based, free shipping, or in-store collection. Each method uses a driver that determines how pricing is resolved. | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | name | `string` | | | description | `text` `nullable` | | | code | `string` `nullable` | Unique identifier used as the shipping option identifier | | enabled | `boolean` | Whether the method is active | | stock\_available | `boolean` | When enabled, the method is only available if all cart items are in stock | | min\_weight | `decimal` `nullable` | Minimum cart weight required for the method to be offered | | max\_weight | `decimal` `nullable` | Maximum cart weight allowed for the method to be offered | | weight\_unit | `string` `nullable` | Unit used by `min_weight` and `max_weight` (e.g., `kg`, `g`) | | data | `json` `nullable` | Driver-specific configuration (cast to `AsArrayObject`) | | driver | `string` | Driver identifier (e.g., `ship-by`, `flat-rate`, `free-shipping`, `collection`) | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | #### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | shippingRates | HasMany | `ShippingRate` | Rates associated with this method | | customerGroups | BelongsToMany | `Lunar\Models\CustomerGroup` | Customer groups that can see and use this method | *** ### ShippingRate ```php theme={null} Lunar\Shipping\Models\ShippingRate ``` A shipping rate connects a shipping method to a shipping zone and holds the pricing. It implements the `Lunar\Models\Contracts\Purchasable` interface and uses the `HasPrices` trait, meaning prices are stored in Lunar's core `prices` table with support for tiered pricing and multiple currencies. | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | shipping\_method\_id | `foreignId` | References the shipping method | | shipping\_zone\_id | `foreignId` | References the shipping zone | | enabled | `boolean` | Whether the rate is active | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | #### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | shippingMethod | BelongsTo | `ShippingMethod` | The parent shipping method | | shippingZone | BelongsTo | `ShippingZone` | The parent shipping zone | | prices | MorphMany | `Lunar\Models\Price` | Tiered pricing via the `HasPrices` trait | *** ### ShippingZonePostcode ```php theme={null} Lunar\Shipping\Models\ShippingZonePostcode ``` | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | shipping\_zone\_id | `foreignId` | References the shipping zone | | postcode | `string` | Indexed; spaces are automatically stripped on save | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | #### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | shippingZone | BelongsTo | `ShippingZone` | The parent shipping zone | *** ### ShippingExclusionList ```php theme={null} Lunar\Shipping\Models\ShippingExclusionList ``` An exclusion list groups products that should not be shipped to certain zones. If a cart contains any product on an exclusion list associated with a zone, shipping options for that zone are not available. | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | name | `string` | Unique name for the list | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | #### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | exclusions | HasMany | `ShippingExclusion` | Products in this list | | shippingZones | BelongsToMany | `ShippingZone` | Zones this list applies to | *** ### ShippingExclusion ```php theme={null} Lunar\Shipping\Models\ShippingExclusion ``` | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | shipping\_exclusion\_list\_id | `foreignId` | References the exclusion list | | purchasable\_type | `string` | Polymorphic type | | purchasable\_id | `unsignedBigInteger` | Polymorphic ID | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | #### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | list | BelongsTo | `ShippingExclusionList` | The parent exclusion list | | purchasable | MorphTo | — | The excluded purchasable (e.g., a `Product`) | ## Method Availability Each shipping method exposes two ways to control when it can be offered to customers: an availability schedule and an optional weight range. ### Availability Schedule Shipping methods use an availability schedule to define when the method can be selected. The schedule replaces the older single daily cutoff time and supports finer-grained rules (for example, different cutoffs per day of the week, or unavailable on specific dates). The schedule is managed through the Shipping Method page in the admin panel. When the cart is evaluated, the shipping rate resolver checks the schedule for each method and only returns rates from methods that are currently available. ### Weight Constraints `min_weight` and `max_weight` on the shipping method allow restricting the method to carts within a given weight range. Both fields are optional; leaving them empty means no lower or upper bound is applied. `weight_unit` defines the unit used by both values. The total cart weight is calculated from each cart line's purchasable weight multiplied by its quantity. Methods whose constraints are not satisfied are excluded from the resolver's results. ## Drivers Each shipping method uses a driver to determine how pricing is resolved. The add-on ships with four built-in drivers. ### Ship By **Driver identifier:** `ship-by` The most flexible driver. Pricing is based on either the cart total or the total weight of items in the cart. Prices are stored as tiered rates on the shipping rate, where each tier's `min_quantity` represents the threshold (cart subtotal in minor units, or total weight). **Data configuration:** | Key | Values | Description | | :- | :- | :- | | `charge_by` | `cart_total` (default), `weight` | Determines what value is used to match against price tiers. When set to `weight`, each cart line's weight is converted into the method's `weight_unit` and multiplied by its quantity. | #### Weight tiers Added in 1.5 When `charge_by` is set to `weight`, tiers are evaluated in the unit configured as the shipping method's `weight_unit`, defaulting to `kg` when it is empty. Each cart line's weight is converted from its own purchasable unit first, so a cart mixing items measured in grams and kilograms is totaled correctly. Tier thresholds are stored as whole numbers. To express a threshold below one kilogram, configure the method in a smaller unit: a method with a `weight_unit` of `g` can use tiers of `500` and `1000` where kilograms would have required `0.5` and `1`. The admin panel shows the configured unit alongside the tier field and rejects decimal values rather than truncating them. > [!WARNING] > > Before Lunar 1.5, weight tiers were always evaluated in kilograms regardless of the method's `weight_unit`. Methods that set a unit other than `kg` need their tier thresholds re-entered in that unit after upgrading. Methods that left `weight_unit` empty are unaffected. ### Flat Rate **Driver identifier:** `flat-rate` Charges a flat rate per order, with optional tiered pricing based on the cart subtotal. Prices are stored on the shipping rate using Lunar's pricing system with quantity tiers representing cart subtotal thresholds. ### Free Shipping **Driver identifier:** `free-shipping` Offers free shipping when the cart meets a minimum spend requirement. **Data configuration:** | Key | Values | Description | | :- | :- | :- | | `minimum_spend` | `array` or `number` | Minimum cart subtotal required. Can be a single value or an array keyed by currency code (e.g., `{"GBP": 5000, "USD": 6000}`). Values are in minor units. | | `use_discount_amount` | `boolean` | When `true`, discount amounts are subtracted from the cart subtotal before checking the minimum spend. | ### Collection **Driver identifier:** `collection` Allows customers to collect their order in store. Returns a shipping option with a price of zero and sets `collect: true` on the shipping option, which can be used to identify collection orders in the storefront. ## Per-Currency Pricing Shipping rates store their base price per currency, not just for the store's default currency. Each currency enabled on the store can be assigned its own base price through the Shipping Rates page in the admin panel. Tiered pricing (used by `ship-by` and `flat-rate`) continues to be defined alongside, using Lunar's core pricing system. ## Shipping Discounts The add-on registers a `ShippingDiscount` discount type that targets the shipping portion of the cart. It is configured through the Discounts area of the admin panel. ```php theme={null} Lunar\Shipping\DiscountTypes\ShippingDiscount ``` A shipping discount holds one or more rules. Each rule may target a specific shipping method (by `shipping_method_id`) or act as a catch-all (no method selected), and offers one of two adjustments: * **Percentage** — reduces the matched shipping option price by a percentage. * **Fixed per currency** — replaces the matched shipping option price with a fixed value per currency code. A value of `0` produces free shipping. When the discount is applied, the resolver matches each item in the cart's shipping breakdown against the configured rules and rewrites the price accordingly. Discount conditions (minimum spend, customer groups, etc.) apply as with any other discount type. ## Storefront Usage This add-on registers a `ShippingModifier` with Lunar's shipping modifier pipeline. Shipping options are automatically resolved and available through the `ShippingManifest`: ```php theme={null} use Lunar\Facades\ShippingManifest; $options = ShippingManifest::getOptions($cart); ``` The modifier resolves shipping zones based on the cart's shipping address, finds applicable rates, and converts them into `ShippingOption` instances that are added to the manifest. > [!NOTE] > > If an existing storefront already uses the `ShippingManifest` to retrieve shipping options, no changes are needed. The add-on integrates automatically. ## Advanced Usage ### Retrieving Supported Drivers ```php theme={null} use Lunar\Shipping\Facades\Shipping; $drivers = Shipping::getSupportedDrivers(); ``` ### Resolving a Driver Directly ```php theme={null} use Lunar\Shipping\Facades\Shipping; use Lunar\Shipping\DataTransferObjects\ShippingOptionRequest; $option = Shipping::driver('ship-by') ->on($shippingRate) ->resolve( new ShippingOptionRequest( shippingRate: $shippingRate, cart: $cart, ) ); ``` ### Resolving Shipping Zones The zone resolver finds matching zones based on address criteria. Each method is optional; combining them makes the lookup more specific. ```php theme={null} use Lunar\Shipping\Facades\Shipping; use Lunar\Shipping\DataTransferObjects\PostcodeLookup; $zones = Shipping::zones() ->country($country) ->state($state) ->postcode( new PostcodeLookup( country: $country, postcode: 'NW1' ) ) ->get(); ``` The resolver always includes zones with type `unrestricted`, plus any zones matching the specified country, state, or postcode criteria. ### Resolving Shipping Rates The rate resolver finds applicable shipping rates for a cart, filtering by customer group, cutoff time, and stock availability. ```php theme={null} use Lunar\Shipping\Facades\Shipping; $rates = Shipping::shippingRates($cart)->get(); ``` ### Resolving Shipping Options The option resolver takes shipping rates and resolves them into priced `ShippingOption` instances using each rate's driver. ```php theme={null} use Lunar\Shipping\Facades\Shipping; use Lunar\Shipping\DataTransferObjects\ShippingOptionLookup; $rates = Shipping::shippingRates($cart)->get(); $options = Shipping::shippingOptions($cart)->get( new ShippingOptionLookup(shippingRates: $rates) ); ``` ## Postcode Resolvers Added in 1.5 Postcode formats vary considerably between countries, so the add-on splits a raw postcode into a set of "parts" that are matched against `ShippingZonePostcode` records. The default `Lunar\Shipping\Resolvers\PostcodeResolver` works well for UK-style postcodes (and any country that follows a similar prefix structure), but custom resolvers can be registered for stores operating in regions where a different breakdown is needed. ### The PostcodeResolverInterface A resolver implements `Lunar\Shipping\Interfaces\PostcodeResolverInterface`: ```php theme={null} namespace Lunar\Shipping\Interfaces; use Illuminate\Support\Collection; use Lunar\Models\Contracts\Country as CountryContract; interface PostcodeResolverInterface { public function supportsCountry(CountryContract $country): bool; public function getParts(string $postcode, CountryContract $country): Collection; } ``` * `supportsCountry` declares which countries the resolver handles. Returning `true` for every country makes the resolver a catch-all. * `getParts` returns the postcode permutations to match against the zone's stored postcodes. Wildcards (`*`) are honored by the zone resolver. ### Registering a custom resolver Resolvers are registered through the `Lunar\Shipping\Facades\Postcode` facade, typically in the `boot` method of a service provider: ```php theme={null} use Lunar\Shipping\Facades\Postcode; use App\Shipping\UsZipResolver; Postcode::addResolver(UsZipResolver::class); ``` Resolvers are evaluated in reverse registration order — the last-registered resolver that supports the country wins. Register country-specific resolvers after the default, more general ones. ```php theme={null} use Lunar\Shipping\Facades\Postcode; // Match the resolver for the cart's shipping country. $resolver = Postcode::country($country); $parts = $resolver->getParts('SW1A 1AA', $country); ``` ### Example resolver ```php theme={null} namespace App\Shipping; use Illuminate\Support\Collection; use Lunar\Models\Contracts\Country as CountryContract; use Lunar\Shipping\Interfaces\PostcodeResolverInterface; class UsZipResolver implements PostcodeResolverInterface { public function supportsCountry(CountryContract $country): bool { return $country->iso2 === 'US'; } public function getParts(string $postcode, CountryContract $country): Collection { $zip = preg_replace('/[^0-9]/', '', $postcode); return collect([ $zip, // 902101234 substr($zip, 0, 5), // 90210 substr($zip, 0, 5).'*', // 90210* substr($zip, 0, 3), // 902 substr($zip, 0, 3).'*', // 902* ])->filter()->unique()->values(); } } ``` > [!NOTE] > > If no registered resolver supports the cart's country, a `Lunar\Shipping\Exceptions\NoPostcodeResolverException` is thrown. The default resolver ships unrestricted, so this only applies when it has been removed. ## Events ### ShippingOptionResolvedEvent ```php theme={null} Lunar\Shipping\Events\ShippingOptionResolvedEvent ``` Dispatched each time a shipping option is successfully resolved from a shipping rate. | Property | Type | Description | | :- | :- | :- | | `cart` | `Lunar\Models\Contracts\Cart` | The cart being resolved | | `shippingRate` | `ShippingRate` | The shipping rate that was resolved | | `shippingOption` | `Lunar\DataTypes\ShippingOption` | The resulting shipping option | ## Order Observer When an order is created or updated, the add-on automatically resolves the shipping zone from the order's shipping address and attaches it to the order via the `order_shipping_zone` pivot table. The zone name is also stored in the order's meta for search indexing. # Access Control Source: https://docs.lunarphp.com/1.x/admin/extending/access-control Manage staff members, roles, permissions, and two-factor authentication in the admin panel. ## Staff Members Staff members are the users who can log in to the admin panel. They are stored in a separate table from the `users` table used for customer authentication. This is a deliberate design choice to ensure that customers can never accidentally be given access to the admin panel. ## Roles and Permissions The Lunar admin panel uses roles and permissions for authorization, powered by the `spatie/laravel-permission` package. Multiple permissions can be assigned to a role, and roles can be assigned to staff members rather than assigning permissions individually. ### Roles Lunar provides two built-in roles: `admin` and `staff`. New roles can be created using the Access Control page in the Staff menu. After installation, the panel has one admin. Additional admin accounts can be assigned, but non-admin staff cannot assign the admin role to others. ### Permissions Permissions can be assigned to roles or directly to individual staff members. Permissions control what a staff member can see and do in the panel. If a user does not have the required permission for a page or action, they will receive an unauthorized HTTP error. They may also see fewer menu items in the navigation. To manage permissions for a staff member, edit them through the staff page and assign the desired permissions. ### Adding Permissions Permissions should not be created through the panel UI, as the corresponding authorization logic must be implemented in code. The recommended approach is to create permissions through a Laravel migration or Lunar migration state, which allows them to be deployed consistently across environments. ## Authorization First-party permissions provided by Lunar are used to authorize the respective sections of the panel. When adding custom permissions for new pages or functionality, the corresponding authorization checks must also be implemented. For example, authorization can be applied using middleware or checked directly in code: ```php theme={null} // As route middleware Route::get('/custom-page', CustomPageController::class) ->middleware('can:permission-handle'); // Checking in code Auth::user()->can('permission-handle'); ``` ## Two-Factor Authentication Two-factor authentication can be enforced or disabled for all staff members: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; public function register(): void { // Enforce two-factor authentication for all staff LunarPanel::forceTwoFactorAuth()->register(); // Or disable two-factor authentication entirely LunarPanel::disableTwoFactorAuth()->register(); } ``` # Developing Addons Source: https://docs.lunarphp.com/1.x/admin/extending/addons How to develop addon packages that extend the Lunar admin panel. When creating addon packages for Lunar, new screens and functionality can be added to the admin panel by creating a Filament plugin. With Filament plugins, additional resources, pages, and widgets can be registered. See the [Filament documentation](https://filamentphp.com/docs) for more information on building plugins. ## Registering Filament Plugins Addon packages should not auto-register Filament plugins in the Lunar panel. Instead, provide installation instructions so that developers can register the plugin manually in their service provider. Below is an example of how a plugin should be registered: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; LunarPanel::panel(fn ($panel) => $panel->plugin(new ReviewsPlugin())) ->register(); ``` > [!NOTE] > > When extending forms or tables in an addon, use a defensive approach since the form contents may have been modified by other extensions. See [Extending Pages in Addons](/1.x/admin/extending/pages#extending-pages-in-addons) for more details. # Extending Attributes Source: https://docs.lunarphp.com/1.x/admin/extending/attributes How to add custom attribute field types to the Lunar admin panel. Custom attribute field types can be added to Lunar to control how they are rendered in the panel. To render a form component from an attribute, it must be converted into a Filament form component with a suitable Livewire Synthesizer so it can be hydrated and dehydrated properly. ## Create the Field ```php theme={null} use Lunar\FieldTypes\Text; class CustomField extends Text { // ... } ``` ## Create the Field Type ```php theme={null} use Lunar\Admin\Support\FieldTypes\BaseFieldType; class CustomFieldType extends BaseFieldType { protected static string $synthesizer = CustomFieldSynth::class; public static function getFilamentComponent(Attribute $attribute): Component { return TextInput::make($attribute->handle); } } ``` ## Adding Settings Additional settings can be added to a field type. For example, the Number field has `min` and `max` settings. To define these settings, tell Filament how to render the configuration inputs. ```php theme={null} class CustomFieldType extends BaseFieldType { // ... public static function getConfigurationFields(): array { return [ Grid::make(2)->schema([ \Filament\Forms\Components\TextInput::make('min_length'), \Filament\Forms\Components\TextInput::make('max_length'), ]), ]; } } ``` These settings are stored in the `configuration` JSON column for the attribute and can be accessed when rendering the field in the panel. ```php theme={null} use Lunar\Admin\Support\FieldTypes\BaseFieldType; class CustomFieldType extends BaseFieldType { // ... public static function getFilamentComponent(Attribute $attribute): Component { $min = (int) $attribute->configuration->get('min_length'); $max = (int) $attribute->configuration->get('max_length'); return TextInput::make($attribute->handle)->min($min)->max($max); } } ``` ## Create the Livewire Synthesizer A Livewire Synthesizer tells Livewire how to hydrate and dehydrate the values provided to the field type during editing. See the [Livewire Synthesizers documentation](https://livewire.laravel.com/docs/synthesizers) for more details. ```php theme={null} use Lunar\Admin\Support\Synthesizers\AbstractFieldSynth; use Lunar\FieldTypes\Text; class CustomFieldSynth extends AbstractFieldSynth { public static $key = 'lunar_custom_field_field'; protected static $targetClass = CustomField::class; } ``` ## Register the Field The last step is to register the field type with the `AttributeData` facade, typically in a service provider. ```php theme={null} use Lunar\Admin\Support\Facades\AttributeData; AttributeData::registerFieldType(\App\FieldTypes\CustomField::class, \App\Panel\FieldTypes\CustomFieldType::class); ``` # Configuration Source: https://docs.lunarphp.com/1.x/admin/extending/configuration Configure the admin panel behavior and options. ## Panel Configuration Publish the panel configuration file if it has not already been published: ```bash theme={null} php artisan vendor:publish --tag=lunar-panel ``` This creates `config/lunar-panel.php` with the following options: | Option | Type | Default | Description | | :- | :- | :- | :- | | `enable_variants` | `bool` | `true` | Show the variants manager when editing a product. Set to `false` if the storefront does not support variants. | | `pdf_rendering` | `string` | `download` | How PDFs are handled in the panel. Options are `download` or `stream`. | | `scout_enabled` | `bool` | `false` | Use Laravel Scout for searching supported models in panel tables. | | `order_count_statuses` | `array` | `['payment-received']` | Order statuses included in the navigation badge count. | ## Product Association Types By default, the admin panel provides three association types in the product associations dropdown: Cross Sell, Up Sell, and Alternate. These come from the `Lunar\Base\Enums\ProductAssociation` enum. To add custom association types, create a new backed enum that implements the `ProvidesProductAssociationType` interface: ```php theme={null} namespace App\Enums; use Lunar\Base\Enums\Concerns\ProvidesProductAssociationType; enum ProductAssociation: string implements ProvidesProductAssociationType { case CROSS_SELL = 'cross-sell'; case UP_SELL = 'up-sell'; case ALTERNATE = 'alternate'; case BUNDLE = 'bundle'; case ACCESSORY = 'accessory'; public function label(): string { return match ($this) { self::CROSS_SELL => 'Cross Sell', self::UP_SELL => 'Up Sell', self::ALTERNATE => 'Alternate', self::BUNDLE => 'Bundle', self::ACCESSORY => 'Accessory', }; } } ``` Then update `config/lunar/products.php` to point to the custom enum: ```php theme={null} return [ 'association_types_enum' => \App\Enums\ProductAssociation::class, ]; ``` The admin panel reads from this configuration automatically. The custom types will appear in the association type dropdown when creating or viewing product associations, with no additional setup required. > [!NOTE] > > The enum must be a backed string enum, and each case must implement a `label()` method that returns the human-readable name. See the [Associations reference](/1.x/reference/associations#custom-types) for full details on using custom types in application code. # Extending Order Management Source: https://docs.lunarphp.com/1.x/admin/extending/order-management How to extend the order management view in the Lunar admin panel. The order management page supports the same customization as [Pages](/1.x/admin/extending/pages), along with additional methods specific to the order view screen. ## Registration Register an order management extension in a service provider: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\OrderResource\Pages\ManageOrder::class => MyManageOrderExtension::class, ]); ``` ## Available Methods The following methods can be overridden in the extension class to customize sections of the order view. ### Main Infolist * `extendInfolistSchema(): array` ### Aside Panel * `extendInfolistAsideSchema(): array` * `extendCustomerEntry(): Infolists\Components\Component` * `extendTagsSection(): Infolists\Components\Component` * `extendAdditionalInfoSection(): Infolists\Components\Component` * `extendShippingAddressInfolist(): Infolists\Components\Component` * `extendBillingAddressInfolist(): Infolists\Components\Component` * `extendAddressEditSchema(): array` ### Order Summary * `extendOrderSummaryInfolist(): Infolists\Components\Section` * `extendOrderSummarySchema(): array` * `extendOrderSummaryNewCustomerEntry(): Infolists\Components\Entry` * `extendOrderSummaryStatusEntry(): Infolists\Components\Entry` * `extendOrderSummaryReferenceEntry(): Infolists\Components\Entry` * `extendOrderSummaryCustomerReferenceEntry(): Infolists\Components\Entry` * `extendOrderSummaryChannelEntry(): Infolists\Components\Entry` * `extendOrderSummaryCreatedAtEntry(): Infolists\Components\Entry` * `extendOrderSummaryPlacedAtEntry(): Infolists\Components\Entry` ### Timeline * `extendTimelineInfolist(): Infolists\Components\Component` ### Order Totals * `extendOrderTotalsAsideSchema(): array` * `extendDeliveryInstructionsEntry(): Infolists\Components\TextEntry` * `extendOrderNotesEntry(): Infolists\Components\TextEntry` * `extendOrderTotalsInfolist(): Infolists\Components\Section` * `extendOrderTotalsSchema(): array` * `extendSubTotalEntry(): Infolists\Components\TextEntry` * `extendDiscountTotalEntry(): Infolists\Components\TextEntry` * `extendShippingBreakdownGroup(): Infolists\Components\Group` * `extendTaxBreakdownGroup(): Infolists\Components\Group` * `extendTotalEntry(): Infolists\Components\TextEntry` * `extendPaidEntry(): Infolists\Components\TextEntry` * `extendRefundEntry(): Infolists\Components\TextEntry` ### Shipping and Transactions * `extendShippingInfolist(): Infolists\Components\Section` * `extendTransactionsInfolist(): Infolists\Components\Component` * `extendTransactionsRepeatableEntry(): Infolists\Components\RepeatableEntry` ## Extending the Order Items Table The order items table can be extended separately by registering an extension for the `OrderItemsTable` component: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\OrderResource\Pages\Components\OrderItemsTable::class => OrderItemsTableExtension::class, ]); ``` ### Available Methods | Method | Description | | :- | :- | | `extendOrderLinesTableColumns(): array` | Customize the columns displayed for order line items. | | `extendTable(): Table` | Customize the full order items table configuration. | # Extending the Admin Panel Source: https://docs.lunarphp.com/1.x/admin/extending/overview An overview of how to extend Lunar's admin panel pages and resources. The Lunar admin panel is highly customizable. Extensions allow adding and changing the behavior of existing Filament resources. This is useful for adding buttons, custom functionality, or modifying how data is displayed. ## Extending Pages To extend a page, create an extension class and register it with the `LunarPanel` facade. ### Extending an edit page The following example registers a custom extension for the `EditProduct` page: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; use Lunar\Admin\Filament\Resources\ProductResource\Pages\EditProduct; use App\Admin\Extensions\MyEditExtension; LunarPanel::extensions([ EditProduct::class => MyEditExtension::class, ]); ``` ### Extending a list page The following example registers a custom extension for the `ListProducts` page: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; use Lunar\Admin\Filament\Resources\ProductResource\Pages\ListProducts; use App\Admin\Extensions\MyListExtension; LunarPanel::extensions([ ListProducts::class => MyListExtension::class, ]); ``` ## Extending Resources Much like extending pages, resource extensions are created and registered with the `LunarPanel` facade. The following example registers a custom extension for the `ProductResource`: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; use Lunar\Admin\Filament\Resources\ProductResource; use App\Admin\Extensions\MyProductResourceExtension; LunarPanel::extensions([ ProductResource::class => MyProductResourceExtension::class, ]); ``` ## Extendable Resources All Lunar panel resources are extendable, allowing custom functionality to be added or existing behavior to be changed. ```php theme={null} use Lunar\Admin\Filament\Resources\ActivityResource; use Lunar\Admin\Filament\Resources\AttributeGroupResource; use Lunar\Admin\Filament\Resources\BrandResource; use Lunar\Admin\Filament\Resources\ChannelResource; use Lunar\Admin\Filament\Resources\CollectionGroupResource; use Lunar\Admin\Filament\Resources\CollectionResource; use Lunar\Admin\Filament\Resources\CurrencyResource; use Lunar\Admin\Filament\Resources\CustomerGroupResource; use Lunar\Admin\Filament\Resources\CustomerResource; use Lunar\Admin\Filament\Resources\DiscountResource; use Lunar\Admin\Filament\Resources\LanguageResource; use Lunar\Admin\Filament\Resources\OrderResource; use Lunar\Admin\Filament\Resources\ProductOptionResource; use Lunar\Admin\Filament\Resources\ProductResource; use Lunar\Admin\Filament\Resources\ProductTypeResource; use Lunar\Admin\Filament\Resources\ProductVariantResource; use Lunar\Admin\Filament\Resources\StaffResource; use Lunar\Admin\Filament\Resources\TagResource; use Lunar\Admin\Filament\Resources\TaxClassResource; use Lunar\Admin\Filament\Resources\TaxRateResource; use Lunar\Admin\Filament\Resources\TaxZoneResource; ``` ## Events The admin panel dispatches events for changes made through its relation managers and management pages, where an Eloquent model event alone would not describe what happened. These are useful for invalidating caches, syncing to an external system, or triggering downstream work. Every event lives in the `Lunar\Admin\Events` namespace and exposes a single public property, `$model`. For changes made through a relation manager, `$model` is the record that owns the relationship rather than the related record that changed. | Event | Dispatched when | `$model` | | :- | :- | :- | | `ChildCollectionCreated` | A child collection is created beneath another collection | Parent collection | | `CollectionProductAttached` | A product is attached to a collection | Collection | | `CollectionProductDetached` | A product is detached from a collection | Collection | | `CustomerAddressEdited` | A customer's address is edited | Address | | `CustomerUserEdited` | A user associated with a customer is edited | User | | `ModelChannelsUpdated` | A model's channel availability is updated | Owning model | | `ModelMediaUpdated` | A model's media is added, edited, or removed | Owning model | | `ModelPricesUpdated` | A model's prices are updated | Owning model | | `ModelUrlsUpdated` | A model's URLs are updated | Owning model | | `ProductAssociationsUpdated` | A product's associations are updated | Product | | `ProductCollectionsUpdated` | The collections a product belongs to are updated | Product | | `ProductCustomerGroupsUpdated` | A product's customer group availability is updated | Product | | `ProductPricingUpdated` | A product's customer group pricing is updated | Product | | `ProductVariantInventoryUpdated` Added in 1.5 | Stock is saved on the product or variant inventory page | Product variant | | `ProductVariantOptionsUpdated` | A product's option values are updated | Product | Listen for them as with any Laravel event: ```php theme={null} use Illuminate\Support\Facades\Event; use Lunar\Admin\Events\ProductVariantInventoryUpdated; Event::listen(ProductVariantInventoryUpdated::class, function (ProductVariantInventoryUpdated $event) { $event->model; // Lunar\Models\ProductVariant }); ``` > [!NOTE] > > These events cover changes made through the admin panel only. To react to changes from any source, including the storefront and queued jobs, observe the Eloquent model instead. # Extending Pages Source: https://docs.lunarphp.com/1.x/admin/extending/pages How to extend Create, Edit, List, View, and Relation pages in the Lunar admin panel. Lunar provides extension classes for each type of Filament page. These allow customizing headings, actions, widgets, form behavior, and lifecycle hooks. Place extension classes in the application, for example at `App\Lunar\Extensions\MyCreateExtension`. Once created, register the extension in a service provider. ## CreatePageExtension Extends create pages with custom headings, actions, widgets, and lifecycle hooks. ```php theme={null} use Filament\Actions; use Illuminate\Database\Eloquent\Model; use Lunar\Admin\Support\Extending\CreatePageExtension; class MyCreateExtension extends CreatePageExtension { public function heading($title): string { return $title . ' - Custom'; } public function subheading($title): ?string { return 'A custom subheading'; } public function headerActions(array $actions): array { return [ ...$actions, Actions\Action::make('Cancel'), ]; } public function formActions(array $actions): array { return [ ...$actions, Actions\Action::make('Create and Edit'), ]; } public function headerWidgets(array $widgets): array { return [ ...$widgets, MyCustomWidget::make(), ]; } public function footerWidgets(array $widgets): array { return [ ...$widgets, MyOtherWidget::make(), ]; } public function beforeCreate(array $data): array { // Modify data before validation $data['model_code'] .= 'ABC'; return $data; } public function beforeCreation(array $data): array { // Modify data after validation but before saving return $data; } public function afterCreation(Model $record, array $data): Model { // Perform actions after the record is created return $record; } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\CustomerGroupResource\Pages\CreateCustomerGroup::class => MyCreateExtension::class, ]); ``` ## EditPageExtension Extends edit pages with custom headings, actions, widgets, and lifecycle hooks. ```php theme={null} use Filament\Actions; use Illuminate\Database\Eloquent\Model; use Lunar\Admin\Support\Extending\EditPageExtension; class MyEditExtension extends EditPageExtension { public function heading($title, Model $record): string { return $title . ' - ' . $record->name; } public function subheading($title, Model $record): ?string { return 'Editing ' . $record->name; } public function headerActions(array $actions): array { return [ ...$actions, Actions\ActionGroup::make([ Actions\Action::make('View on Storefront'), Actions\Action::make('Copy Link'), Actions\Action::make('Duplicate'), ]), ]; } public function formActions(array $actions): array { return [ ...$actions, Actions\Action::make('Update and Continue'), ]; } public function headerWidgets(array $widgets): array { return [ ...$widgets, MyCustomWidget::make(), ]; } public function footerWidgets(array $widgets): array { return [ ...$widgets, MyOtherWidget::make(), ]; } public function beforeFill(array $data): array { // Modify data before the form is filled return $data; } public function beforeSave(array $data): array { // Modify data before saving return $data; } public function beforeUpdate(array $data, Model $record): array { // Modify data before the record is updated return $data; } public function afterUpdate(Model $record, array $data): Model { // Perform actions after the record is updated return $record; } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\ProductResource\Pages\EditProduct::class => MyEditExtension::class, ]); ``` ## ListPageExtension Extends list pages with custom headings, actions, widgets, and tabs. ```php theme={null} use Filament\Actions; use Filament\Resources\Components\Tab; use Illuminate\Database\Eloquent\Builder; use Lunar\Admin\Support\Extending\ListPageExtension; class MyListExtension extends ListPageExtension { public function heading($title): string { return $title . ' - Custom'; } public function subheading($title): ?string { return 'A custom subheading'; } public function headerActions(array $actions): array { return [ ...$actions, Actions\Action::make('Export'), ]; } public function getTabs(array $tabs): array { return [ ...$tabs, 'review' => Tab::make('Review') ->modifyQueryUsing(fn (Builder $query) => $query->where('status', 'review')), ]; } public function headerWidgets(array $widgets): array { return [ ...$widgets, MyCustomWidget::make(), ]; } public function footerWidgets(array $widgets): array { return [ ...$widgets, MyOtherWidget::make(), ]; } public function relationManagers(array $managers): array { return $managers; } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\ProductResource\Pages\ListProducts::class => MyListExtension::class, ]); ``` ## ViewPageExtension Extends view pages with custom headings and actions. ```php theme={null} use Filament\Actions; use Illuminate\Database\Eloquent\Model; use Lunar\Admin\Support\Extending\ViewPageExtension; class MyViewExtension extends ViewPageExtension { public function heading($title, Model $record): string { return $title . ' - ' . $record->name; } public function subheading($title, Model $record): ?string { return 'Viewing ' . $record->name; } public function headerActions(array $actions): array { return [ ...$actions, Actions\ActionGroup::make([ Actions\Action::make('Download PDF'), ]), ]; } public function headerWidgets(array $widgets): array { return [ ...$widgets, MyCustomWidget::make(), ]; } public function footerWidgets(array $widgets): array { return [ ...$widgets, MyOtherWidget::make(), ]; } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\OrderResource\Pages\ManageOrder::class => MyViewExtension::class, ]); ``` ## RelationPageExtension Extends relation pages with custom headings, actions, and table customization. Relation-style pages (those built on `Lunar\Admin\Support\Pages\BaseManageRelatedRecords`) include: * `ManageBrandCollections`, `ManageBrandProducts` * `ManageCollectionChildren`, `ManageCollectionProducts` * `ManageProductAssociations`, `ManageProductCollections`, `ManageProductVariants` * `ManageVariantMedia` * `ManageUrlsRelatedRecords` ```php theme={null} use Filament\Actions; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Illuminate\Database\Eloquent\Model; use Lunar\Admin\Support\Extending\RelationPageExtension; class MyRelationExtension extends RelationPageExtension { public function heading($title, Model $record): string { return $title . ' - Custom'; } public function subheading($title, Model $record): ?string { return 'A custom subheading'; } public function headerActions(array $actions): array { return [ ...$actions, Actions\ActionGroup::make([ Actions\Action::make('Download PDF'), ]), ]; } public function extendTable(Table $table): Table { return $table->columns([ ...$table->getColumns(), TextColumn::make('sku')->label('SKU'), ]); } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\ProductResource\Pages\ManageProductMedia::class => MyRelationExtension::class, ]); ``` ### Extending the table Added in 1.5 `extendTable` receives the page's default table and returns the modified instance. It is the same seam used by resource and relation-manager extensions, so columns, actions, filters, and query modifiers can all be applied without replacing the page class. When no extension is registered, the default table behavior is unchanged. ## Extending Pages in Addons When building an addon for Lunar, a defensive approach is needed when modifying forms since the contents may have been altered by other extensions. Use `getComponents()` to retrieve the currently registered components before appending new ones: ```php theme={null} public function extendForm(Form $form): Form { $form->schema([ ...$form->getComponents(true), // Gets the currently registered components TextInput::make('model_code'), ]); return $form; } ``` # Extending the Panel Source: https://docs.lunarphp.com/1.x/admin/extending/panel How to customize the Filament panel configuration for Lunar. The Filament panel can be customized when registering it in a service provider. The `LunarPanel::panel()` method provides direct access to the panel instance for configuration. For example, the following changes the panel's URL to `/admin` instead of the default `/lunar`: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; LunarPanel::panel(fn ($panel) => $panel->path('admin')) ->extensions([ // ... ]) ->register(); ``` ## Adding to the Panel The Filament panel supports adding new screens as Pages or Resources, as well as other customizations such as Livewire components, plugins, and navigation groups. ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; LunarPanel::panel(function ($panel) { return $panel ->pages([ // Register standalone Filament Pages SalesReport::class, RevenueReport::class, ]) ->resources([ // Register new Filament Resources OpeningTimeResource::class, BannerResource::class, ]) ->livewireComponents([ // Register Livewire components OrdersSalesChart::class, ])->plugin( // Register a Filament plugin new ShippingPlugin(), ) ->navigationGroups([ // Set the navigation groups 'Catalog', 'Sales', 'CMS', 'Reports', 'Shipping', 'Settings', ]); })->register(); ``` For further information, consult the [Filament documentation](https://filamentphp.com/docs). # Extending Relation Managers Source: https://docs.lunarphp.com/1.x/admin/extending/relation-managers How to extend Filament relation managers in the Lunar admin panel. Relation manager extensions allow modifying the form and table of any relation manager in the Lunar admin panel. Create a class that extends `RelationManagerExtension` and register it with the `LunarPanel` facade. ## Example The following example extends the `CustomerGroupPricingRelationManager` to add a custom column to the form and table: ```php theme={null} use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Lunar\Admin\Support\Extending\RelationManagerExtension; class MyCustomerGroupPricingExtension extends RelationManagerExtension { public function extendForm(Form $form): Form { return $form->schema([ ...$form->getComponents(withHidden: true), TextInput::make('custom_column'), ]); } public function extendTable(Table $table): Table { return $table->columns([ ...$table->getColumns(), TextColumn::make('product_code'), ]); } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\ProductResource\RelationManagers\CustomerGroupPricingRelationManager::class => MyCustomerGroupPricingExtension::class, ]); ``` ## Available Methods | Method | Description | | :- | :- | | `extendForm(Form $form)` | Modify the relation manager's form schema. | | `extendTable(Table $table)` | Modify the relation manager's table columns and configuration. | | `headerActions(array $actions)` | Add or modify header actions. | # Extending Resources Source: https://docs.lunarphp.com/1.x/admin/extending/resources How to extend Filament resources in the Lunar admin panel. Resource extensions allow modifying the form, table, relations, pages, and sub-navigation of any Lunar admin resource. Create a class that extends `ResourceExtension` and register it with the `LunarPanel` facade. ## Example The following example extends the `ProductResource` to add a custom column to the form and table, a custom relation manager, and additional pages: ```php theme={null} use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Lunar\Admin\Support\Extending\ResourceExtension; class MyProductResourceExtension extends ResourceExtension { public function extendForm(Form $form): Form { return $form->schema([ ...$form->getComponents(withHidden: true), TextInput::make('custom_column'), ]); } public function extendTable(Table $table): Table { return $table->columns([ ...$table->getColumns(), TextColumn::make('product_code'), ]); } public function getRelations(array $managers): array { return [ ...$managers, MyCustomProductRelationManager::class, ]; } public function extendPages(array $pages): array { return [ ...$pages, 'my-page-route-name' => MyPage::route('/{record}/my-page'), ]; } public function extendSubNavigation(array $nav): array { return [ ...$nav, MyPage::class, ]; } } // Typically placed in a service provider... LunarPanel::extensions([ \Lunar\Admin\Filament\Resources\ProductResource::class => MyProductResourceExtension::class, ]); ``` ## Available Methods | Method | Description | | :- | :- | | `extendForm(Form $form)` | Modify the resource's form schema. | | `extendTable(Table $table)` | Modify the resource's table columns and configuration. | | `getRelations(array $managers)` | Add or modify relation managers for the resource. | | `extendPages(array $pages)` | Add custom pages to the resource. | | `extendSubNavigation(array $nav)` | Add items to the resource's sub-navigation. | | `headerActions(array $actions)` | Add or modify header actions. | See the [Filament documentation](https://filamentphp.com/docs) for more details on building resources, relation managers, and pages. # Admin Panel Source: https://docs.lunarphp.com/1.x/admin/introduction An overview of Lunar's admin panel and how to register it. Lunar's admin panel is built on [Filament](https://filamentphp.com/), providing a feature-rich interface for managing an e-commerce store. The panel is designed to be extended and customized to suit any project. ## Features The admin panel allows store administrators to manage: * **Products** including variants, pricing, images, and associations * **Collections** organized into collection groups * **Orders** with full order lifecycle management * **Customers** and customer groups * **Discounts** with flexible conditions and rewards * **Settings** for channels, languages, currencies, taxes, tags, and more ## Registration If the core installation instructions or a starter kit were used, this registration is likely already in place. The `LunarPanel` facade must be registered in a service provider: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; class AppServiceProvider extends ServiceProvider { public function register(): void { LunarPanel::register(); } } ``` The panel is accessible at `/lunar` by default. This path and other panel options can be customized through the [panel configuration](/1.x/admin/extending/panel). # Extending Carts Source: https://docs.lunarphp.com/1.x/extending/carts The cart system can be extended with custom pipelines and modifiers to add business logic. ## Overview Carts are a central part of any e-commerce storefront. The cart system is designed to be easily extended, allowing any custom logic to be added throughout a cart's lifetime. ## Pipelines ### Adding a Cart Pipeline All pipelines are defined in `config/lunar/cart.php` ```php theme={null} 'pipelines' => [ /* * Run these pipelines when the cart is calculating. */ 'cart' => [ Lunar\Pipelines\Cart\CalculateLines::class, Lunar\Pipelines\Cart\ApplyShipping::class, Lunar\Pipelines\Cart\ApplyDiscounts::class, Lunar\Pipelines\Cart\CalculateTax::class, Lunar\Pipelines\Cart\Calculate::class, ], /* * Run these pipelines when the cart lines are being calculated. */ 'cart_lines' => [ Lunar\Pipelines\CartLine\GetUnitPrice::class, ], ], ``` You can add your own pipelines to the configuration, they might look something like: ```php theme={null} [ // ... App\Pipelines\Cart\CustomCartPipeline::class, ], ``` > [!TIP] > > Pipelines will run from top to bottom ## Actions During the lifecycle of a cart, various actions are taken. While generally what Lunar provides will be fine for most storefronts, there are times where something slightly different may be needed. For this reason, all actions are configurable and can be swapped out as needed. Actions are defined in `config/lunar/cart.php` and if you need to replace an action, check the class of the action you want to change to see what it is expecting. ## Action validation You may wish to provide some validation against actions before they run. Your own validation may look something like: ```php theme={null} parameters['quantity'] ?? 0; // ... if (!$condition) { return $this->fail('cart', 'Something went wrong'); } return $this->pass(); } } ``` You can then register this class against the corresponding action in `config/lunar/cart.php`: ```php theme={null} 'validators' => [ 'add_to_cart' => [ // ... \App\Validation\CartLine\CartLineQuantity::class, ], // ... ], ``` If validation fails, a `Lunar\Exceptions\Carts\CartException` will be thrown. Errors can be accessed in the same way as Laravel's own validation responses. ```php theme={null} try { $cart->setShippingOption($option); } catch (\Lunar\Exceptions\Carts\CartException $e) { $e->errors()->all(); } ``` # Extending Discounts Source: https://docs.lunarphp.com/1.x/extending/discounts Custom discount types can be registered to add additional discount logic beyond the built-in types. ## Overview If you want to add additional functionality to Discounts, you can register your own custom discount types. ## Registering a discount type. ```php theme={null} use Lunar\Facades\Discounts; Discounts::addType(MyCustomDiscountType::class); ``` ```php theme={null} label('My label') ->required(), ]; } /** * Mutate the model data before displaying it in the admin form. */ public function lunarPanelOnFill(array $data): array { // optionally do something with $data return $data; } /** * Mutate the form data before saving it to the discount model. */ public function lunarPanelOnSave(array $data): array { // optionally do something with $data return $data; } } ``` # Extending Models Source: https://docs.lunarphp.com/1.x/extending/models Lunar's Eloquent models can be extended with custom relationships and, when needed, replaced entirely with custom implementations. ## Overview Lunar provides a number of Eloquent models and quite often in custom applications additional relationships and functionality are needed. > [!WARNING] > > Rather than modifying fields on Lunar's core models, it is recommended to create your own Eloquent models and relate them to Lunar's models. This keeps custom data separate and avoids conflicts during upgrades. > > Add-on packages must never replace core models, as this would conflict with other packages and the end user's application. Add-ons should use dynamic relationships and their own models exclusively. ## Dynamic Eloquent Relationships The recommended way to extend Lunar's models is by using Laravel's dynamic relationships. This allows custom relationships to be added to any Lunar model without needing to replace it. ```php theme={null} use Lunar\Models\Order; use App\Models\Ticket; Order::resolveRelationUsing('ticket', function ($orderModel) { return $orderModel->belongsTo(Ticket::class, 'ticket_id'); }); ``` This should be registered in the `boot` method of a service provider. See the [Laravel documentation on dynamic relationships](https://laravel.com/docs/eloquent-relationships#dynamic-relationships) for more information. ## Replaceable Models For cases where dynamic relationships are not sufficient, all Lunar models are replaceable. This means Lunar can be instructed to use a custom model throughout the ecosystem using dependency injection. > [!NOTE] > > Most use cases are better served by dynamic relationships above. Model replacement should only be used when deeper customization is required, such as overriding methods or adding scopes. ### Registration Custom models should be registered within the `boot` method of a service provider. When registering models, the Lunar model's contract should be set as the first argument and the custom model implementation as the second. ```php theme={null} /** * Bootstrap any application services. * * @return void */ public function boot() { \Lunar\Facades\ModelManifest::replace( \Lunar\Models\Contracts\Product::class, \App\Model\Product::class, ); } ``` #### Registering multiple Lunar models. If multiple models need to be replaced, instead of replacing them one by one, a directory can be specified for Lunar to scan for models. This assumes that each model extends its counterpart model, e.g. `App\Models\Product` extends `Lunar\Models\Product`. ```php theme={null} /** * Bootstrap any application services. * * @return void */ public function boot() { \Lunar\Facades\ModelManifest::addDirectory( __DIR__.'/../Models' ); } ``` ### Route binding Route binding is supported and simply requires the relevant contract class to be injected. ```php theme={null} Route::get('products/{id}', function (\Lunar\Models\Contracts\Product $product) { $product; // App\Models\Product }); ``` ### Relationship support If a model used in a relationship is replaced, the custom model will be returned via relationship methods. For example, assuming a custom `App\Models\ProductVariant` has been registered: ```php theme={null} // In a service provider. public function boot() { \Lunar\Facades\ModelManifest::replace( \Lunar\Models\Contracts\ProductVariant::class, \App\Model\ProductVariant::class, ); } // Somewhere else in your code... $product = \Lunar\Models\Product::first(); $product->variants->first(); // App\Models\ProductVariant ``` ### Static call forwarding If a custom model has additional methods, those functions can be called directly from the Lunar model instance. For example, to provide a new function on a product variant model: ```php theme={null} [ 'creation' => [ Lunar\Pipelines\Order\Creation\FillOrderFromCart::class, Lunar\Pipelines\Order\Creation\CreateOrderLines::class, Lunar\Pipelines\Order\Creation\CreateOrderAddresses::class, Lunar\Pipelines\Order\Creation\CreateShippingLine::class, Lunar\Pipelines\Order\Creation\CleanUpOrderLines::class, Lunar\Pipelines\Order\Creation\MapDiscountBreakdown::class, // ... ], ], ``` You can add your own pipelines to the configuration, they might look something like: ```php theme={null} [ 'creation' => [ // ... App\Pipelines\Orders\CustomOrderPipeline::class, ], ], ``` > [!TIP] > > Pipelines will run from top to bottom # Extending Payments Source: https://docs.lunarphp.com/1.x/extending/payments Custom payment drivers can be added to support any payment provider. ## Overview Lunar provides an easy way for you to add your own payment drivers, by default, there is a basic `OfflinePayment` driver that ships with Lunar, additional providers should be added to your Storefront via addons. Below is a list of available payment drivers. ## Available drivers ### First party * [Stripe](https://github.com/lunarphp/stripe) ### Community > Made a custom driver that should be listed here? Get in touch on the Lunar discord channel to get it added. ## Building your own A payment driver should take into account 2 fundamentals: * Capturing a payment (whether straight away, or at a later date) * Refunding an existing payment ### Registering your driver ```php theme={null} use Lunar\Facades\Payments; Payments::extend('custom', function ($app) { return $app->make(CustomPayment::class); }); ``` ### The payment driver class The following is the complete class, which is then broken down below. ```php theme={null} order) { if (!$this->order = $this->cart->order) { $this->order = $this->cart->createOrder(); } } // ... $response = new PaymentAuthorize( success: true, message: 'The payment was successful', orderId: $this->order->id, paymentType: 'custom-type' ); PaymentAttemptEvent::dispatch($response); return $response; } /** * {@inheritDoc} */ public function refund(Transaction $transaction, int $amount = 0, $notes = null): PaymentRefund { // ... return new PaymentRefund(true); } /** * {@inheritDoc} */ public function capture(Transaction $transaction, $amount = 0): PaymentCapture { // ... return new PaymentCapture(true); } } ``` This is the most basic implementation of a driver, extending the `AbstractPayment` class provided by Lunar. This class contains useful helpers that can be used in custom drivers. [See available methods](#abstract-class-methods) #### Releasing payments ```php theme={null} public function authorize(); ``` This is where you'd check the payment details which have been passed in, create any transactions for the order and return the response. If payment is not being taken straight away, any transactions should be set to the type of `intent`. When the payment is later captured, it is recommended to create another transaction that is related to the intent via the `parent_transaction_id`. #### Capturing payments ```php theme={null} public function capture(Transaction $transaction, $amount = 0): PaymentCapture ``` When you have a transaction that has a type of `intent` the Staff member who is logged into the hub can then decide to capture it so the card used gets charged the amount that has been authorised. You can pass an optional amount, but be cautious as you generally cannot capture an amount that exceeds the original amount on the `intent` transaction. If you capture an amount less, services like Stripe will treat that as a partial refund and no further captures can take place on that order. Here you should create an additional transaction against the order to show how much has been captured. #### Refunding payments ```php theme={null} public function refund(Transaction $transaction, int $amount = 0, $notes = null): PaymentRefund ``` When refunding a transaction, you can only do so to one that's been captured. If you need to refund an order that hasn't been captured you should instead capture an amount less to what's been authorised. You should only refund transactions with the type `capture`. ## The AbstractPayment class ### Available methods * [`cart`](#cart) * [`order`](#order) * [`withData`](#withData) * [`setConfig`](#setconfig) #### `cart` ```php theme={null} public function cart(Cart $cart): self ``` Sets the `$cart` property on the payment driver. When using the `authorize` method, it is recommended to expect a `$cart` instance and check for the existence of an order. #### `order` ```php theme={null} public function order(Order $order): self ``` Sets the `$order` property on the payment driver. #### `withData` ```php theme={null} public function withData(array $data): self ``` This method allows you to add any additional data to the payment driver, this can be anything that the payment driver needs to function, for example. ```php theme={null} Payments::driver('stripe')->withData([ 'payment_intent' => $paymentIntentId ])->authorize(); ``` #### `setConfig` ```php theme={null} public function setConfig(array $config): self ``` Here you can set up any additional config for this payment driver. By default, this will be called when you register your payment driver and will take any values which are set in `config/lunar/payments.php` for that type. ## Creating transactions Depending on how your driver works, you're likely going to need to create some transactions depending on different scenarios. ### Database Schema ``` Lunar\Models\Transaction ``` | Field | Type | Description | | :- | :- | :- | | `id` | `bigint` | Primary key | | `parent_transaction_id` | `foreignId` `nullable` | The ID of the preceding transaction | | `order_id` | `foreignId` | The associated order | | `success` | `boolean` | Whether the transaction succeeded | | `type` | `enum` | One of `intent`, `capture`, or `refund` | | `driver` | `string` | The payment driver, e.g. `stripe` | | `amount` | `integer` | Amount in the currency's smallest unit, e.g. `10000` | | `reference` | `string` | Provider reference, e.g. `STRIPE_123456` | | `status` | `string` | Provider-specific status | | `notes` | `string` `nullable` | Any additional notes for the transaction | | `card_type` | `string` `nullable` | Card brand, e.g. `visa` | | `last_four` | `string` `nullable` | Last four digits of the card | | `meta` | `json` `nullable` | Additional provider data | | `captured_at` | `dateTime` `nullable` | When the payment was captured | | `created_at` | `timestamp` `nullable` | | | `updated_at` | `timestamp` `nullable` | | ### Best Practices #### Releasing When releasing a payment, if you're not charging the card straight away, you should create a transaction with type `intent`. This tells Lunar you intend to charge the card at a later date. ```php theme={null} Transaction::create([ //... 'type' => 'intent', ]); ``` If you are charging the card straight away, set the type to `capture`. ```php theme={null} Transaction::create([ //... 'type' => 'capture', ]); ``` #### Capturing > [!TIP] > > If the card is already being charged, this step can be skipped as payment has already been received. When capturing a transaction, you should create an additional transaction with the amount that's been captured. Even if this is the same amount as the `intent` transaction. ```php theme={null} $intent = Transaction::whereType('intent')->first(); Transaction::create([ //... 'parent_transaction_id' => $intent->id, 'type' => 'capture', 'amount' => 2000, ]); ``` #### Refunding ```php theme={null} $capture = Transaction::whereType('capture')->first(); Transaction::create([ //... 'parent_transaction_id' => $capture->id, 'type' => 'refund', ]); ``` # Extending Search Source: https://docs.lunarphp.com/1.x/extending/search Search indexing can be extended to customize searchable, sortable, and filterable fields. ## Overview Good search is the backbone of any storefront, so Lunar aims to make this as extensible as possible. Custom fields can be indexed for the storefront without compromising what Lunar requires for the admin panel. There are three things to consider when you want to extend the search: * Searchable fields * Sortable fields * Filterable fields ## Default index values Eloquent models which use the `Lunar\Base\Traits\Searchable` trait will use an indexer class to tell Scout how each model should be indexed. If an indexer isn't mapped in the config, the default `ScoutIndexer` (provided by Lunar) will be used. This class will map a basic set of fields to the search index: * The ID of the model * Any `searchable` attributes. Some models require a bit more information to be indexed, such as SKU's, prices etc. For these scenarios, dedicated indexers have been created and are mapped in the config already. #### `Lunar\Search\ProductIndexer` Fields which are indexed: * The ID of the model * Any `searchable` attributes. * The product `status` * The product `product_type` * The `brand` (if applicable) * The ProductVariant `skus` related to the product. * The `created_at` timestamp ## Mapping custom indexers All indexers are mapped in `config/lunar/search.php` under `indexers`. If a model isn't mapped here, the default `ScoutIndexer` is used. To change how each model is indexed, map it like so: ```php theme={null} return [ // ... 'indexers' => [ Lunar\Models\Product::class => App\Search\CustomProductIndexer::class, ], ], ``` ## Creating a custom indexer To create your own indexer, simply create a custom class like so: ```php theme={null} with([ 'thumbnail', 'variants', 'productType', 'brand', ]); } // Scout method to get the ID used for indexing public function getScoutKey(Model $model): mixed { return $model->getKey(); } // Scout method to get the column used for the ID. public function getScoutKeyName(Model $model): mixed { return $model->getKeyName(); } // Simple array of any sortable fields. public function getSortableFields(): array { return [ 'created_at', 'updated_at', ]; } // Simple array of any filterable fields. public function getFilterableFields(): array { return [ '__soft_deleted', ]; } // Return an array representing what should be sent to the search service e.g. Algolia public function toSearchableArray(Model $model): array { return array_merge([], $this->mapSearchableAttributes($model)); } } ``` The `ScoutIndexer` class implements the `Lunar\Search\Interfaces\ScoutIndexerInterface` interface. If a custom indexer does not extend `ScoutIndexer`, it must implement this interface directly. There are some methods which are available on `ScoutIndexer` but not defined on the interface: #### mapSearchableAttributes ```php theme={null} mapSearchableAttributes(Model $model): array ``` This method will take all `searchable` attributes for the model attribute type and map them into the index, this means when you add searchable attributes in the hub they will automatically be added to the index. # Extending Shipping Source: https://docs.lunarphp.com/1.x/extending/shipping Custom shipping options can be added to the checkout using shipping modifiers. ## Overview On your checkout, if your customer has added an item that needs shipping, you're likely going to want to display some shipping options. Currently the best way to do this is to implement your own by adding a `ShippingModifier` and adding using that to determine what shipping options you want to make available and add them to the `ShippingManifest` class. ## Adding a Shipping Modifier Create your own custom shipping provider: ```php theme={null} namespace App\Modifiers; use Lunar\Base\ShippingModifier; use Lunar\DataTypes\Price; use Lunar\DataTypes\ShippingOption; use Lunar\Facades\ShippingManifest; use Lunar\Models\Cart; use Lunar\Models\Currency; use Lunar\Models\TaxClass; class CustomShippingModifier extends ShippingModifier { public function handle(Cart $cart, \Closure $next) { // Get the tax class $taxClass = TaxClass::first(); ShippingManifest::addOption( new ShippingOption( name: 'Basic Delivery', description: 'A basic delivery option', identifier: 'BASDEL', price: new Price(500, $cart->currency, 1), taxClass: $taxClass ) ); ShippingManifest::addOption( new ShippingOption( name: 'Pick up in store', description: 'Pick your order up in store', identifier: 'PICKUP', price: new Price(0, $cart->currency, 1), taxClass: $taxClass, // This is for your reference, so you can check if a collection option has been selected. collect: true ) ); // Or add multiple options, it's your responsibility to ensure the identifiers are unique ShippingManifest::addOptions(collect([ new ShippingOption( name: 'Basic Delivery', description: 'A basic delivery option', identifier: 'BASDEL', price: new Price(500, $cart->currency, 1), taxClass: $taxClass ), new ShippingOption( name: 'Express Delivery', description: 'Express delivery option', identifier: 'EXDEL', price: new Price(1000, $cart->currency, 1), taxClass: $taxClass ) ])); return $next($cart); } } ``` In your service provider: ```php theme={null} public function boot(\Lunar\Base\ShippingModifiers $shippingModifiers) { $shippingModifiers->add( CustomShippingModifier::class ); } ``` # Extending Taxation Source: https://docs.lunarphp.com/1.x/extending/taxation Taxation is driver-based, allowing custom tax calculation logic to replace or extend the default system. ## Overview Taxation is complex and sometimes what Lunar offers out of the box is not sufficient. This is why taxation is driver-based, allowing custom logic to be added as needed. By default, a `SystemTaxDriver` is used, which relies on Lunar's internal models and database as outlined in the [Taxation](/1.x/reference/taxation) reference. To use a custom implementation, the driver can be changed in the `config/lunar/taxes.php` config file. ```php theme={null} 'system', ]; ``` ## Writing a Custom Driver A custom driver must implement the `Lunar\Base\TaxDriver` interface: ```php theme={null} make(TaxJar::class); }); } ``` Then set the driver in the `config/lunar/taxes.php` config: ```php theme={null} 'taxjar', ]; ``` # AI Development Source: https://docs.lunarphp.com/1.x/getting-started/overview/ai-development Use Lunar documentation with AI tools like Claude, ChatGPT, Cursor, and VS Code Lunar's documentation is designed to work seamlessly with AI-powered development tools. Whether using an AI assistant to generate storefront code or querying the docs from an IDE, several built-in features make this possible. ## Laravel Boost Skill Added in 1.5 Lunar ships a skill for [Laravel Boost](https://github.com/laravel/boost), giving an AI assistant a working orientation in a Lunar project: where the models and facades live, which config files matter, and which documentation page covers each task. Install it into the project with the Boost Artisan command: ```sh theme={null} php artisan boost:add-skill lunarphp/lunar ``` The skill activates when the assistant is working with Lunar concepts such as products, variants, carts, checkout, orders, discounts, payments, pricing, collections, attributes, or tax. It also instructs the assistant to fetch current documentation rather than answering from memory, since the API changes between minor versions. > [!NOTE] > > Boost's own `search-docs` tool does not index Lunar. The skill points the assistant at the MCP server and `llms.txt` described below instead. ## llms.txt The Lunar documentation site automatically provides an `llms.txt` file at the root of the docs domain. Similar to how `sitemap.xml` helps search engines index a website, `llms.txt` helps large language models discover and understand documentation content. Two files are available: | File | URL | Description | | - | - | - | | `llms.txt` | [docs.lunarphp.com/llms.txt](https://docs.lunarphp.com/llms.txt) | Structured listing of all pages with descriptions | | `llms-full.txt` | [docs.lunarphp.com/llms-full.txt](https://docs.lunarphp.com/llms-full.txt) | Full documentation content in a single file | The `llms.txt` file lists every documentation page along with its description, making it useful for AI tools that need to locate specific topics. The `llms-full.txt` file consolidates all documentation into one file, which is ideal for AI tools that benefit from ingesting the entire knowledge base at once. > [!TIP] > > When pasting documentation context into an AI chat, use `llms-full.txt` to give the model comprehensive knowledge of Lunar's API and features. ## MCP Server Lunar's documentation includes a built-in [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server. MCP allows AI applications to search and retrieve documentation directly, providing more accurate and up-to-date responses than relying on the model's training data alone. The MCP server is available at: ``` https://docs.lunarphp.com/mcp ``` ### Connecting from AI Tools > [!NOTE] > > The MCP server supports filtering by documentation version using a `version` parameter (e.g., `v1.x` or `v0.x`). #### Claude Code ```bash theme={null} claude mcp add lunar-docs --transport http https://docs.lunarphp.com/mcp ``` #### Cursor Open the Command Palette and select **MCP: Add Server**, then add the following to the MCP configuration: ```json theme={null} { "mcpServers": { "lunar-docs": { "url": "https://docs.lunarphp.com/mcp" } } } ``` #### VS Code Create or update `.vscode/mcp.json` in the project root: ```json theme={null} { "servers": { "lunar-docs": { "type": "http", "url": "https://docs.lunarphp.com/mcp" } } } ``` #### Claude (Web) Navigate to **Settings > Connectors > Add custom connector**, then enter a name and the MCP server URL. ## Markdown Export Any documentation page can be viewed as plain Markdown by appending `.md` to its URL. For example: ``` https://docs.lunarphp.com/1.x/reference/carts.md ``` This is useful for feeding specific pages into AI tools as context. Markdown is more token-efficient than HTML, resulting in faster processing and better response quality. ## Contextual Menu Each documentation page includes a contextual menu that provides quick access to AI-related actions: * **Copy as Markdown** for pasting into any AI tool * **Open in Claude**, **ChatGPT**, or **Perplexity** with the current page loaded as context * **Install MCP server** directly into Cursor or VS Code # Contributing Source: https://docs.lunarphp.com/1.x/getting-started/overview/contributing How to contribute code, report bugs, and improve the documentation. Lunar is an open source project and welcomes contributions of all kinds, from bug reports and documentation improvements to new features and code fixes. ## Monorepo Lunar uses a monorepo at [lunarphp/lunar](https://github.com/lunarphp/lunar) to manage its codebase. All packages, tests, and admin panel code live in a single repository. [Monorepos](https://en.wikipedia.org/wiki/Monorepo) are common in large projects and allow changes that span multiple packages to be developed and reviewed together. ## Contributing Code The basic process for contributing code to Lunar is: 1. Fork the [lunarphp/lunar](https://github.com/lunarphp/lunar) monorepo 2. Clone the fork locally 3. Create a new branch for the change 4. Make changes and write tests 5. Ensure the full test suite passes 6. Submit a pull request > [!TIP] > > For a step-by-step walkthrough of setting up the monorepo inside a Laravel application, see the [Local Development](/1.x/getting-started/overview/local-development) guide. ### Coding Standards Lunar follows the [Laravel coding style](https://laravel.com/docs/contributions#coding-style) and uses [Laravel Pint](https://laravel.com/docs/pint) to enforce it. Before submitting a pull request, run Pint from the repository root: ```bash theme={null} vendor/bin/pint ``` ### Running Tests Lunar uses [Pest](https://pestphp.com/) for its test suite. Tests can be run from the repository root: ```bash theme={null} vendor/bin/pest ``` All existing tests must continue to pass, and new features or bug fixes should include corresponding test coverage. ## Reporting a Bug If a bug is discovered, please open a GitHub issue on the [lunarphp/lunar](https://github.com/lunarphp/lunar/issues) repository. The issue should include: **At minimum:** * A clear title and description of the issue * Steps to reproduce the behavior **Ideally:** * The version of Lunar, PHP, and Laravel in use * An accompanying pull request with a failing test that demonstrates the issue Providing as much detail as possible gives the issue the best chance of being resolved quickly. Creating an issue does not guarantee immediate activity; maintainers review issues as time allows. > [!WARNING] > > Security vulnerabilities should not be reported as public issues. See the [Security](/1.x/getting-started/overview/security) page for responsible disclosure instructions. ## Proposing a Feature Before investing time on a new feature, it is strongly recommended to start a [discussion](https://github.com/lunarphp/lunar/discussions) first. This allows the community and maintainers to provide feedback on whether the feature aligns with Lunar's direction before any code is written. Prototyping the feature alongside the discussion is welcome if it helps illustrate the proposal. ## Making a Pull Request When submitting a [pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request), the repository provides a template to guide the submission. A well-structured pull request should include: * A title that clearly summarizes the change * A description explaining what the change does and why it is valuable * References to any related issues (e.g., `Fixes #123`) * A label of `bug`, `enhancement`, or `feature` * Automated tests with adequate coverage * Any relevant documentation updates Pull requests that are missing key information or are unclear in their purpose may be delayed or closed. ## Documentation Lunar's documentation is maintained in the [lunarphp/docs](https://github.com/lunarphp/docs) repository. It is built with [Mintlify](https://mintlify.com/) and all content is written in MDX. To contribute documentation changes: 1. Fork the [lunarphp/docs](https://github.com/lunarphp/docs) repository 2. Install the Mintlify CLI and run the dev server locally 3. Make changes and verify they render correctly 4. Submit a pull request ```bash theme={null} npm i -g mint mint dev ``` > [!NOTE] > > Any new page must also be added to the `docs.json` navigation configuration, or it will not appear in the sidebar. # Introduction Source: https://docs.lunarphp.com/1.x/getting-started/overview/introduction Start building e-commerce with Laravel Lunar is a headless e-commerce package for [Laravel](https://laravel.com/) that provides everything needed to build a fully featured online store. ## Why Lunar? Unlike hosted platforms such as Shopify or WooCommerce, Lunar gives developers complete ownership of the codebase, the data, and the storefront. It handles the complex e-commerce logic — products, carts, orders, payments, discounts, taxation, and more — while leaving full creative control over the customer-facing experience. Because Lunar is a Laravel package (not a standalone application), it integrates directly into any Laravel project. There is no separate system to maintain, no external API to call, and no vendor lock-in. ## Tech Stack Lunar is made up of two primary Composer packages: * **`lunarphp/core`** — the e-commerce engine: models, pipelines, pricing, search, and all core functionality. * **`lunarphp/lunar`** — the admin panel, built on [Filament](https://filamentphp.com/), for managing products, orders, customers, and more. > [!NOTE] > > Although the admin panel uses Laravel Livewire, there is no requirement for the storefront to use Livewire. ## Key Features * **Product catalog** — products, variants, options, collections, associations, and flexible attribute system * **Cart and checkout** — cart management with built-in pipelines for validation, tax calculation, and shipping * **Order management** — full order lifecycle with statuses, transactions, and PDF support * **Discounts** — percentage, fixed amount, and "buy X get Y" discount types with conditions and limitations * **Payments** — first-party drivers for Stripe, PayPal, and Opayo, plus an extensible payment interface * **Search** — Algolia and Meilisearch support through Laravel Scout with pre-configured indexing * **Multi-channel and multi-currency** — sell across multiple channels with localized pricing * **Taxation** — configurable tax classes, zones, and rates * **Extensible admin panel** — customize pages, resources, and relation managers through Filament ## Getting Started > [card] [Install Lunar](/1.x/getting-started/setup/installation) > > Add Lunar to a Laravel application with Composer. > [card] [Livewire Starter Kit](/1.x/getting-started/starter-kits/livewire) > > Spin up a fully working storefront as a starting point. > [card] [Storefront Guides](/1.x/guides/catalog-menu) > > Step-by-step guides for building catalog, cart, and checkout flows. # Local Development Source: https://docs.lunarphp.com/1.x/getting-started/overview/local-development Setting up the Lunar monorepo locally for development and contribution. This guide walks through setting up the Lunar monorepo inside a Laravel application for local development and contribution. ## Prerequisites * PHP 8.2 or higher * A working [Laravel](https://laravel.com/docs/installation) application * [Composer](https://getcomposer.org/) * [Git](https://git-scm.com/) ## Setting Up the Monorepo ### 1. Create a packages directory In the root of the Laravel application, create a `packages` directory to hold the monorepo source code. ```bash theme={null} mkdir packages ``` Add `packages` to the `.gitignore` file so it is not committed to the application's repository. ``` /packages ``` ### 2. Clone the repository Fork the [lunarphp/lunar](https://github.com/lunarphp/lunar) repository on GitHub, then clone the fork into the `packages` directory. ```bash theme={null} cd packages git clone https://github.com/YOUR-USERNAME/lunar.git ``` This places the monorepo at `packages/lunar/`. ### 3. Configure Composer Back in the Laravel application's `composer.json`, add a path repository and require the monorepo package. ```json theme={null} { "repositories": [ { "type": "path", "url": "packages/*", "symlink": true } ], "minimum-stability": "dev", "require": { "lunarphp/lunarmono": "*" } } ``` The `lunarphp/lunarmono` package is the monorepo root and includes all Lunar packages: core, admin panel, payment drivers, and add-ons. > [!NOTE] > > The `symlink` option ensures that changes made in the `packages/lunar` directory are immediately reflected in the application without needing to run `composer update` after every edit. ### 4. Install dependencies Run Composer from the Laravel application's root directory to install the local packages. ```bash theme={null} composer update ``` Once complete, follow the standard [installation](/1.x/getting-started/setup/installation) steps to run migrations and publish assets. ## Running Tests Lunar uses [Pest](https://pestphp.com/) for testing. Tests can be run from the monorepo root at `packages/lunar/`. ```bash theme={null} cd packages/lunar vendor/bin/pest ``` To run tests for a specific package, use the `--filter` flag or point to a specific test directory. ```bash theme={null} vendor/bin/pest tests/core vendor/bin/pest tests/admin ``` All existing tests must continue to pass before submitting a pull request. ## Code Style Lunar follows the [Laravel coding style](https://laravel.com/docs/contributions#coding-style) and uses [Laravel Pint](https://laravel.com/docs/pint) for enforcement. Run Pint from the monorepo root before committing changes. ```bash theme={null} vendor/bin/pint ``` ## Monorepo Structure The monorepo contains the following packages under `packages/`: | Directory | Composer Package | Description | | - | - | - | | `core` | `lunarphp/core` | Core e-commerce functionality | | `admin` | `lunarphp/lunar` | Admin panel built with Filament | | `stripe` | `lunarphp/stripe` | Stripe payment driver | | `paypal` | `lunarphp/paypal` | PayPal payment driver | | `opayo` | `lunarphp/opayo` | Opayo payment driver | | `search` | `lunarphp/search` | Search with Typesense and Meilisearch support | | `meilisearch` | `lunarphp/meilisearch` | Meilisearch addon | | `table-rate-shipping` | `lunarphp/table-rate-shipping` | Table rate shipping addon | Tests for each package are located in the top-level `tests/` directory, organized by package name. ## Next Steps With local development set up, see the [Contributing](/1.x/getting-started/overview/contributing) guide for information on coding standards, submitting pull requests, and reporting bugs. # Security Source: https://docs.lunarphp.com/1.x/getting-started/overview/security Security features and best practices for Lunar-powered storefronts. Lunar is built on Laravel's security foundations and adds e-commerce-specific protections for payments, admin access, and customer data. ## Reporting Vulnerabilities If a security issue is discovered in Lunar, please reach out privately on [Discord](https://lunarphp.com/discord) or via email at [security@lunarphp.io](mailto:security@lunarphp.io) so the issue can be addressed and patched as soon as possible. Do not open public GitHub issues for security vulnerabilities. ## Securing Laravel Lunar inherits Laravel's built-in security features including CSRF protection, encryption, and hashed passwords. Before deploying to production, review these Laravel guides: * [Deployment](https://laravel.com/docs/deployment) * [Encryption](https://laravel.com/docs/encryption) * [Hashing](https://laravel.com/docs/hashing) ## Admin Panel Security The admin panel uses a dedicated `staff` authentication guard, separate from your storefront's user authentication. This means admin sessions are completely isolated from customer sessions. ### Two-Factor Authentication Lunar's admin panel supports two-factor authentication (2FA) out of the box. In production environments, 2FA can be enforced for all staff members: ```php theme={null} use Lunar\Admin\LunarPanelManager; LunarPanelManager::forceTwoFactorAuth(); ``` To disable 2FA entirely (not recommended for production): ```php theme={null} LunarPanelManager::disableTwoFactorAuth(); ``` When enabled, staff members are prompted to set up 2FA on their next login and are provided with recovery codes for account recovery. ### Role-Based Access Control Lunar uses [Spatie Laravel Permission](https://spatie.be/docs/laravel-permission) for granular access control. Permissions are scoped to the `staff` guard and support hierarchical grouping with dot notation (e.g., `settings:manage-staff`). For more details on configuring roles and permissions, see the [Access Control](/1.x/admin/extending/access-control) documentation. ### Session Protection The admin panel applies the following middleware to all routes: * **CSRF verification** prevents cross-site request forgery attacks * **Cookie encryption** ensures cookies cannot be tampered with * **Session authentication** regenerates the session ID on authentication changes, preventing session fixation attacks ## Payment Security ### PCI Compliance Lunar does not store sensitive card data. All payment processing is delegated to PCI-compliant providers such as Stripe, PayPal, and Opayo. Only non-sensitive reference data is stored locally: * Last four digits of the card number * Card type/brand * Transaction reference IDs Raw card numbers, CVVs, and full expiry dates are never stored in the database. ### Webhook Verification Payment add-ons such as Stripe automatically verify webhook signatures before processing events. This ensures that incoming webhook requests genuinely originate from the payment provider and have not been tampered with. ### 3D Secure & Strong Customer Authentication The Opayo add-on includes built-in support for 3D Secure and Strong Customer Authentication (SCA/PSD2). The Stripe add-on handles SCA through Stripe's Payment Intents API. These protocols add an additional layer of verification during checkout to reduce fraud. ## Cart & Session Security Lunar's cart session manager ties carts to the authenticated user when available, preventing cart hijacking. On logout, cart sessions are automatically cleared through the `CartSessionAuthListener`, ensuring abandoned sessions cannot be reused. These behaviors are configurable in `config/lunar/cart_session.php`: | Option | Description | | :- | :- | | `session_key` | The session key used to store the cart identifier | | `auto_create` | Whether to create a cart automatically when none exists | | `delete_on_forget` | Whether to delete cart data from the database on logout | ## Activity Logging Lunar uses [Spatie Activity Log](https://spatie.be/docs/laravel-activitylog) to maintain an audit trail of changes to core models including orders, transactions, and carts. Every change records what was modified, when, and by whom. Activity logs are viewable from the admin panel. Sensitive fields can be excluded from logging on a per-model basis to prevent unnecessary exposure. ## Securing Search Depending on the search driver in use, additional steps may be needed to protect indexed data in production. To provide a rich search experience in the admin panel, Lunar indexes several models, some of which may contain sensitive information. ### What Is Sensitive Information? Sensitive information includes any data that contains details about customers or orders, whether personally identifiable or not. This includes addresses, email addresses, names, and order details. ### Lunar's Indexes Index names are relative to the `SCOUT_PREFIX` environment variable. | Model | Index | Contains Sensitive Information | | :- | :- | :- | | `Lunar\Models\Product` | `products` | No | | `Lunar\Models\Collection` | `collections` | No | | `Lunar\Models\ProductOption` | `product_options` | No | | `Lunar\Models\Customer` | `customers` | Yes | | `Lunar\Models\Order` | `orders` | Yes | ### Securing Meilisearch In a production environment, an API key must be set to control access to Meilisearch endpoints. It is recommended to use two API keys: one for admin tasks such as indexing documents (read/write) and one solely for reading. See: [Run Meilisearch in production](https://docs.meilisearch.com/learn/cookbooks/running_production.html) ### Securing Algolia Algolia provides many security features out of the box, along with additional steps to further lock down access. See: [Algolia Security Best Practices](https://www.algolia.com/doc/guides/security/security-best-practices/) ## Production Checklist Before deploying a Lunar-powered storefront to production, verify the following: * [ ] `APP_DEBUG` is set to `false` * [ ] `APP_ENV` is set to `production` * [ ] All payment provider API keys use production credentials, not test keys * [ ] Webhook secrets are configured for payment providers * [ ] Two-factor authentication is enabled (or enforced) for admin staff * [ ] Staff roles and permissions are configured, not all staff given admin access * [ ] Search API keys are restricted to the minimum required access * [ ] HTTPS is enforced for all traffic * [ ] The `APP_KEY` is set and kept secret # Upgrade Guide Source: https://docs.lunarphp.com/1.x/getting-started/overview/upgrade-guide Instructions for upgrading between Lunar versions, including breaking changes and migration steps. This page covers the steps required to upgrade between Lunar releases, along with any breaking changes or manual actions needed for each version. ## General Upgrade Instructions > [!WARNING] > > Before upgrading, back up the database and commit (or stash) any uncommitted changes. This makes it easy to roll back if something goes wrong. Update the Lunar package to the latest version: ```sh theme={null} composer update lunarphp/lunar ``` Run any new migrations: ```sh theme={null} php artisan migrate ``` After migrating, clear cached config and views to ensure the application picks up any changes: ```sh theme={null} php artisan optimize:clear ``` > [!TIP] > > Pin Lunar to a specific minor version in `composer.json` (e.g., `"lunarphp/lunar": "^1.4"`) to avoid unexpected breaking changes when running `composer update`. Review the version-specific notes below for any additional steps required by the target release. *** ## 1.5 > [!WARNING] > > **Breaking changes ahead.** Lunar 1.5 raises the minimum PHP and Laravel versions, upgrades the admin panel to Filament v4, and changes a number of database columns. Every section below should be reviewed before upgrading; skipping steps will leave the application in a broken state. > [!NOTE] > > **Filament v4 only.** Lunar 1.5 upgrades the admin panel to Filament v4 and drops support for Filament v3. Projects that need to stay on Filament v3 should remain on the [1.4 release line](#14), which is the final Lunar version built on Filament v3. > [!TIP] > > Test the upgrade on a staging environment before applying it to production. Filament v4 and the Filament v3 to v4 migration account for most of the work involved. ### Summary of breaking changes * **PHP 8.3+ required.** PHP 8.2 is no longer supported. * **Laravel 12 or 13 required.** Laravel 11 is no longer supported. * **Admin panel upgraded to Filament v4.** Filament v3 is no longer supported. Custom resources, pages, widgets, and actions must be migrated to the new APIs. * **Staff two-factor columns renamed.** `two_factor_secret` → `app_authentication_secret`, `two_factor_recovery_codes` → `app_authentication_recovery_codes`, and `two_factor_confirmed_at` removed. * **Nested set package replaced.** `kalnoy/nestedset` is replaced by `lunarphp/nestedset`, which changes the trait and query builder namespaces used by `Lunar\Models\Collection`. * **Order line purchasable morph is now nullable.** Shipping lines no longer store a placeholder morph, so `$orderLine->purchasable` returns `null` for them. * **Shipping method `cutoff` column removed.** Method availability is now controlled by an availability schedule. Each item is covered in detail below. ### High Impact #### PHP and Laravel requirements Lunar 1.5 raises the minimum supported versions: * PHP 8.3 or later (PHP 8.2 is no longer supported). * Laravel 12 or Laravel 13 (Laravel 11 is no longer supported, as it has reached end of life). Upgrade the application's `composer.json` accordingly before bumping Lunar: ```diff theme={null} - "php": "^8.2", + "php": "^8.3", - "laravel/framework": "^11.0", + "laravel/framework": "^12.0|^13.0", ``` #### Filament v4 The admin panel has been upgraded from Filament v3 to Filament v4. Projects that extend the panel with custom resources, pages, widgets, or actions will need to follow the official [Filament v4 upgrade guide](https://filamentphp.com/docs/4.x/upgrade-guide) and adapt any extension code to the new APIs. Update the constraint in `composer.json`: ```diff theme={null} - "filament/filament": "^3.0", + "filament/filament": "^4.1", ``` Common areas that require changes: * Form and table builders now use the dedicated `Filament\Schemas\Schema` and `Filament\Tables\Table` signatures. * Actions have moved to the `Filament\Actions` namespace (for example, `EditAction`, `DeleteBulkAction`, and `BulkActionGroup`). * Form components such as `Section`, `Group`, and `Get` now live under `Filament\Schemas\Components`. Run the Filament upgrade tooling to assist with the migration: ```sh theme={null} composer require filament/upgrade:^4.0 -W --dev vendor/bin/filament-v4 ``` After upgrading, run migrations to apply the staff table column rename described below: ```sh theme={null} php artisan migrate ``` #### Two-factor staff columns renamed Filament v4 ships its own multi-factor authentication primitives. As part of the upgrade, the columns on the `staff` table have been renamed and the redundant confirmation timestamp removed: * `two_factor_secret` is renamed to `app_authentication_secret`. * `two_factor_recovery_codes` is renamed to `app_authentication_recovery_codes`. * `two_factor_confirmed_at` is dropped. The rename is handled automatically by a Lunar migration. Update any application code that references the old column names directly. The previous `lunarphp/filament3-2fa` package is no longer required and can be removed from `composer.json`. #### Nested set package replaced Collections build their tree using a nested set implementation. Lunar 1.5 switches from `kalnoy/nestedset` to `lunarphp/nestedset`, a Lunar-maintained fork kept current for Laravel 12 and 13. Composer resolves the new package as a Lunar dependency, so no manual `require` is needed, but the namespaces have changed: ```diff theme={null} - use Kalnoy\Nestedset\NodeTrait; - use Kalnoy\Nestedset\QueryBuilder; - use Kalnoy\Nestedset\NestedSetServiceProvider; + use Lunar\Nestedset\NodeTrait; + use Lunar\Nestedset\QueryBuilder; + use Lunar\Nestedset\NestedSetServiceProvider; ``` Update any application code that imports these classes directly, type-hints against them, or extends `Lunar\Models\Collection` and re-declares a nested set method. The API itself is unchanged, so tree queries such as `whereIsRoot()`, `appendNode()`, and `withDepth()` continue to work as before. See [Collections → Nested Collections](/1.x/reference/collections#nested-collections). If the application requires `kalnoy/nestedset` for its own models, it can stay in `composer.json` alongside the fork. ### Medium Impact #### Order line purchasable morph is now nullable Shipping order lines previously stored a placeholder morph (`purchasable_type` set to `Lunar\DataTypes\ShippingOption`, `purchasable_id` set to `1`) purely to satisfy the non-nullable morph columns. `ShippingOption` is a data transfer object rather than an Eloquent model, so reading `$orderLine->purchasable` on a shipping line raised a fatal error, as did eager loading `lines.purchasable` across an order. In 1.5, `order_lines.purchasable_type` and `order_lines.purchasable_id` are nullable, and shipping lines are stored with no morph at all. A migration nulls the placeholder morph on existing shipping lines. The migration is scoped to that exact class, so custom morphs stored on shipping-type lines are left untouched. ```php theme={null} $order->shippingLines->first()->purchasable; // null (previously a fatal error) ``` Shipping lines are self-describing: `description`, `unit_price`, `total`, and `meta` are snapshotted onto the line, so display and totals are unaffected. Storefront code that iterates `$order->lines` and reaches for `$line->purchasable` should guard against `null`: ```php theme={null} foreach ($order->lines as $line) { if (! $line->purchasable) { continue; // Shipping line } // ... } ``` Alternatively, iterate `$order->productLines` to exclude shipping lines entirely. See [Orders → Order Lines](/1.x/reference/orders#order-lines). #### Discount conditions are now honored by BuyXGetY `Lunar\DiscountTypes\BuyXGetY` did not check the discount's conditions before awarding a reward. Minimum spend, customer restrictions, and `max_uses_per_user` were all ignored, and only the quantity condition (`min_qty`) gated the discount. These conditions are now enforced, matching `Lunar\DiscountTypes\AmountOff`. Existing BuyXGetY discounts that were configured with a minimum spend or a customer restriction will start applying it, so a discount that previously awarded a reward on every qualifying cart may now award it on fewer carts. Review live BuyXGetY discounts before upgrading to confirm their conditions reflect what the store intends to offer. #### Stripe amounts converted using currency decimal places `Lunar\Stripe\Managers\StripeManager::toStripeAmount()` previously passed the stored cart total straight through to Stripe for all but three currencies, assuming the currency's configured `decimal_places` matched the sub-unit Stripe expects. A currency configured with more decimal places than Stripe uses was overcharged, by a factor of 100 in the case of a four decimal place currency. Amounts are now converted back to the major unit using the currency's `decimal_places`, then re-scaled to the sub-unit Stripe expects for that currency code (zero decimal places for JPY, KRW, and similar, three for BHD, JOD, KWD, OMR, and TND, two otherwise). Stores using the Stripe add-on with a currency whose `decimal_places` is not `2` should verify the amounts sent to Stripe after upgrading. No action is needed for currencies configured with two decimal places. See [Stripe](/1.x/addons/payments/stripe). #### Weight tiers evaluated in the shipping method's weight unit The `ship-by` driver hardcoded kilograms when summing cart weight, ignoring the `weight_unit` column on the shipping method. Each cart line's weight is now converted from its own unit into the method's configured `weight_unit`, defaulting to `kg` when the column is empty. Methods that left `weight_unit` empty behave exactly as before. Methods that set a `weight_unit` other than `kg` will now match tiers in that unit, so their tier thresholds need to be re-entered in the configured unit. Weight tiers remain whole numbers; the admin panel now shows the configured unit alongside the field and rejects decimal values instead of silently truncating them. See [Table Rate Shipping → Ship By](/1.x/addons/table-rate-shipping#ship-by). #### Optimized default search indexer relationship select The default search indexers now eager-load only the columns each indexer uses in `toSearchableArray()`. Search output is unchanged, so no action is required when using the default indexers. Projects with custom indexers that extend Lunar's indexers should review their `makeAllSearchableUsing()` method to confirm the required columns are still selected. * Indexers updated: `CustomerIndexer`, `OrderIndexer`, `ProductIndexer`, `ProductOptionIndexer`. * Indexers unchanged: `BrandIndexer`, `CollectionIndexer`. #### Shipping method cutoff replaced by availability schedule The `cutoff` column on `shipping_methods` has been removed. Method availability is now controlled through a dedicated availability schedule, offering finer control over when each shipping method is offered. A migration drops the column and Lunar's migration state copies any existing cutoff value into a schedule entry. Update any application code that reads or writes `cutoff` directly on `Lunar\Shipping\Models\ShippingMethod`. See [Table Rate Shipping](/1.x/addons/table-rate-shipping) for the new model. ### Low Impact #### Min and max weight on shipping methods Shipping methods now support optional `min_weight`, `max_weight`, and `weight_unit` fields. A migration adds the columns as nullable, so existing methods continue to work without changes. #### `card_type` on transactions is now nullable The `card_type` column on the `transactions` table is now nullable and stored as `string` (no length constraint). Existing rows are unaffected. Custom code that assumed a non-null value should be updated. #### Per-currency base price for table rate shipping Table rate shipping rates can now hold a base price per currency, not just the default currency. No schema change is required; the admin panel exposes the additional inputs. #### New `ShippingDiscount` discount type The Table Rate Shipping add-on registers a new `ShippingDiscount` discount type, allowing discounts to target specific shipping methods (or all methods) with a fixed price per currency or a percentage off. See [Table Rate Shipping](/1.x/addons/table-rate-shipping) for usage. #### Date parameters widened to `DateTimeInterface` Applications that call `Date::use(CarbonImmutable::class)` receive a `CarbonImmutable` from `now()`, which is not a `DateTime` subclass. Any cart or discount calculation then failed with a `TypeError`, because these methods declared `DateTime` parameters. The parameter type hints are now `DateTimeInterface` across three traits: | Trait | Methods | | :- | :- | | `Lunar\Base\Traits\HasCustomerGroups` | `scheduleCustomerGroup()`, `applyCustomerGroupScope()`, `scopeCustomerGroup()` | | `Lunar\Base\Traits\HasChannels` | `scheduleChannel()`, `scopeChannel()` | | `Lunar\Base\Traits\CanScheduleAvailability` | `schedule()` | Widening a parameter type is backwards compatible, so all existing call sites continue to work. The one exception is a custom model that overrides one of these methods and re-declares the narrower `DateTime` type: PHP raises a fatal error when the class loads. Widen the override's signature to `DateTimeInterface` to match. #### `getDefault()` can return `null` `Lunar\Base\Traits\HasDefaultRecord::getDefault()` was annotated as returning a model, but it returns `null` when no record is flagged as the default. The annotation now reflects that. There is no runtime change, but static analysis will start reporting calls that assume a model is always returned, such as `Currency::getDefault()->code`. Guard these calls or seed a default record: ```php theme={null} if ($currency = \Lunar\Models\Currency::getDefault()) { // ... } ``` #### `DefaultPriceFormatter` formatter style type The `$formatterStyle` parameter on `Lunar\Pricing\DefaultPriceFormatter` is now typed `int` rather than `string`, matching the `NumberFormatter` constants (such as `NumberFormatter::CURRENCY`) that are passed to it. Custom price formatters that extend this class should update their signature to match. #### Deterministic relationship ordering Several relationships had no explicit ordering, so the row order was left to the database engine. MySQL happens to return primary key order; PostgreSQL returns heap order, which can change after an unrelated update. Because `Lunar\Actions\Carts\GenerateFingerprint` reduces cart lines in iteration order, an unstable order could change a cart's fingerprint. Explicit ordering has been added: | Relationship | Ordering | | :- | :- | | `Lunar\Models\Cart::lines()` | `id` | | `Lunar\Models\Order::lines()` | `id` | | `Lunar\Models\ProductVariant::values()` | `position`, then the pivot `id` | Ordering `Order::lines()` also stabilizes the derived `physicalLines`, `digitalLines`, `shippingLines`, and `productLines` relationships. Applications that relied on the previous incidental ordering may see a different (but now consistent) line order. #### Order addresses are no longer duplicated by type `Lunar\Pipelines\Order\Creation\CreateOrderAddresses` matched existing order addresses on both type and postcode, so a cart whose draft order was rebuilt with a changed address added a second row of the same type rather than updating the first. Because `$order->shippingAddress` returns the oldest match, the order then reported the stale address. Existing addresses are now matched on type alone, so each order holds at most one address per type and rebuilding the draft order updates it in place. No migration is included, so orders that already hold duplicate addresses keep them, and the extra rows can be cleaned up manually if needed. #### State tax zones are scoped to the address country A tax zone attached to a state matched any address whose state code or name matched, in any country. Because state codes collide across countries (`WA` is both Washington and Western Australia), the wrong zone could apply, and a wrong state match also suppressed the correct country zone. State lookups are now scoped to the address country, so a state zone applies only to addresses in that state's country. Stores that unintentionally relied on a cross-country match will see the lookup fall through to the country zone, then the default zone. See [Taxation → Zone resolution](/1.x/reference/taxation#zone-resolution). #### Cart repriced when the session currency changes `Lunar\Facades\CartSession::setCurrency()` updated the cart's `currency_id` but left the loaded relationships in place, so the next `calculate()` priced every line in the previous currency. The cart's loaded `currency` and `lines` relationships are now reset when the currency changes, so pricing resolves against the new currency's `Price` records. See [Carts → Setting the currency](/1.x/reference/carts#setting-the-currency). *** ## 1.4 Lunar 1.4 is the final minor version built on Filament v3. [Lunar 1.5](#15) upgrades the admin panel to Filament v4, so projects that need to remain on Filament v3 should stay on the 1.4 release line. ### Low Impact #### `shipping:manage` permission The Table Rate Shipping add-on now enforces a `shipping:manage` permission on its admin resources (Shipping Methods, Shipping Zones, and Shipping Exclusion Lists). A migration creates the permission automatically; staff who previously had unrestricted access need to be assigned the new permission (or a role that includes it) to continue managing shipping. See [Table Rate Shipping](/1.x/addons/table-rate-shipping) for details. *** ## 1.3 ### Low Impact The `stephenjude/filament-two-factor-authentication` package has been removed due to an issue with Fortify and no suitable release being tagged. Replace the package with the forked version provided by Lunar: ```diff theme={null} - "stephenjude/filament-two-factor-authentication": "^2.0", + "lunarphp/filament3-2fa": "^2.1.0", ``` *** ## 1.2 ### Low Impact #### Product association types ENUM Product association types have been moved to a dedicated ENUM. The model constants are now deprecated. The ENUM class can be swapped in config to allow for extending. #### Added meta fields to product options The `ProductOption` and `ProductOptionValue` models now include a `meta` field. If the application already defines custom `meta` fields on these models, a migration conflict may occur. *** ## 1.1 ### Medium Impact #### Renamed Order resource extension hook There was a typo in the extension hook. Rename `exendOrderSummaryInfolist` to `extendOrderSummaryInfolist` in any code that references it. *** ## 1.0.0 (stable release) This release introduces anonymous usage insights, sent via a deferred API call. The purpose of this addition is to provide insight into how Lunar is being used and at what capacity. No identifying information is sent or stored. This is completely optional; however, it is turned on by default. To opt out, add the following to a service provider: ```php theme={null} \Lunar\Facades\Telemetry::optOut(); ``` *** ## 1.0.0-beta.24 ### Medium Impact #### Customer `vat_no` field renamed The field on the `customers` table has been renamed to `tax_identifier`. This aligns with the new field of the same name on `addresses`, `cart_addresses`, and `order_addresses`. ### Low Impact #### Buy X Get Y discount conditions and rewards Buy X Get Y discounts can now use collections and variants as conditions, and variants as rewards. As part of this change, the `discount_purchasables` table has been renamed to `discountables` and has its own `Discountable` model. Any code referencing `discount_purchasables` directly, or the `purchasables` relation on the discount model, must be updated. *** ## 1.0.0-beta.22 ### High Impact > [!WARNING] > > This release removes Laravel 10 support. Projects must be upgraded to Laravel 11 or later before updating Lunar. [Laravel Shift](https://laravelshift.com/) can assist with this process. #### Lunar Panel discount interface The `LunarPanelDiscountInterface` now requires a `lunarPanelRelationManagers` method that returns an array of relation managers to show in the admin panel for the discount type. Update any custom discount types to include this method. *** ## 1.0.0-beta.21 ### High Impact #### Order reference generation changes The previous order reference generator used the format `YYYY-MM-{X}`, which had been in place since the early days of the project. This approach was not ideal for order references and could lead to anomalies when determining the next reference in the sequence. The new format uses the Order ID with leading zeros and an optional prefix: ``` // Old (assuming order #250 in April 2025) 2025-04-00250 // New (assuming order ID is 1965) 00001965 ``` The length of the reference and the prefix can be defined in the `lunar/orders.php` config file: ```php theme={null} 'reference_format' => [ /** * Optional prefix for the order reference */ 'prefix' => null, /** * STR_PAD_LEFT: 00001965 * STR_PAD_RIGHT: 19650000 * STR_PAD_BOTH: 00196500 */ 'padding_direction' => STR_PAD_LEFT, /** * 00001965 * AAAA1965 */ 'padding_character' => '0', /** * If the length specified below is smaller than the length * of the Order ID, then no padding will take place. */ 'length' => 8, ], ``` To keep using the previous reference generation logic, [copy the existing class](https://github.com/lunarphp/lunar/blob/1.0.0-beta20/packages/core/src/Base/OrderReferenceGenerator.php) into the application and update the `reference_generator` path in config. ### Medium Impact #### Two-factor authentication Staff members now have the ability to set up two-factor authentication (2FA). Currently this is opt-in; however, it can be enforced for all staff members: ```php theme={null} public function register() { \Lunar\Admin\Support\Facades\LunarPanel::enforceTwoFactorAuth()->register(); } ``` To disable 2FA entirely (the setup option will not appear): ```php theme={null} public function register() { \Lunar\Admin\Support\Facades\LunarPanel::disableTwoFactorAuth()->register(); } ``` *** ## 1.0.0-beta.1 ### High Impact #### Model extending > [!WARNING] > > Model extending has been completely rewritten and requires changes to any Laravel application that has previously extended Lunar models. Lunar models now implement a contract (interface) and support dependency injection across the storefront and the Lunar panel. Update how models are registered: ```php theme={null} // Old ModelManifest::register(collect([ Product::class => \App\Models\Product::class, // ... ])); // New ModelManifest::replace( \Lunar\Models\Contracts\Product::class, \App\Models\Product::class ); ``` > [!TIP] > > If custom models do not extend their Lunar counterpart, they must implement the relevant contract in `Lunar\Models\Contracts`. See the [model extending](/1.x/extending/models) section for all available functionality. #### Polymorphic relationships To better support model extending, all polymorphic relationships now use an alias instead of the fully qualified class name. This allows relationships to resolve to custom models when interacting with Eloquent. There is an additional config setting in `config/lunar/database.php` where polymorph mappings can be prefixed: ```php theme={null} 'morph_prefix' => null, ``` By default this is set to `null`, so the mapping for a product would just be `product`. A migration handles this change for Lunar tables and some third-party tables; however, additional migrations may be needed for other tables or custom models. #### Shipping methods availability Shipping methods are now associated with customer groups. When using the shipping add-on, ensure that all shipping methods are associated with the correct customer groups. #### Stripe add-on The Stripe add-on now attempts to update an order's billing and shipping address based on what is stored against the Payment Intent. This is due to Stripe not always returning this information during express checkout flows. To disable this behavior, set the `lunar.stripe.sync_addresses` config value to `false`. ##### PaymentIntent storage and reference to carts/orders Previously, PaymentIntent information was stored in the Cart model's meta and then transferred to the order when created. This approach caused limitations and meant that if the cart's meta was updated elsewhere (or the intent information was removed), it could result in unrecoverable data loss. PaymentIntent data has been moved from the `payment_intent` key in meta to a dedicated `StripePaymentIntent` model. This allows more flexibility in how payment intents are handled. A `StripePaymentIntent` is associated with both a cart and an order. The stored information is now: * `intent_id` — the PaymentIntent ID provided by Stripe * `status` — the PaymentIntent status * `event_id` — if the order was placed via the webhook, this contains the event ID * `processing_at` — populated when a request to place the order is made * `processed_at` — populated with the current timestamp once the order is placed ##### Preventing overlap Previously, the job to place the order was dispatched to the queue with a 20-second delay. Now the payment type checks whether the order is already being processed and, if so, takes no further action. This prevents overlaps regardless of how they are triggered. *** ## 1.0.0-alpha.34 ### Medium Impact #### Stripe add-on The Stripe driver now checks whether an order already has a `placed_at` value. If so, no further processing takes place. Additionally, the webhook logic has been moved to the job queue with a 20-second dispatch delay. This allows storefronts to manually process a payment intent alongside the webhook without worrying about overlap. The Stripe webhook environment variable has been renamed: ```diff theme={null} - STRIPE_WEBHOOK_PAYMENT_INTENT=... + LUNAR_STRIPE_WEBHOOK_SECRET=... ``` The Stripe config that Lunar looks for in `config/services.php` has changed: ```php theme={null} 'stripe' => [ 'key' => env('STRIPE_SECRET'), 'public_key' => env('STRIPE_PK'), 'webhooks' => [ 'lunar' => env('LUNAR_STRIPE_WEBHOOK_SECRET'), ], ], ``` *** ## 1.0.0-alpha.32 ### High Impact > [!WARNING] > > A new `LunarUser` interface must be implemented on the application's `User` model. ```php theme={null} // ... class User extends Authenticatable implements \Lunar\Base\LunarUser { use \Lunar\Base\Traits\LunarUser; } ``` *** ## 1.0.0-alpha.31 ### High Impact Certain parts of `config/cart.php` that are specific to session-based cart interaction have been relocated to a new `config/cart_session.php` file. ```php theme={null} // Move to config/cart_session.php 'session_key' => 'lunar_cart', 'auto_create' => false, ``` Check this file for any new config values that may need to be added. *** ## 1.0.0-alpha.29 ### High Impact #### Cart calculate function no longer recalculates The `$cart->calculate()` method previously ran calculations every time it was called, regardless of whether the cart had already been calculated. Now `calculate()` only runs if cart totals do not exist. To force a recalculation, use `$cart->recalculate()`. #### Unique index for collection group handle The `handle` column on collection groups now has a unique index. If collection groups are created through the admin panel, no changes are required. ### Medium Impact #### Update custom shipping modifiers signature The `\Lunar\Base\ShippingModifier` `handle` method now correctly passes a closure as the second parameter. Update any custom shipping modifiers that extend this class: ```php theme={null} public function handle(\Lunar\Models\Cart $cart, \Closure $next) { // ... return $next($cart); } ``` *** ## 1.0.0-alpha.26 ### Medium Impact If custom classes implement the `Purchasable` interface, add the following methods: ```php theme={null} public function canBeFulfilledAtQuantity(int $quantity): bool; public function getTotalInventory(): int; ``` If checking the `ProductVariant` `purchasable` attribute, update the following check: ```php theme={null} // Old $variant->purchasable == 'backorder'; // New $variant->purchasable == 'in_stock_or_on_backorder'; ``` *** ## 1.0.0-alpha.22 ### Medium Impact Carts now use soft deletes. A cart is deleted when `CartSession::forget()` is called. To forget the session without deleting the cart, pass `delete: false`: ```php theme={null} \Lunar\Facades\CartSession::forget(delete: false); ``` *** ## 1.0.0-alpha.20 ### High Impact #### Stripe add-on facade change The Stripe add-on facade has been renamed: ```php theme={null} // Old \Lunar\Stripe\Facades\StripeFacade; // New \Lunar\Stripe\Facades\Stripe; ``` *** ## 1.0.0-alpha.x > [!WARNING] > > When upgrading to `1.x` from `0.x`, ensure the application is upgraded to `0.8` first. ### High Impact #### Change to Staff model namespace The Staff model has moved from `Lunar\Hub\Models\Staff` to `Lunar\Admin\Models\Staff`. Update all references in the codebase and any polymorphic relations. #### Spatie Media Library This package has been upgraded to version 11, which introduces some breaking changes. See the [Spatie Media Library upgrade guide](https://github.com/spatie/laravel-medialibrary/blob/main/UPGRADING.md) for more information. #### Media conversions The `lunar.media.conversions` configuration has been removed in favor of registering custom media definitions instead. Media definition classes allow registration of media collections, conversions, and more. See [Media Collections](/1.x/reference/media.html#media-collections) for further information. #### Product options The `position` field has been removed from the `product_options` table and is now found on the `product_product_option` pivot table. Position data is automatically adjusted when running migrations. #### Tiers renamed to price breaks The `tier` column on pricing has been renamed to `min_quantity`. Any references in code to `tiers` must be updated. ##### Price model ```php theme={null} // Old $priceModel->tier // New $priceModel->min_quantity // Old $priceModel->tiers // New $priceModel->priceBreaks ``` ##### Lunar\Base\DataTransferObjects\PricingResponse ```php theme={null} // Old public Collection $tiered, // New public Collection $priceBreaks, ``` ##### Lunar\Base\DataTransferObjects\PaymentAuthorize Two new properties have been added to the constructor for this DTO: ```php theme={null} public ?int $orderId = null, public ?string $paymentType = null ``` # Installation Source: https://docs.lunarphp.com/1.x/getting-started/setup/installation Add Lunar to a Laravel application with Composer. Lunar integrates into an existing Laravel application as a Composer package. This guide walks through the full setup process. ## Requirements * PHP >= 8.3 (Lunar 1.5+) — PHP 8.2 is supported on Lunar 1.4 and earlier * Laravel 12, 13 (Lunar 1.5+) — Laravel 11 is supported on Lunar 1.4 and earlier * Filament 4 (Lunar 1.5+) — Filament 3 is supported on Lunar 1.4 and earlier * MySQL 8.0+ / PostgreSQL 9.4+ * `bcmath` PHP extension * `exif` PHP extension * `intl` PHP extension > [!NOTE] > > Lunar 1.5 builds the admin panel on Filament v4. Projects that need to stay on Filament v3 should install the 1.4 release line, which is the final Lunar version to support it: `composer require lunarphp/lunar:"^1.4"`. See the [upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) for the differences between the two. ## 1. Install the package ```sh theme={null} composer require lunarphp/lunar:"^1.0" -W ``` ## 2. Add the LunarUser trait Parts of the Lunar core rely on the `User` model having certain e-commerce relationships (carts, orders, customers). Add the bundled trait and interface to any model that represents users in the application. ```php theme={null} use Lunar\Base\Traits\LunarUser; use Lunar\Base\LunarUser as LunarUserInterface; // ... class User extends Authenticatable implements LunarUserInterface { use LunarUser; // ... } ``` ## 3. Register the admin panel Register the Lunar admin panel in the application's `AppServiceProvider`: ```php theme={null} use Lunar\Admin\Support\Facades\LunarPanel; class AppServiceProvider extends ServiceProvider { public function register(): void { LunarPanel::register(); } } ``` ## 4. Run the installer ```sh theme={null} php artisan lunar:install ``` The installer will guide through a series of prompts and perform the following: * Publish configuration files * Run database migrations * Create a default admin user * Seed initial data: a default channel, language, currency (USD), customer group, collection group, tax class, tax zone, and product/collection attributes * Publish Filament assets ## 5. Access the admin panel Once the installer completes, the admin panel is available at `https://| Product | Price | Quantity | Total | |
|---|---|---|---|---|
|
{{ $product->attr('name') }} @if($variant->getOptions()->isNotEmpty()){{ $variant->getOption() }} @endif{{ $variant->sku }} |
{{ $line->unitPrice->formatted() }} | {{ $line->subTotal->formatted() }} |
Discount: -{{ $cart->discountTotal->formatted() }}
@foreach($cart->discountBreakdown as $breakdown){{ $breakdown->discount->name }}: -{{ $breakdown->price->formatted() }}
@endforeach @endif ``` ## Cart Totals After calculation, the cart provides all the totals needed to build a summary. ```blade theme={null}{{ $tax->description }} ({{ $tax->percentage }}%): {{ $tax->price->formatted() }}
@endforeach ``` ## Estimated Shipping Shipping costs are typically calculated during checkout once a full address is provided. However, the cart page can show an estimated shipping cost based on a partial address. ```php theme={null} $cart->getEstimatedShipping([ 'postcode' => $request->postcode, 'country_id' => $request->country_id, ], setOverride: true); $cart->recalculate(); ``` Passing `setOverride: true` tells the cart to use the returned shipping option when calculating totals for that request. The `shippingTotal` on the cart will then reflect the estimate. When using `CartSession`, set the estimation parameters once and they persist for the session: ```php theme={null} CartSession::estimateShippingUsing([ 'postcode' => $request->postcode, 'country_id' => $request->country_id, ]); $cart = CartSession::current(estimateShipping: true); ``` ## Routes ```php theme={null} use App\Http\Controllers\CartController; Route::get('/cart', [CartController::class, 'show'])->name('cart.show'); Route::patch('/cart/line', [CartController::class, 'updateLine'])->name('cart.update-line'); Route::delete('/cart/line', [CartController::class, 'removeLine'])->name('cart.remove-line'); Route::post('/cart/coupon', [CartController::class, 'applyCoupon'])->name('cart.apply-coupon'); ``` ## Putting It All Together Here is a complete controller for the cart page: ```php theme={null} lines->isEmpty()) { return view('cart.empty'); } return view('cart.show', compact('cart')); } public function updateLine(Request $request) { $request->validate([ 'line_id' => 'required|integer', 'quantity' => 'required|integer|min:1', ]); $cart = CartSession::current(); try { $cart->updateLine( cartLineId: $request->line_id, quantity: $request->quantity, ); } catch (CartException $e) { return redirect()->route('cart.show') ->withErrors(['quantity' => $e->getMessage()]); } return redirect()->route('cart.show'); } public function removeLine(Request $request) { $request->validate([ 'line_id' => 'required|integer', ]); $cart = CartSession::current(); $cart->remove(cartLineId: $request->line_id); return redirect()->route('cart.show'); } public function applyCoupon(Request $request) { $request->validate([ 'coupon_code' => 'required|string', ]); $cart = CartSession::current(); $cart->update([ 'coupon_code' => $request->coupon_code, ]); $cart->recalculate(); if ($cart->discountTotal?->value === 0) { return redirect()->route('cart.show') ->withErrors(['coupon_code' => 'This coupon code is not valid.']); } return redirect()->route('cart.show') ->with('message', 'Coupon applied.'); } } ``` ## Next Steps * Review the [Carts reference](/1.x/reference/carts) for the full list of cart and cart line fields, configuration options, and session management. * Review the [Extending Carts](/1.x/extending/carts) for customizing the cart calculation pipeline, adding validators, and overriding actions. * Review the [Product Display Page guide](/1.x/guides/product-display-page) for adding items to the cart from a product page. # Catalog Menu Source: https://docs.lunarphp.com/1.x/guides/catalog-menu Build a catalog navigation menu with Lunar, covering collection groups, hierarchical collections, active state tracking, and caching. ## Overview A catalog menu is the primary navigation element that allows customers to browse the store by category. It is built from Lunar's collection hierarchy: collection groups organize top-level navigation sections, and collections within each group form nested trees of categories and subcategories. This guide walks through querying collection groups and their nested collections, rendering a multi-level navigation menu, highlighting the active collection, and caching the result for performance. The examples below use standard Laravel controllers and Blade templates. The same concepts apply whether the storefront is built with Livewire, Inertia, or a headless API. ## How Collections Are Organized Lunar organizes collections into a two-level structure: * **Collection Groups** act as top-level containers (e.g., "Main Menu", "Footer Links", "Seasonal Promotions"). Each group has a unique `handle` for identification. * **Collections** within a group form a nested tree using parent-child relationships. A root collection has no parent, and each root can have unlimited levels of children. **Main Menu (CollectionGroup)** **Clothing** **Men's** **T-Shirts** **Jackets** **Women's** **Dresses** **Tops** **Footwear** **Sneakers** **Boots** **Accessories** ## Querying the Menu Data ### Fetching a Collection Group Retrieve a collection group by its handle. The handle is set when creating the group in the admin panel or via code. ```php theme={null} use Lunar\Models\CollectionGroup; $menuGroup = CollectionGroup::where('handle', 'main-menu')->first(); ``` ### Fetching Root Collections Root collections are those with no parent. Use the nested set's `whereIsRoot()` scope to retrieve them. ```php theme={null} use Lunar\Models\Collection; $rootCollections = Collection::where('collection_group_id', $menuGroup->id) ->whereIsRoot() ->defaultOrder() ->with(['defaultUrl', 'media']) ->get(); ``` The `defaultOrder()` scope orders collections by their nested set position, which matches the order configured in the admin panel. ### Fetching Children Each collection's children can be loaded via the `children` relationship. To build a full menu tree, eager load the children (and their children) to avoid N+1 queries. ```php theme={null} $rootCollections = Collection::where('collection_group_id', $menuGroup->id) ->whereIsRoot() ->defaultOrder() ->with([ 'defaultUrl', 'children' => fn ($query) => $query->defaultOrder(), 'children.defaultUrl', 'children.children' => fn ($query) => $query->defaultOrder(), 'children.children.defaultUrl', ]) ->get(); ``` This loads three levels of the menu hierarchy. Add additional `children` levels as needed for deeper menus. > [!TIP] > > Eager loading children with constrained queries (using the closure syntax) ensures each level is ordered correctly by its nested set position. ### Using `descendantsOf` for the Full Tree For menus that need the entire tree regardless of depth, the nested set provides a `descendantsOf` method. However, for navigation menus it is generally better to eager load a fixed number of levels to keep queries predictable and avoid loading unnecessary data. ```php theme={null} // Load the entire subtree (all depths) for a collection group $allCollections = Collection::where('collection_group_id', $menuGroup->id) ->defaultOrder() ->with('defaultUrl') ->get() ->toTree(); ``` The `toTree()` method on the resulting collection restructures the flat list into a nested tree, with each node's `children` relation populated. ## Building a Menu Service Encapsulate the menu query in a dedicated service class to keep controllers clean and make caching straightforward. ```php theme={null} first(); if (! $group) { return collect(); } $query = Collection::where('collection_group_id', $group->id) ->whereIsRoot() ->defaultOrder() ->with($this->buildEagerLoads($depth)); return $query->get(); } protected function buildEagerLoads(int $depth): array { $eagerLoads = ['defaultUrl']; $prefix = ''; for ($i = 1; $i < $depth; $i++) { $prefix .= ($i === 1) ? 'children' : '.children'; $eagerLoads[$prefix] = fn ($query) => $query->defaultOrder(); $eagerLoads["{$prefix}.defaultUrl"] = fn ($query) => $query; } return $eagerLoads; } } ``` Register it in a service provider or resolve it directly: ```php theme={null} use App\Services\CatalogMenuService; $menu = app(CatalogMenuService::class)->getMenu('main-menu'); ``` ## Rendering the Menu ### Sharing Menu Data with All Views Use a view composer or middleware to make the menu available to every page without passing it from each controller. ```php theme={null} with( 'catalogMenu', app(CatalogMenuService::class)->getMenu() ); }); } } ``` > [!NOTE] > > When using a view composer with `'*'`, the menu query runs on every request. Pair this with caching (covered below) to avoid repeated database queries. ### Basic Menu Template ```blade theme={null} ``` ### Recursive Menu for Unlimited Depth For menus with an arbitrary number of levels, use a recursive Blade partial. Create a partial at `resources/views/partials/menu-item.blade.php`: ```blade theme={null}{{ $line->purchasable->product->attr('name') }}
Qty: {{ $line->quantity }}
{{ $line->total->formatted() }}
{{ $cart->shippingAddress->first_name }} {{ $cart->shippingAddress->last_name }}
{{ $cart->shippingAddress->line_one }}
{{ $cart->shippingAddress->city }}, {{ $cart->shippingAddress->postcode }}
@endif{{ $cart->billingAddress->first_name }} {{ $cart->billingAddress->last_name }}
{{ $cart->billingAddress->line_one }}
{{ $cart->billingAddress->city }}, {{ $cart->billingAddress->postcode }}
@endifThank you for your order!
Order Reference: {{ $order->reference }}
{{ $line->description }}
Qty: {{ $line->quantity }}
{{ $line->total->formatted() }}
{{ $line->description }}: {{ $line->total->formatted() }}
@endforeach @endifNo saved addresses.
@else @foreach($addresses as $address){{ $address->first_name }} {{ $address->last_name }} @if($address->shipping_default) Default Shipping @endif @if($address->billing_default) Default Billing @endif
@if($address->company_name){{ $address->company_name }}
@endif{{ $address->line_one }}
@if($address->line_two){{ $address->line_two }}
@endif{{ $address->city }}, {{ $address->state }} {{ $address->postcode }}
{{ $address->country?->name }}
{{ $customer->fullName }}
@if($customer->company_name){{ $customer->company_name }}
@endif{{ $order->reference }}
{{ $order->placed_at->format('M d, Y') }}
{{ $order->total->formatted() }}
@emptyNo orders yet.
@endforelse{{ $address->first_name }} {{ $address->last_name }}
{{ $address->line_one }}
{{ $address->city }}, {{ $address->postcode }}
{{ $address->country?->name }}
@if($address->shipping_default) Default Shipping @endif @if($address->billing_default) Default Billing @endifNo saved addresses.
@endforelse ``` ## Updating Customer Profile ```php theme={null} validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'company_name' => 'nullable|string|max:255', ]); $customer = StorefrontSession::getCustomer(); $customer->update([ 'first_name' => $request->first_name, 'last_name' => $request->last_name, 'company_name' => $request->company_name, ]); return redirect()->route('account.show') ->with('message', 'Profile updated.'); } } ``` ## Checking Authentication in Views Use the `StorefrontSession` to conditionally display content based on whether a customer is linked: ```blade theme={null} @php $customer = \Lunar\Facades\StorefrontSession::getCustomer(); @endphp @if($customer) Hi, {{ $customer->first_name }} @else Sign In Register @endif ``` ## Routes ```php theme={null} use App\Http\Controllers\AccountController; use App\Http\Controllers\Auth\RegisterController; // Registration Route::get('/register', [RegisterController::class, 'create'])->name('register'); Route::post('/register', [RegisterController::class, 'store']); // Account (requires authentication) Route::middleware('auth')->group(function () { Route::get('/account', [AccountController::class, 'show'])->name('account.show'); Route::patch('/account', [AccountController::class, 'update'])->name('account.update'); }); ``` ## Putting It All Together Here is a complete registration controller and account controller: ```php theme={null} validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'password' => 'required|string|min:8|confirmed', ]); $user = User::create([ 'name' => $request->first_name . ' ' . $request->last_name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); $customer = Customer::create([ 'first_name' => $request->first_name, 'last_name' => $request->last_name, ]); $customer->users()->attach($user); Auth::login($user); return redirect()->route('home'); } } ``` ```php theme={null} route('login'); } $customer->load([ 'addresses.country', 'orders' => fn ($query) => $query->whereNotNull('placed_at') ->latest('placed_at') ->limit(5), ]); return view('account.show', compact('customer')); } public function update(Request $request) { $request->validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'company_name' => 'nullable|string|max:255', ]); $customer = StorefrontSession::getCustomer(); $customer->update([ 'first_name' => $request->first_name, 'last_name' => $request->last_name, 'company_name' => $request->company_name, ]); return redirect()->route('account.show') ->with('message', 'Profile updated.'); } } ``` ## Next Steps * Review the [Customers reference](/1.x/reference/customers) for the full list of customer model fields, relationships, and scopes. * Review the [Storefront Session reference](/1.x/storefront-utils/storefront-session) for all session management methods. * Review the [Customer Addresses guide](/1.x/guides/customer-addresses) for managing saved addresses. * Review the [Order History guide](/1.x/guides/order-history) for displaying past orders. * Review the [Cart guide](/1.x/guides/cart) for details on how cart calculation and session management work. # Order History Source: https://docs.lunarphp.com/1.x/guides/order-history Build an order history page with Lunar, covering customer authentication, order listing, pagination, and order detail views. ## Overview The order history page allows authenticated customers to view their past orders, check order statuses, and review the details of individual orders. This guide walks through resolving the current customer, querying their orders, displaying a paginated order list, and building an order detail page. The examples below use standard Laravel controllers and Blade templates. The same concepts apply whether the storefront is built with Livewire, Inertia, or a headless API. ## Resolving the Current Customer Lunar separates the concept of a `Customer` from Laravel's `User` model. An authenticated user can be linked to one or more customers through the `LunarUser` trait. The `StorefrontSession` facade provides the current customer for the session. ```php theme={null} use Lunar\Facades\StorefrontSession; $customer = StorefrontSession::getCustomer(); ``` If no customer is associated with the current session, `getCustomer()` returns `null`. Protect account pages with middleware that checks for an authenticated user and a valid customer: ```php theme={null} use Lunar\Facades\StorefrontSession; class AccountController extends Controller { public function orders() { $customer = StorefrontSession::getCustomer(); if (! $customer) { abort(404); } // ... } } ``` > [!NOTE] > > The `StorefrontSession` automatically resolves the customer from the authenticated user when the `LunarUser` trait is applied to the `User` model. See the [Storefront Session reference](/1.x/storefront-utils/storefront-session) for details on how customer resolution works. ## Listing Orders Query the customer's orders using the `orders` relationship. Only orders with a `placed_at` value should be shown, as draft orders (where `placed_at` is `null`) have not been completed. ```php theme={null} use Lunar\Facades\StorefrontSession; class AccountController extends Controller { public function orders() { $customer = StorefrontSession::getCustomer(); if (! $customer) { abort(404); } $orders = $customer->orders() ->whereNotNull('placed_at') ->orderBy('placed_at', 'desc') ->paginate(10); return view('account.orders', compact('orders')); } } ``` ### Displaying the Order List Each order has its financial totals cast to `Lunar\DataTypes\Price` objects, so `formatted()` can be called directly. ```blade theme={null}No orders have been placed yet.
@else| Order | Date | Status | Total | |
|---|---|---|---|---|
| {{ $order->reference }} | {{ $order->placed_at->format('M d, Y') }} | {{ $order->status }} | {{ $order->total->formatted() }} | View |
Placed on {{ $order->placed_at->format('M d, Y \a\t g:i A') }}
Status: {{ $order->status }}
| Product | Price | Quantity | Total |
|---|---|---|---|
|
{{ $line->description }} @if($line->option){{ $line->option }} @endif{{ $line->identifier }} |
{{ $line->unit_price->formatted() }} | {{ $line->quantity }} | {{ $line->total->formatted() }} |
{{ $order->shippingAddress->first_name }} {{ $order->shippingAddress->last_name }}
@if($order->shippingAddress->company_name){{ $order->shippingAddress->company_name }}
@endif{{ $order->shippingAddress->line_one }}
@if($order->shippingAddress->line_two){{ $order->shippingAddress->line_two }}
@endif{{ $order->shippingAddress->city }}, {{ $order->shippingAddress->state }} {{ $order->shippingAddress->postcode }}
{{ $order->shippingAddress->country?->name }}
@endif{{ $order->billingAddress->first_name }} {{ $order->billingAddress->last_name }}
@if($order->billingAddress->company_name){{ $order->billingAddress->company_name }}
@endif{{ $order->billingAddress->line_one }}
@if($order->billingAddress->line_two){{ $order->billingAddress->line_two }}
@endif{{ $order->billingAddress->city }}, {{ $order->billingAddress->state }} {{ $order->billingAddress->postcode }}
{{ $order->billingAddress->country?->name }}
@endif{{ $tax->description }} ({{ $tax->percentage }}%): {{ $tax->price->formatted() }}
@endforeach ``` ## Eager Loading for Performance When displaying an order list, eager load the relationships needed for the list view to avoid N+1 queries: ```php theme={null} $orders = $customer->orders() ->whereNotNull('placed_at') ->orderBy('placed_at', 'desc') ->with('currency') ->paginate(10); ``` For the detail page, load everything needed in a single query: ```php theme={null} $order->load([ 'productLines.purchasable.product', 'shippingAddress.country', 'billingAddress.country', 'shippingLines', ]); ``` ## Routes ```php theme={null} use App\Http\Controllers\AccountController; Route::middleware('auth')->group(function () { Route::get('/account/orders', [AccountController::class, 'orders'])->name('account.orders'); Route::get('/account/orders/{order}', [AccountController::class, 'showOrder'])->name('account.orders.show'); }); ``` ## Putting It All Together Here is a complete controller for the order history pages: ```php theme={null} orders() ->whereNotNull('placed_at') ->orderBy('placed_at', 'desc') ->paginate(10); return view('account.orders', compact('orders')); } public function showOrder(Order $order) { $customer = StorefrontSession::getCustomer(); if (! $customer || $order->customer_id !== $customer->id) { abort(404); } if ($order->isDraft()) { abort(404); } $order->load([ 'productLines.purchasable.product', 'shippingAddress.country', 'billingAddress.country', 'shippingLines', ]); return view('account.orders.show', compact('order')); } } ``` ## Next Steps * Review the [Orders reference](/1.x/reference/orders) for the full list of order fields, relationships, and status configuration. * Review the [Customers reference](/1.x/reference/customers) for customer model details and the user-customer relationship. * Review the [Storefront Session reference](/1.x/storefront-utils/storefront-session) for how customer resolution works. * Review the [Customer Addresses guide](/1.x/guides/customer-addresses) for building an address management page. # Payment Integration Source: https://docs.lunarphp.com/1.x/guides/payment-integration Integrate payment processing with Lunar using Stripe, covering payment intents, frontend elements, webhooks, and the complete payment lifecycle. This guide walks through wiring a payment provider into Lunar end to end, using Stripe as the worked example. ## Overview Lunar uses a driver-based payment system through the `Payments` facade. This guide focuses on integrating Stripe as the payment provider, covering the complete flow from creating a payment intent to handling webhooks. The same high-level patterns apply to other payment drivers. The examples below use standard Laravel controllers and Blade templates. The same concepts apply whether the storefront is built with Livewire, Inertia, or a headless API. ## Payment Architecture Lunar's payment system has three layers: 1. **Payment Manager** (`Lunar\Facades\Payments`) — routes payment calls to the correct driver based on configuration 2. **Payment Type** (e.g., `Lunar\Stripe\StripePaymentType`) — handles authorization, capture, and refund logic for a specific provider 3. **Transactions** (`Lunar\Models\Transaction`) — records of every payment event stored against the order Payment types are configured in `config/lunar/payments.php`: ```php theme={null} return [ 'default' => env('PAYMENTS_TYPE', 'offline'), 'types' => [ 'cash-in-hand' => [ 'driver' => 'offline', 'authorized' => 'payment-offline', ], 'card' => [ 'driver' => 'stripe', 'released' => 'payment-received', ], ], ]; ``` Each type maps a name (used in `Payments::driver()`) to a driver class and the order statuses to assign on success. ## Setting Up Stripe ### Installation ```bash theme={null} composer require lunarphp/stripe ``` ### Configuration Publish the configuration file: ```bash theme={null} php artisan vendor:publish --tag=lunar.stripe.config ``` Set the Stripe keys in the application's `.env` file: ```bash theme={null} STRIPE_SECRET=sk_test_... STRIPE_PUBLIC=pk_test_... ``` ### Stripe Configuration Options The published config file (`config/lunar/stripe.php`) contains: ```php theme={null} return [ 'webhook_path' => 'stripe/webhook', 'policy' => 'automatic', 'sync_addresses' => true, 'status_mapping' => [ // Maps Stripe PaymentIntent statuses to Lunar order statuses ], ]; ``` | Option | Description | | :- | :- | | `webhook_path` | The URL path where Stripe sends webhook events | | `policy` | `automatic` captures payment immediately; `manual` authorizes first and captures later | | `sync_addresses` | When `true`, billing and shipping addresses from Stripe are synced to the order | | `status_mapping` | Maps Stripe `PaymentIntent` statuses to Lunar order statuses | ### Register the Payment Driver In a service provider (e.g., `AppServiceProvider`), register the Stripe driver: ```php theme={null} use Lunar\Facades\Payments; use Lunar\Stripe\StripePaymentType; public function boot(): void { Payments::extend('stripe', function ($app) { return $app->make(StripePaymentType::class); }); } ``` Update the payments configuration to use the Stripe driver: ```php theme={null} // config/lunar/payments.php return [ 'default' => 'card', 'types' => [ 'card' => [ 'driver' => 'stripe', 'released' => 'payment-received', ], ], ]; ``` ## Payment Flow The Stripe integration follows this lifecycle: 1. **Create a PaymentIntent** — when the customer reaches checkout, a Stripe PaymentIntent is created for the cart total 2. **Collect payment details** — the frontend renders Stripe's Payment Element to collect card details 3. **Confirm the payment** — Stripe.js confirms the payment on the client side and redirects back 4. **Authorize in Lunar** — the return handler calls `Payments::authorize()` to complete the order 5. **Webhook backup** — Stripe sends webhook events to handle edge cases (browser closed, network issues) ## Creating a Payment Intent Use the `Stripe` facade to create or fetch a PaymentIntent for the cart. The intent amount is automatically calculated from the cart total. ```php theme={null} use Lunar\Facades\CartSession; use Lunar\Stripe\Facades\Stripe; $cart = CartSession::current(); $intent = Stripe::fetchOrCreateIntent($cart); $clientSecret = $intent->client_secret; ``` `fetchOrCreateIntent()` checks whether an active intent already exists for the cart. If one exists, it syncs the amount and returns it. If none exists, it creates a new one. > [!NOTE] > > The PaymentIntent is linked to the cart through the `lunar_stripe_payment_intents` table. This table tracks the intent ID, cart ID, status, and processing state. ### Syncing the Intent If the cart total changes (for example, after applying a coupon or changing the shipping method), sync the intent to update the amount: ```php theme={null} Stripe::syncIntent($cart); ``` This updates the existing PaymentIntent on Stripe to match the current cart total. ## Frontend Integration Stripe's [Payment Element](https://stripe.com/docs/payments/payment-element) renders a prebuilt UI for collecting payment details. It supports cards, wallets, bank transfers, and other payment methods automatically. ### Including Stripe.js Add the Stripe.js script to the checkout layout: ```html theme={null} ``` ### Rendering the Payment Element ```blade theme={null}{{ ucfirst($transaction->type) }} — {{ $transaction->success ? 'Successful' : 'Failed' }}
{{ \Lunar\DataTypes\Price::from($transaction->amount, $order->currency)->formatted() }}
@if($transaction->card_type){{ ucfirst($transaction->card_type) }} ending {{ $transaction->last_four }}
@endif{{ $transaction->created_at->format('M d, Y H:i') }}
{{ $product->brand->name }}
@endif ``` ### Custom Attributes Any custom attributes defined on the product type are accessible in the same way. For example, if the product type includes a "Material" attribute: ```php theme={null} $product->attr('material'); // e.g. "Premium Leather" ``` ## Product Images Lunar uses [Spatie MediaLibrary](https://spatie.be/docs/laravel-medialibrary) for image management. Products store images in the `images` media collection. ```blade theme={null} {{-- Primary / thumbnail image --}}{{ $price->price->formatted() }}
@if($price->compare_price?->value)
{{ $price->compare_price->formatted() }}
{{ $price->priceIncTax()->formatted() }} inc. tax
{{ $price->priceExTax()->formatted() }} ex. tax
``` See the [Pricing reference](/1.x/reference/pricing) for more on configuring whether prices are stored inclusive or exclusive of tax. ### Price Breaks If the product offers quantity-based pricing, display the available tiers: ```blade theme={null} @if($pricing->priceBreaks->count() > 1)| Quantity | Price |
|---|---|
| {{ $break->min_quantity }}+ | {{ $break->price->formatted() }} |
{{ $related->attr('name') }}
@endforeach{{ $product->brand->name }}
@endif{{ $price->price->formatted() }}
@if($price->compare_price?->value){{ $price->compare_price->formatted() }}
{{ $results->count }} results for "{{ $results->query }}"
{{ $hit->document['brand'] }}
@endif @endforeachI'm a description!
" } ] } ``` ### Retrieving a Single Attribute Value The `translateAttribute` method returns the resolved value for a single attribute. For `TranslatedText` fields, it resolves the correct locale automatically. ```php theme={null} // Returns the value for the current app locale $product->translateAttribute('name'); // Returns the French translation $product->translateAttribute('name', 'fr'); // Falls back to the first available value $product->translateAttribute('name', 'FOO'); ``` The shorthand `attr` method does the same thing: ```php theme={null} $product->attr('name'); $product->attr('name', 'fr'); ``` For non-translatable fields, `translateAttribute` returns the raw value directly: ```php theme={null} // Returns the integer value $product->translateAttribute('pack_qty'); ``` ## Adding Attributes to a Custom Model To make a custom model support attributes: 1. Add the `HasAttributes` trait. 2. Cast the `attribute_data` column using `AsAttributeData`. 3. Add an `attribute_data` JSON column to the model's database table. ```php theme={null} use Lunar\Base\Casts\AsAttributeData; use Lunar\Base\Traits\HasAttributes; use Lunar\Base\Traits\HasTranslations; class MyModel extends Model { use HasAttributes; use HasTranslations; protected $casts = [ 'attribute_data' => AsAttributeData::class, ]; } ``` Then add the JSON column via a migration: ```php theme={null} Schema::table('my_models', function (Blueprint $table) { $table->json('attribute_data')->nullable(); }); ``` Finally, register the model as an attributable type so that attribute groups and attributes can be created for it: ```php theme={null} use Lunar\Facades\AttributeManifest; // In a service provider's boot method AttributeManifest::addType(\App\Models\MyModel::class); ``` ## Attribute Manifest The `AttributeManifest` manages which model types support attributes and provides access to searchable attribute data. ```php theme={null} use Lunar\Facades\AttributeManifest; // Get all registered attributable types $types = AttributeManifest::getTypes(); // Get a specific type by key (lowercase class basename) $type = AttributeManifest::getType('product'); // Register a new attributable type AttributeManifest::addType(\App\Models\MyModel::class); // Get all searchable attributes for a model type $searchable = AttributeManifest::getSearchableAttributes('product'); ``` # Carts Source: https://docs.lunarphp.com/1.x/reference/carts Manage shopping carts, calculate totals, and handle cart sessions in Lunar. Carts manage the collection of items a customer intends to purchase, with dynamic price calculation. ## Overview Carts hold a collection of purchasable items (typically product variants) that a customer intends to order. They belong to users (which relate to customers) and support a single currency each. > [!NOTE] > > Cart prices are dynamically calculated and are **not** stored in the database. Once a cart is converted to an order, the prices are persisted on the order instead. ## Cart Model ```php theme={null} Lunar\Models\Cart ``` | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | user\_id | `foreignId` `nullable` | For guest carts | | customer\_id | `foreignId` `nullable` | | | merged\_id | `foreignId` `nullable` | References the cart this was merged into | | currency\_id | `foreignId` | | | channel\_id | `foreignId` | | | tax\_zone\_id | `foreignId` `nullable` | Overrides the resolved tax zone when set. Added in 1.5 | | order\_id | `foreignId` `nullable` | References the order created from this cart | | coupon\_code | `string` `nullable` | Promotional coupon code | | completed\_at | `dateTime` `nullable` | | | meta | `json` `nullable` | | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | | deleted\_at | `timestamp` `nullable` | | ### Creating a Cart ```php theme={null} use Lunar\Models\Cart; $cart = Cart::create([ 'currency_id' => 1, 'channel_id' => 2, ]); ``` ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `lines` | Has many | `CartLine` | The line items in the cart. | | `addresses` | Has many | `CartAddress` | All addresses associated with the cart. | | `shippingAddress` | Has one | `CartAddress` | The shipping address (filtered by `type = shipping`). | | `billingAddress` | Has one | `CartAddress` | The billing address (filtered by `type = billing`). | | `currency` | Belongs to | `Currency` | The currency for the cart. | | `taxZone` | Belongs to | `TaxZone` | An explicit tax zone for this cart, when set. Added in 1.5 | | `user` | Belongs to | Auth user model | The authenticated user who owns the cart. | | `customer` | Belongs to | `Customer` | The customer associated with the cart. | | `orders` | Has many | `Order` | All orders created from the cart. | | `draftOrder` | Has one | `Order` | The unplaced (draft) order. | | `completedOrder` | Has one | `Order` | A single placed (completed) order. | | `completedOrders` | Has many | `Order` | All placed (completed) orders. | The `draftOrder` and `completedOrder` relationships accept an optional order ID parameter to filter to a specific order: ```php theme={null} $cart->draftOrder; $cart->completedOrder; // Filter to a specific order $cart->draftOrder($orderId)->first(); ``` ### Scopes | Scope | Description | | :- | :- | | `unmerged` | Filters to carts that have not been merged into another cart (`merged_id` is null). | | `active` | Filters to carts that have no orders, or only have unplaced (draft) orders. | ```php theme={null} use Lunar\Models\Cart; $unmergedCarts = Cart::unmerged()->get(); $activeCarts = Cart::active()->get(); ``` ### Setting the Tax Zone Added in 1.5 A cart can be assigned an explicit tax zone, which lets line totals be calculated tax-inclusive before a shipping address is captured. This is typically wired up in middleware that infers the customer's tax zone from their IP address. ```php theme={null} use Lunar\Models\Cart; use Lunar\Models\TaxZone; $cart->setTaxZone(TaxZone::find(1)); $cart->setTaxZone(null); // Clear the explicit tax zone. ``` `setTaxZone` triggers a recalculation by default. Pass `false` as the second argument to defer the recalculation. > [!NOTE] > > When `setShippingAddress` is called on a cart that already has an explicit tax zone, the zone is cleared so that address-based resolution can take over. Pass `clearTaxZone: false` to keep the explicit zone in place. ## Cart Lines Each item in a cart is represented by a `CartLine`. Lines link to a purchasable model (usually a `ProductVariant`) and track the desired quantity. ```php theme={null} Lunar\Models\CartLine ``` | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | cart\_id | `foreignId` | | | purchasable\_type | `string` | Morph type for the purchasable item | | purchasable\_id | `unsignedBigInteger` | Morph ID for the purchasable item | | quantity | `unsignedInteger` | | | meta | `json` `nullable` | | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `cart` | Belongs to | `Cart` | The cart this line belongs to. | | `purchasable` | Morph to | (polymorphic) | The purchasable item, typically a `ProductVariant`. | | `taxClass` | Has one through | `TaxClass` | The tax class, resolved through the purchasable item. | | `discounts` | Belongs to many | `Discount` | Discounts applied to this line. | ### Adding Lines Use the `add` method to add a purchasable item to the cart. If the item already exists in the cart, its quantity is updated instead. ```php theme={null} $cart->add($purchasable, quantity: 2, meta: [ 'personalization' => 'Happy Birthday!', ]); ``` Multiple lines can be added at once using `addLines`: ```php theme={null} use Lunar\Models\ProductVariant; $cart->addLines([ [ 'purchasable' => ProductVariant::find(1), 'quantity' => 2, 'meta' => ['foo' => 'bar'], ], [ 'purchasable' => ProductVariant::find(2), 'quantity' => 1, ], ]); ``` Lines can also be created directly via the relationship: ```php theme={null} $cart->lines()->create([ 'purchasable_type' => $purchasable->getMorphClass(), 'purchasable_id' => $purchasable->id, 'quantity' => 2, 'meta' => [ 'personalization' => 'Happy Birthday!', ], ]); ``` ### Updating Lines ```php theme={null} // Update a single line's quantity and meta $cart->updateLine($cartLineId, quantity: 3, meta: ['foo' => 'bar']); // Update multiple lines at once $cart->updateLines(collect([ ['id' => 1, 'quantity' => 5, 'meta' => ['foo' => 'bar']], ['id' => 2, 'quantity' => 3], ])); ``` ### Removing Lines ```php theme={null} // Remove a specific line $cart->remove($cartLineId); // Remove all lines $cart->clear(); ``` ### Line Validation When adding, updating, or removing items, a series of validation actions are run (defined in `config/lunar/cart.php`). These throw a `CartException` on failure. ```php theme={null} use Lunar\Exceptions\Carts\CartException; try { $cart->add($purchasable, quantity: 500); } catch (CartException $e) { $error = $e->getMessage(); } ``` ## Exceptions Lunar throws specific exceptions during cart operations to help identify what went wrong. All cart exceptions extend `Lunar\Exceptions\LunarException`. ### CartException ```php theme={null} Lunar\Exceptions\Carts\CartException ``` The primary exception for cart validation failures. It is thrown by the validation pipeline when adding, updating, or removing cart lines, or when creating an order. It wraps a `MessageBag` containing one or more error messages. ```php theme={null} use Lunar\Exceptions\Carts\CartException; try { $cart->add($purchasable, quantity: 500); } catch (CartException $e) { $e->getMessage(); // Summary of the first error $e->errors(); // Returns the full MessageBag } ``` When creating an order, the `ValidateCartForOrderCreation` validator may throw a `CartException` with one of the following messages: | Error Key | Cause | | :- | :- | | `carts.order_exists` | The cart already has a completed order. | | `carts.billing_missing` | No billing address has been set on the cart. | | `carts.billing_incomplete` | The billing address is missing required fields (`country_id`, `first_name`, `line_one`, `city`, `postcode`). | | `carts.shipping_missing` | The cart contains shippable items but has no shipping address. | | `carts.shipping_incomplete` | The shipping address is missing required fields. | | `carts.shipping_option_missing` | The cart contains shippable items but no shipping option has been selected. | ### InvalidCartLineQuantityException ```php theme={null} Lunar\Exceptions\InvalidCartLineQuantityException ``` Thrown when attempting to add a purchasable to the cart with a quantity of zero or less. ```php theme={null} use Lunar\Exceptions\InvalidCartLineQuantityException; try { $cart->add($purchasable, quantity: 0); } catch (InvalidCartLineQuantityException $e) { // Quantity must be at least 1 } ``` ### NonPurchasableItemException ```php theme={null} Lunar\Exceptions\NonPurchasableItemException ``` Thrown when creating or updating a cart line with a model that does not implement the `Lunar\Base\Purchasable` interface. This is checked automatically by the `CartLineObserver`. ### CartLineIdMismatchException ```php theme={null} Lunar\Exceptions\CartLineIdMismatchException ``` Thrown when attempting to remove a cart line that does not belong to the specified cart. ```php theme={null} use Lunar\Exceptions\CartLineIdMismatchException; try { $cart->remove($cartLineId); } catch (CartLineIdMismatchException $e) { // The cart line ID does not belong to this cart } ``` ### DisallowMultipleCartOrdersException ```php theme={null} Lunar\Exceptions\DisallowMultipleCartOrdersException ``` Thrown when calling `createOrder()` on a cart that already has a completed order, unless `allowMultipleOrders: true` is passed. ```php theme={null} use Lunar\Exceptions\DisallowMultipleCartOrdersException; try { $order = $cart->createOrder(); } catch (DisallowMultipleCartOrdersException $e) { // Cart already has a completed order } ``` ### FingerprintMismatchException ```php theme={null} Lunar\Exceptions\FingerprintMismatchException ``` Thrown when the fingerprint passed to `checkFingerprint()` does not match the cart's current fingerprint. See [Detecting Cart Changes](#detecting-cart-changes) for usage details. ## Calculating Totals Call `calculate()` to hydrate the cart with computed prices and tax breakdowns. ```php theme={null} $cart->calculate(); ``` > [!TIP] > > All monetary values return a `Lunar\DataTypes\Price` object, providing access to `value`, `formatted`, and `decimal` properties. To force recalculation (bypassing the cached result), use `recalculate`: ```php theme={null} $cart->recalculate(); ``` To check whether a cart has already been calculated: ```php theme={null} if ($cart->isCalculated()) { // Totals are available } ``` ### Cart-Level Properties | Property | Description | | :- | :- | | `total` | The total price for the cart (including tax). | | `subTotal` | The cart sub total, excluding tax. | | `subTotalDiscounted` | The cart sub total, minus the discount amount. | | `taxTotal` | The total tax applied. | | `discountTotal` | The total discount applied. | | `shippingSubTotal` | The shipping total, excluding tax. | | `shippingTaxTotal` | The tax amount applied to shipping. | | `shippingTotal` | The shipping total, including tax. | ### Line-Level Properties After calculation, each cart line is also hydrated with its own totals: | Property | Description | | :- | :- | | `unitPrice` | Price for a single item. | | `unitPriceInclTax` | Price for a single item, including tax. | | `total` | Total price for this line. | | `subTotal` | Sub total, excluding tax. | | `subTotalDiscounted` | Sub total, minus the discount amount. | | `taxAmount` | Tax applied to this line. | | `taxBreakdown` | Collection of all taxes applied to this line. | | `discountTotal` | Discount applied to this line. | | `promotionDescription` | Description of the promotion applied to this line. | ```php theme={null} foreach ($cart->lines as $cartLine) { $cartLine->unitPrice; $cartLine->subTotal; $cartLine->taxAmount; // ... } ``` ### Breakdowns The cart also provides detailed breakdowns for tax, discounts, and shipping: ```php theme={null} // Tax breakdown foreach ($cart->taxBreakdown->amounts as $taxRate) { $taxRate->description; $taxRate->price->value; } // Discount breakdown foreach ($cart->discountBreakdown as $discountBreakdown) { $discountBreakdown->discount->id; $discountBreakdown->price->value; foreach ($discountBreakdown->lines as $discountLine) { $discountLine->quantity; $discountLine->line; } } // Shipping breakdown foreach ($cart->shippingBreakdown->items as $shippingBreakdown) { $shippingBreakdown->name; $shippingBreakdown->identifier; $shippingBreakdown->price->formatted(); } ``` ### Extending Cart Calculations To programmatically change cart values (e.g. custom discounts or prices), see [Cart Extending](/1.x/extending/carts). ## Cart Addresses Each cart can have a shipping and billing address, represented by the `CartAddress` model. These addresses are used when calculating tax breakdowns and shipping costs. ```php theme={null} Lunar\Models\CartAddress ``` | Field | Type | Description | | :- | :- | :- | | id | `bigIncrements` | Primary key | | cart\_id | `foreignId` | | | country\_id | `foreignId` `nullable` | | | title | `string` `nullable` | | | first\_name | `string` `nullable` | | | last\_name | `string` `nullable` | | | company\_name | `string` `nullable` | | | tax\_identifier | `string` `nullable` | Tax ID or VAT number | | line\_one | `string` `nullable` | | | line\_two | `string` `nullable` | | | line\_three | `string` `nullable` | | | city | `string` `nullable` | | | state | `string` `nullable` | | | postcode | `string` `nullable` | | | delivery\_instructions | `string` `nullable` | | | contact\_email | `string` `nullable` | | | contact\_phone | `string` `nullable` | | | type | `string` | Either `shipping` or `billing`. Defaults to `shipping` | | shipping\_option | `string` `nullable` | The selected shipping option identifier | | meta | `json` `nullable` | | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `cart` | Belongs to | `Cart` | The cart this address belongs to. | | `country` | Belongs to | `Country` | The country for this address. | ### Cached Properties After the cart is calculated, shipping addresses are hydrated with shipping-related totals: | Property | Description | | :- | :- | | `shippingOption` | The resolved `ShippingOption` data type. | | `shippingSubTotal` | The shipping sub total, excluding tax. | | `shippingTaxTotal` | The tax amount applied to shipping. | | `shippingTotal` | The shipping total, including tax. | | `taxBreakdown` | Breakdown of all taxes applied to shipping. | ## Setting Addresses Shipping and billing addresses can be set on the cart, which are used when calculating tax breakdowns. ```php theme={null} $cart->setShippingAddress([ 'first_name' => null, 'last_name' => null, 'line_one' => null, 'line_two' => null, 'line_three' => null, 'city' => null, 'state' => null, 'postcode' => null, 'country_id' => null, ]); $cart->setBillingAddress([ 'first_name' => null, 'last_name' => null, 'line_one' => null, 'line_two' => null, 'line_three' => null, 'city' => null, 'state' => null, 'postcode' => null, 'country_id' => null, ]); ``` An `Address` model or a `CartAddress` model can also be passed: ```php theme={null} use Lunar\Models\Address; $shippingAddress = Address::first(); $cart->setShippingAddress($shippingAddress); // Use the same address for billing $cart->setBillingAddress($cart->shippingAddress); ``` Retrieve addresses via the properties: ```php theme={null} $cart->shippingAddress; $cart->billingAddress; ``` > [!NOTE] > > During a cart's early lifetime, address information may not yet be available. Some countries don't display tax until checkout. The address-based tax calculation is designed to handle this: the addresses can be set when they become available. ## Shipping Options A shipping option can be set on the cart after an address has been provided. The available options are determined by the shipping manifest. ```php theme={null} $cart->setShippingOption($shippingOption); ``` To retrieve the currently selected shipping option: ```php theme={null} $shippingOption = $cart->getShippingOption(); ``` To check whether the cart contains any shippable items: ```php theme={null} if ($cart->isShippable()) { // Cart has items that require shipping } ``` ## Shipping Estimates It may be useful to show an estimated shipping cost before a full address is provided. The `getEstimatedShipping` method returns the cheapest available shipping option based on partial address data. ```php theme={null} use Lunar\Models\Country; $shippingOption = $cart->getEstimatedShipping([ 'postcode' => '123456', 'state' => 'Essex', 'country' => Country::first(), ]); ``` By default, this estimate is **not** used in cart total calculations. To include it, pass `setOverride: true`: ```php theme={null} use Lunar\Models\Country; $shippingOption = $cart->getEstimatedShipping([ 'postcode' => '123456', 'state' => 'Essex', 'country' => Country::first(), ], setOverride: true); ``` > [!NOTE] > > When `setOverride` is enabled, the returned shipping option bypasses other shipping logic in the cart pipelines, but only for that single request. The override can also be set manually: ```php theme={null} use Lunar\DataTypes\ShippingOption; $cart->shippingOptionOverride = new ShippingOption(/* .. */); ``` ## Creating Orders Once a cart has been calculated and all required information (addresses, shipping, etc.) has been provided, an order can be created from the cart. ```php theme={null} $order = $cart->createOrder(); ``` By default, a cart can only have one order. To allow multiple orders from the same cart (e.g. for split shipments), pass `allowMultipleOrders`: ```php theme={null} $order = $cart->createOrder(allowMultipleOrders: true); ``` To update an existing order instead of creating a new one, pass the order ID: ```php theme={null} $order = $cart->createOrder(orderIdToUpdate: $existingOrderId); ``` ### Checking Order Readiness Before attempting to create an order, check whether the cart has sufficient information: ```php theme={null} if ($cart->canCreateOrder()) { $order = $cart->createOrder(); } ``` To check whether the cart already has completed (placed) orders: ```php theme={null} $cart->hasCompletedOrders(); // bool ``` To retrieve the current draft order (matching the cart's fingerprint and total): ```php theme={null} $draftOrder = $cart->currentDraftOrder(); ``` ### Discount Consumption Added in 1.5 Order creation records a use against each applied discount as soon as the draft order exists. A checkout that runs order creation more than once for the same cart, such as a retry after a declined card, would therefore find the cart's own coupon exhausted and re-price the same order without it. To prevent this, a cart tracks the discounts it has already consumed, read from its draft order's discount breakdown. A cart's own consumption is not counted against it, so one order consumes one use however many times order creation runs for it. ```php theme={null} $cart->consumedDiscountIds(); // Illuminate\Support\Collection of discount IDs ``` The result is memoized on the cart instance, because it is read once when the applicable discount set is rebuilt and once per discount while conditions are checked. Order creation is the only thing that changes the answer, and it clears the memo itself. Code that writes a discount breakdown outside of order creation should clear it manually: ```php theme={null} $cart->forgetConsumedDiscountIds(); ``` ### Stock Validation Stock levels can be validated before order creation. This checks each cart line against the available stock for its purchasable item. ```php theme={null} use Lunar\Exceptions\Carts\CartException; try { $cart->validateStock(); } catch (CartException $e) { // One or more items are out of stock } ``` ## Associating Users and Customers A user can be associated directly on the cart model. The `policy` parameter controls how the association behaves when the user already has an existing cart: `merge` combines the carts, while `override` replaces the existing one. ```php theme={null} $cart->associate($user, policy: 'merge'); ``` A customer can also be associated: ```php theme={null} $cart->setCustomer($customer); ``` ## Cart Session Manager > [!TIP] > > The cart session manager is useful when building a traditional Laravel storefront that uses sessions. The session manager provides a convenient API for managing carts tied to the current user's session. ### Configuration Cart configuration lives in `config/lunar/cart.php`: | Option | Description | Default | | :- | :- | :- | | `auth_policy` | How to handle merging when a user logs in (`merge` or `override`). | `merge` | | `eager_load` | Relationships to eager load by default when calculating cart totals. | See below | The default `eager_load` relationships are: ```php theme={null} 'eager_load' => [ 'currency', 'lines.purchasable.taxClass', 'lines.purchasable.values', 'lines.purchasable.product.thumbnail', 'lines.purchasable.prices.currency', 'lines.purchasable.prices.priceable', 'lines.purchasable.product', 'lines.cart.currency', ], ``` Additional session-specific config is in `config/lunar/cart_session.php`: | Option | Description | Default | | :- | :- | :- | | `session_key` | Key used when storing the cart ID in the session. | `lunar_cart` | | `auto_create` | Create a cart automatically if none exists for the session. | `false` | | `allow_multiple_orders_per_cart` | Whether carts can have multiple orders associated to them. | `false` | ### Getting the Session Instance Use the facade or inject the interface: ```php theme={null} use Lunar\Facades\CartSession; $cart = CartSession::current(); // Or via dependency injection use Lunar\Base\CartSessionInterface; public function __construct( protected CartSessionInterface $cartSession ) { // ... } ``` When `current()` is called, the behavior depends on the `auto_create` config. With `auto_create` set to `false` (default), `null` is returned if no cart exists, preventing unnecessary database records. ### Managing Lines ```php theme={null} use Lunar\Facades\CartSession; use Lunar\Models\ProductVariant; // Add a single line CartSession::add($purchasable, $quantity); // Add multiple lines (accepts a collection or array) CartSession::addLines([ [ 'purchasable' => ProductVariant::find(123), 'quantity' => 25, 'meta' => ['foo' => 'bar'], ], // ... ]); // Update a single line CartSession::updateLine($cartLineId, $quantity, $meta); // Update multiple lines CartSession::updateLines(collect([ [ 'id' => 1, 'quantity' => 25, 'meta' => ['foo' => 'bar'], ], // ... ])); // Remove a line CartSession::remove($cartLineId); // Remove all lines CartSession::clear(); ``` ### Setting the Currency A cart holds a single currency. Switching it updates the cart's `currency_id` and resets the loaded `currency` and `lines` relationships, so the next call to `calculate()` prices every line from the new currency's `Price` records: ```php theme={null} use Lunar\Facades\CartSession; use Lunar\Models\Currency; CartSession::setCurrency(Currency::where('code', 'USD')->first()); ``` > [!NOTE] > > Lunar stores a price per currency rather than converting between them. A line whose purchasable has no `Price` record for the new currency raises `Lunar\Exceptions\MissingCurrencyPriceException` when the cart is calculated. ### Using a Specific Cart ```php theme={null} use Lunar\Facades\CartSession; use Lunar\Models\Cart; $cart = Cart::first(); CartSession::use($cart); ``` ### Associating a User ```php theme={null} use Lunar\Facades\CartSession; // Associate a cart with a user and set it as the session cart // The third argument is the auth policy: 'merge' or 'override' CartSession::associate($cart, $user, 'merge'); ``` ### Associating a Customer A customer can be associated directly on the cart model: ```php theme={null} $cart->setCustomer($customer); ``` ### Forgetting the Cart Forgetting a cart removes it from the session and soft-deletes it from the database: ```php theme={null} use Lunar\Facades\CartSession; CartSession::forget(); ``` To remove it from the session without deleting: ```php theme={null} use Lunar\Facades\CartSession; CartSession::forget(delete: false); ``` ### Shipping Estimates When using the `CartSession` manager, shipping estimation parameters can be persisted so they do not need to be passed each time: ```php theme={null} use Lunar\Facades\CartSession; use Lunar\Models\Country; CartSession::estimateShippingUsing([ 'postcode' => '123456', 'state' => 'Essex', 'country' => Country::first(), ]); // Default behavior: no shipping estimate applied CartSession::current(); // Apply the shipping estimate set above CartSession::current(estimateShipping: true); ``` See [Shipping Estimates](#shipping-estimates) above for more on how the underlying estimation works. ## Handling User Login When a user logs in, Lunar automatically listens to authentication events and handles cart association. If the user had a guest cart, it will be merged with (or override) any existing cart on their account, depending on the `auth_policy` config. ## Detecting Cart Changes Carts are dynamic: items, quantities, and prices can change at any moment. To detect whether a cart has been modified (e.g. on a different browser tab during checkout), use the fingerprint system: ```php theme={null} use Lunar\Exceptions\FingerprintMismatchException; $fingerprint = $cart->fingerprint(); try { $cart->checkFingerprint('previously_stored_fingerprint'); } catch (FingerprintMismatchException $e) { // Cart has changed, refresh it } ``` The fingerprint generator class can be customized in `config/lunar/cart.php`: ```php theme={null} return [ // ... 'fingerprint_generator' => Lunar\Actions\Carts\GenerateFingerprint::class, ]; ``` ## Pruning Old Carts Over time, unused carts accumulate in the database. Lunar can automatically prune carts that have no associated order. Enable pruning in `config/lunar/cart.php`: ```php theme={null} return [ // ... 'prune_tables' => [ 'enabled' => false, // Set to true to enable 'pipelines' => [ Lunar\Pipelines\CartPrune\PruneAfter::class, Lunar\Pipelines\CartPrune\WithoutOrders::class, Lunar\Pipelines\CartPrune\WhereNotMerged::class, ], 'prune_interval' => 90, // days ], ]; ``` | Option | Description | Default | | :- | :- | :- | | `enabled` | Whether automatic pruning is active. | `false` | | `prune_interval` | Number of days to retain carts before pruning. | `90` | | `pipelines` | Pipeline classes that determine which carts are eligible for removal. | | ## Activity Logging The Cart model uses [Spatie Activity Log](https://spatie.be/docs/laravel-activitylog) to automatically record changes. All attribute changes are logged except for `updated_at`. ## Macros The Cart model supports macros, allowing custom methods to be added at runtime: ```php theme={null} use Lunar\Models\Cart; Cart::macro('myCustomMethod', function () { // ... }); $cart->myCustomMethod(); ``` # Channels Source: https://docs.lunarphp.com/1.x/reference/channels Channels control where products and other models are published across different storefronts. ## Overview Channels allow products and other models to be published to different storefronts or sales channels. Lunar installs a default `webstore` channel during setup. ```php theme={null} Lunar\Models\Channel ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `name` | `string` | The display name of the channel | | `handle` | `string` | URL-friendly identifier, automatically slugified on save | | `default` | `boolean` | Whether this is the default channel | | `url` | `string` `nullable` | An optional URL associated with the channel | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | | `deleted_at` | `timestamp` `nullable` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `products` | `MorphToMany` | `Lunar\Models\Product` | Products assigned to this channel | | `collections` | `MorphToMany` | `Lunar\Models\Collection` | Collections assigned to this channel | | `discounts` | `MorphToMany` | `Lunar\Models\Discount` | Discounts assigned to this channel | ### Scopes | Scope | Description | | :- | :- | | `default($default = true)` | Filter to the default channel | ## Assigning channels to models Models can be assigned to different channels and optionally scheduled for availability within a date range. To add this functionality to a model, use the `HasChannels` trait: ```php theme={null} scheduleChannel($channel, now()->addDays(14), now()->addDays(24)); // Enable the product on the channel immediately. $product->scheduleChannel($channel); // The method also accepts a collection of channels. $product->scheduleChannel(Channel::get()); ``` There is also a `channel` scope available to models using this trait: ```php theme={null} use Lunar\Models\Product; // Limit to a single channel Product::channel($channel)->get(); // Limit to multiple channels Product::channel([$channelA, $channelB])->get(); // Limit to a channel available the next day Product::channel($channelA, now()->addDay())->get(); // Limit to a channel within a date range Product::channel($channelA, now()->addDay(), now()->addDays(2))->get(); ``` # Collections Source: https://docs.lunarphp.com/1.x/reference/collections Group products into flexible, hierarchical collections with scheduling, channel availability, and sorting. Collections group products together for storefront categories, promotions, and other purposes. ## Overview Collections provide a flexible way to group products together for any purpose: storefront categories, hero sliders, landing page features, seasonal promotions, or any other grouping a store requires. Products can be added to a collection explicitly or filtered by criteria, and collections can be nested to form a hierarchy. Each collection belongs to a collection group, allowing different sets of collections to be maintained independently for different parts of a storefront. ## Collection Groups Collection groups act as top-level containers for collections. A store might have separate groups for a main catalog, seasonal promotions, or landing page features. ```php theme={null} Lunar\Models\CollectionGroup ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `name` | `string` | The group name | | `handle` | `string` | Unique slug identifier | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `collections` | HasMany | `Lunar\Models\Collection` | All collections in this group | ### Creating a collection group ```php theme={null} use Lunar\Models\CollectionGroup; $group = CollectionGroup::create([ 'name' => 'Main Catalogue', 'handle' => 'main-catalogue', ]); ``` ## Collections ```php theme={null} Lunar\Models\Collection ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `collection_group_id` | `foreignId` | The parent collection group | | `_lft` | `unsignedInteger` | Read-only nested set left pointer | | `_rgt` | `unsignedInteger` | Read-only nested set right pointer | | `parent_id` | `unsignedInteger` `nullable` | Parent collection for tree hierarchy | | `type` | `string` | Default: `static` | | `attribute_data` | `json` | Translatable attributes (e.g. name, description) | | `sort` | `string` | Product sort method, default: `custom` | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | | `deleted_at` | `timestamp` `nullable` | Soft deletes | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `group` | BelongsTo | `Lunar\Models\CollectionGroup` | The parent collection group | | `products` | BelongsToMany | `Lunar\Models\Product` | Products in this collection; pivot: `position` | | `customerGroups` | BelongsToMany | `Lunar\Models\CustomerGroup` | Pivot: `visible`, `enabled`, `starts_at`, `ends_at` | | `channels` | MorphToMany | `Lunar\Models\Channel` | Pivot: `enabled`, `starts_at`, `ends_at` | | `discounts` | BelongsToMany | `Lunar\Models\Discount` | Pivot: `type` (`limitation` or `assignment`) | | `brands` | BelongsToMany | `Lunar\Models\Brand` | | | `urls` | MorphMany | `Lunar\Models\Url` | | | `children` | HasMany | `Lunar\Models\Collection` | Direct child collections (from NodeTrait) | | `ancestors` | AncestorsRelation | `Lunar\Models\Collection` | All parent collections up the tree (from NodeTrait) | | `descendants` | DescendantsRelation | `Lunar\Models\Collection` | All children recursively (from NodeTrait) | ### Scopes | Scope | Description | | :- | :- | | `inGroup(int $id)` | Filter by collection group ID | | `channel($channel, $startsAt, $endsAt)` | Filter by channel availability with optional scheduling | | `customerGroup($group, $startsAt, $endsAt)` | Filter by customer group availability with optional scheduling | ### Creating a collection ```php theme={null} use Lunar\Models\Collection; use Lunar\FieldTypes\Text; $collection = Collection::create([ 'collection_group_id' => $group->id, 'attribute_data' => [ 'name' => new Text('Clearance'), ], ]); ``` > [!WARNING] > > Lunar internally expects a `name` attribute on collection attribute data. It must be present in the attributes, otherwise the admin panel may throw unexpected errors. ### Nested Collections Collections form a tree hierarchy using the [lunarphp/nestedset](https://github.com/lunarphp/nestedset) package, a Lunar-maintained fork of `kalnoy/nestedset`. Child collections can be added using the `appendNode` method: ```php theme={null} use Lunar\Models\Collection; $parent = Collection::create([ 'collection_group_id' => $group->id, 'attribute_data' => [ 'name' => new \Lunar\FieldTypes\Text('Clothing'), ], ]); $child = Collection::create([ 'collection_group_id' => $group->id, 'attribute_data' => [ 'name' => new \Lunar\FieldTypes\Text('T-Shirts'), ], ]); $parent->appendNode($child); ``` This produces the following hierarchy: ``` - Clothing - T-Shirts ``` > [!NOTE] > > At least one root (parent) collection must exist before child collections can be created. This is important when using seeders to set up the initial catalog state. #### Breadcrumbs The `breadcrumb` accessor returns the translated names of all ancestor collections, which is useful for building breadcrumb navigation: ```php theme={null} $collection->breadcrumb; // Illuminate\Support\Collection of ancestor names ``` #### Querying the tree The nested set package provides many methods for working with the tree. Here are some common examples: ```php theme={null} // Get all root collections Collection::whereIsRoot()->get(); // Get direct children $collection->children; // Get all descendants (recursive) $collection->descendants; // Get ancestors $collection->ancestors; // Get siblings $collection->getSiblings(); // Get depth in tree (requires withDepth() scope) Collection::withDepth()->find($collection->id)->depth; ``` Refer to the [lunarphp/nestedset documentation](https://github.com/lunarphp/nestedset) for the full API. > [!NOTE] > > Lunar 1.5 replaced `kalnoy/nestedset` with `lunarphp/nestedset`. The API is unchanged, but the trait and query builder namespaces moved from `Kalnoy\Nestedset` to `Lunar\Nestedset`. See the [1.5 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#nested-set-package-replaced). ## Products Products are associated using a `BelongsToMany` relationship with a `position` pivot column for ordering. ### Adding products ```php theme={null} $collection->products()->sync([ $productA->id => ['position' => 1], $productB->id => ['position' => 2], ]); ``` ### Sorting products The `sort` field on a collection determines how products are ordered. Lunar ships with the following sort options: | Sort | Description | | :- | :- | | `min_price:asc` | Sort by base price ascending | | `min_price:desc` | Sort by base price descending | | `sku:asc` | Sort by SKU ascending | | `sku:desc` | Sort by SKU descending | | `custom` | Manually specify the order of each product via the `position` pivot | When a collection is updated, Lunar automatically dispatches the `UpdateProductPositions` job to reorder products based on the current sort setting. ## Channels Collections use the `HasChannels` trait, enabling channel-based availability with optional scheduling. See [Channels](/1.x/reference/channels) for full details. ```php theme={null} use Lunar\Models\Channel; $channel = Channel::first(); // Enable for a channel immediately $collection->scheduleChannel($channel); // Schedule availability with a start and end date $collection->scheduleChannel($channel, now()->addDays(7), now()->addDays(30)); ``` ### Querying by channel ```php theme={null} use Lunar\Models\Collection; Collection::channel($channel)->get(); Collection::channel($channel, now()->addDay(), now()->addDays(7))->get(); ``` ## Customer Groups Collections use the `HasCustomerGroups` trait, enabling customer group visibility with optional scheduling. See [Customers](/1.x/reference/customers) for full details. ```php theme={null} use Lunar\Models\CustomerGroup; $group = CustomerGroup::first(); // Enable for a customer group immediately $collection->scheduleCustomerGroup($group); // Schedule with a date range $collection->scheduleCustomerGroup($group, starts: now()->addDays(7), ends: now()->addDays(30)); // Disable for a customer group $collection->unscheduleCustomerGroup($group); ``` ### Querying by customer group ```php theme={null} use Lunar\Models\Collection; Collection::customerGroup($group)->get(); Collection::customerGroup([$groupA, $groupB])->get(); ``` ## URLs Collections use the `HasUrls` trait, which automatically generates URLs when a collection is created. ```php theme={null} // Get the default URL $collection->defaultUrl; // Get all URLs $collection->urls; ``` See [URLs](/1.x/reference/urls) for full details on managing URLs. ## Media Collections use the `HasMedia` trait (via Spatie Media Library), allowing images and other media to be attached. ```php theme={null} $collection->addMedia($pathToFile)->toMediaCollection('images'); // Get the thumbnail URL $collection->getThumbnailImage(); ``` ## Deletion Behavior Collections use soft deletes. When a collection is deleted, all related pivot data is automatically detached: * Products * Channels * URLs (hard deleted) * Customer groups * Discounts # Countries & States Source: https://docs.lunarphp.com/1.x/reference/countries-states Lunar ships with a full dataset of countries and states used for addresses, shipping, and tax calculations. ## Overview Lunar ships with a full dataset of countries and states that can be imported into your database. These are used across the system for [Addresses](/1.x/reference/addresses), shipping zone configuration, tax calculations, and more. ## Countries ```php theme={null} Lunar\Models\Country ``` | Field | Description | | :- | :- | | `id` | | | `name` | Full country name e.g. United States | | `iso3` | ISO 3166-1 alpha-3 code e.g. USA | | `iso2` | ISO 3166-1 alpha-2 code e.g. US | | `phonecode` | International dialling code e.g. 1 | | `capital` | Capital city | | `currency` | Currency code e.g. USD | | `native` | Native name of the country | | `emoji` | Country flag emoji | | `emoji_u` | Country flag unicode | | `created_at` | | | `updated_at` | | ### Retrieving countries ```php theme={null} use Lunar\Models\Country; // Find a country by ISO code $country = Country::where('iso2', 'US')->first(); // Get all countries $countries = Country::all(); // Get a country with its states $country = Country::with('states')->where('iso2', 'GB')->first(); ``` ### Relationships | Relationship | Type | | :- | :- | | `states` | `HasMany` | ## States States (also known as provinces or regions) belong to a country. They are useful for tax calculations and shipping zone configuration. ```php theme={null} Lunar\Models\State ``` | Field | Description | | :- | :- | | `id` | | | `country_id` | The related country | | `name` | Full state name e.g. California | | `code` | State code e.g. CA | | `created_at` | | | `updated_at` | | ### Retrieving states ```php theme={null} use Lunar\Models\State; // Get all states for a country $states = $country->states; // Find a state by code within a country $state = State::where('country_id', $country->id) ->where('code', 'CA') ->first(); ``` ### Relationships | Relationship | Type | | :- | :- | | `country` | `BelongsTo` | ## Importing Data Country and state data is provided by the [countries-states-cities-database](https://github.com/dr5hn/countries-states-cities-database). Use the following Artisan command to import the data into your database. ```sh theme={null} php artisan lunar:import:address-data ``` > [!NOTE] > > This command should be run after installing Lunar and after any updates that may include new country or state data. # Currencies Source: https://docs.lunarphp.com/1.x/reference/currencies Currencies define the monetary units available for pricing, with exchange rates for conversion. ## Overview Currencies allow pricing to be managed in different monetary units. Each currency has an exchange rate relative to the default currency, enabling price conversion. ```php theme={null} Lunar\Models\Currency ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `code` | `string` | The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code | | `name` | `string` | A descriptive name for the currency | | `exchange_rate` | `decimal(10,4)` | The exchange rate relative to the default currency | | `decimal_places` | `integer` | The number of decimal places, e.g. `2` | | `enabled` | `boolean` | Whether the currency is enabled | | `default` | `boolean` | Whether the currency is the default | | `sync_prices` | `boolean` | Whether to synchronize prices for this currency | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `prices` | `HasMany` | `Lunar\Models\Price` | Prices in this currency | ### Scopes | Scope | Description | | :- | :- | | `enabled($enabled = true)` | Filter to enabled/disabled currencies | | `default($default = true)` | Filter to the default currency | ## Creating a currency ```php theme={null} use Lunar\Models\Currency; Currency::create([ 'code' => 'GBP', 'name' => 'British Pound', 'exchange_rate' => 1.0000, 'decimal_places' => 2, 'enabled' => true, 'default' => true, ]); ``` ## Exchange rates Exchange rates are relative to the default currency. For example, given the following default currency: ```php theme={null} use Lunar\Models\Currency; Currency::create([ 'code' => 'GBP', 'name' => 'British Pound', 'exchange_rate' => 1.0000, 'decimal_places' => 2, 'enabled' => true, 'default' => true, ]); ``` The default currency's exchange rate is set to `1` as the base. To add EUR (Euros) when the exchange rate from GBP to EUR is `1.17`, the value should be relative to the default: 1 / 1.17 = 0.8547. The exchange rate is independent of product pricing, as prices can be specified per currency directly. The exchange rate serves as a helper when working with prices. # Customers Source: https://docs.lunarphp.com/1.x/reference/customers Customers represent the buyers in a store, kept separate from the application's User model. ## Overview Lunar uses a dedicated Customer model to store customer details, rather than the User model. This keeps the application's User models untouched and provides greater flexibility. ## Customers ```php theme={null} Lunar\Models\Customer ``` | Field | Type | Description | | :- | :- | :- | | `id` | | primary key | | `title` | `string` `nullable` | Salutation e.g. Mr, Mrs, Miss | | `first_name` | `string` | | | `last_name` | `string` | | | `company_name` | `string` `nullable` | | | `tax_identifier` | `string` `nullable` | | | `account_ref` | `string` `nullable` | | | `attribute_data` | `json` `nullable` | | | `meta` | `json` `nullable` | | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Creating a customer ```php theme={null} Lunar\Models\Customer::create([ 'title' => 'Mr.', 'first_name' => 'Tony', 'last_name' => 'Stark', 'company_name' => 'Stark Enterprises', 'tax_identifier' => 'GB123456789', 'meta' => [ 'account_no' => 'TNYSTRK1234' ], ]); ``` ### Accessors The Customer model provides a `full_name` accessor that combines the `title`, `first_name`, and `last_name` fields. ```php theme={null} $customer = Lunar\Models\Customer::create([ 'title' => 'Mr.', 'first_name' => 'Tony', 'last_name' => 'Stark', ]); $customer->full_name; // "Mr. Tony Stark" ``` ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `customerGroups` | `BelongsToMany` | `Lunar\Models\CustomerGroup` | Pivot: `customer_customer_group` | | `users` | `BelongsToMany` | Configured via `auth.providers.users.model` | Pivot: `customer_user` | | `discounts` | `BelongsToMany` | `Lunar\Models\Discount` | Pivot: `customer_discount` | | `addresses` | `HasMany` | `Lunar\Models\Address` | | | `orders` | `HasMany` | `Lunar\Models\Order` | | | `mappedAttributes` | `MorphToMany` | `Lunar\Models\Attribute` | | ## Users Customers are typically associated with a user so that they can place orders. It is also possible to have multiple users associated with a single customer. This is useful in B2B e-commerce where a customer may have multiple buyers. ### Attaching users to a customer ```php theme={null} $customer = \Lunar\Models\Customer::create([/* ... */]); $customer->users()->attach($user); $customer->users()->sync([$userA->id, $userB->id, $userC->id]); ``` ## Attaching a customer to a customer group ```php theme={null} $customer = \Lunar\Models\Customer::create([/* ... */]); $customer->customerGroups()->attach($customerGroup); $customer->customerGroups()->sync([$groupA->id, $groupB->id]); ``` ## Customer Groups Default `retail` Customer groups allow customers to be organized into logical segments, enabling different criteria to be defined on models based on which group a customer belongs to. These criteria include: ### Pricing Different pricing can be specified per customer group. For example, customers in the `trade` customer group may have different prices than those in `retail`. ### Product Availability Product visibility can be toggled depending on the customer group, meaning only certain products will show depending on the group a customer belongs to. Scheduling availability is also supported, allowing products to be released earlier or later to different groups. *** At least one customer group must exist in the store. When Lunar is installed, a default group named `retail` is created. ## Creating a customer group ```php theme={null} $customerGroup = Lunar\Models\CustomerGroup::create([ 'name' => 'Retail', 'handle' => 'retail', // Must be unique 'default' => false, ]); ``` > [!TIP] > > Only one default customer group can exist at a time. If a new customer group is created with `default` set to `true`, the existing default will be set to `false`. ## Scheduling availability To add customer group availability to custom models, the `HasCustomerGroups` trait can be used. ```php theme={null} // ... use Lunar\Base\Traits\HasCustomerGroups; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class MyModel extends Model { use HasCustomerGroups; public function customerGroups(): BelongsToMany { $prefix = config('lunar.database.table_prefix'); return $this->belongsToMany( \Lunar\Models\CustomerGroup::class, "{$prefix}customer_group_my_model" )->withTimestamps()->withPivot(['enabled', 'visible', 'starts_at', 'ends_at']); } } ``` This provides access to the following methods: ### Scheduling customer groups ```php theme={null} // Schedule with a specific start and end date. $myModel->scheduleCustomerGroup( $customerGroup, starts: now()->addDays(14), ends: now()->addDays(28), ); // Schedule the model to be enabled immediately (starts_at defaults to null). $myModel->scheduleCustomerGroup($customerGroup); // The schedule method will accept an array or collection of customer groups. $myModel->scheduleCustomerGroup(CustomerGroup::get()); ``` ### Unscheduling customer groups To disable a model for a customer group, it can be unscheduled. This sets `enabled` to `false` and clears the `starts_at` and `ends_at` dates. ```php theme={null} $myModel->unscheduleCustomerGroup($customerGroup); // Additional pivot data can also be passed. $myModel->unscheduleCustomerGroup($customerGroup, pivotData: ['visible' => false]); ``` ### Parameters | Field | Description | Type | | :- | :- | :- | | `$models` | A CustomerGroup model, array, or collection of CustomerGroup models. | mixed | | `$starts` | The date the customer group will be active from. | `DateTime\|null` | | `$ends` | The date the customer group will be active until. | `DateTime\|null` | | `$pivotData` | Any additional pivot data on the link table. | `array` | **Pivot Data** By default the following values are used for `$pivotData`: * `enabled` - Whether the customer group is enabled. Defaults to `true` when scheduling and `false` when unscheduling. * `starts_at` - When scheduling, set to the `$starts` value. When unscheduling, set to `null`. * `ends_at` - When scheduling, set to the `$ends` value. When unscheduling, set to `null`. Any of these values can be overridden, as they are merged internally. ### Querying by customer group The `HasCustomerGroups` trait adds a `customerGroup` scope to the model. This allows querying based on availability for one or more customer groups. The scope accepts a `CustomerGroup` model instance, an array, or a collection. ```php theme={null} $results = MyModel::customerGroup($customerGroup)->paginate(); $results = MyModel::customerGroup([ $groupA, $groupB, ])->paginate(50); ``` The `$startsAt` and `$endsAt` parameters can optionally be passed to filter by scheduling window. Both should be `DateTime` instances. * If neither is provided, both default to `now()` (with `$endsAt` set one second ahead). * The scope returns models where `starts_at` is `null` or before the given start, `ends_at` is `null` or after the given end, and either `enabled` or `visible` is `true`. ```php theme={null} // Filter by a specific date window. $results = MyModel::customerGroup($customerGroup, now()->addDay(), now()->addDays(7))->get(); ``` > [!TIP] > > A model will only be returned if the `enabled` or `visible` column is `true` on the pivot, regardless of whether the start and end dates match. ### Limit by customer group Eloquent models that use the `HasCustomerGroups` trait have a useful scope available: ```php theme={null} // Limit products available to a single customer group Product::customerGroup($customerGroup)->get(); // Limit products available to multiple customer groups Product::customerGroup([$groupA, $groupB])->get(); // Limit to products that are available the next day Product::customerGroup($groupA, now()->addDay())->get(); // Limit to products that are available within a date range. Product::customerGroup($groupA, now()->addDay(), now()->addDays(2))->get(); ``` # Discounts Source: https://docs.lunarphp.com/1.x/reference/discounts Flexible discount system supporting coupons, percentage/fixed reductions, and buy-x-get-y promotions. Lunar provides a flexible discount system supporting coupons, percentage and fixed reductions, and buy-x-get-y promotions. ## Overview Lunar provides a discount system that supports multiple discount types out of the box, including amount-off (percentage or fixed) and buy-x-get-y promotions. Discounts can be scoped to specific channels, customer groups, collections, brands, and individual products or variants. ```php theme={null} Lunar\Models\Discount ``` | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `name` | `string` | | | `handle` | `string` | Unique identifier | | `coupon` | `string` `nullable` | Coupon code customers can enter to apply the discount | | `type` | `string` | Fully qualified class name of the discount type | | `starts_at` | `dateTime` | When the discount becomes active | | `ends_at` | `dateTime` `nullable` | When the discount expires, if `null` the discount does not expire | | `uses` | `unsignedInteger` | How many times the discount has been used | | `max_uses` | `unsignedMediumInteger` `nullable` | Maximum times this discount can be applied storewide | | `max_uses_per_user` | `unsignedMediumInteger` `nullable` | Maximum times a single user can use this discount | | `priority` | `unsignedMediumInteger` | Order of priority (default: `1`) | | `stop` | `boolean` | Whether to stop processing further discounts after this one is applied | | `restriction` | `string` `nullable` | Restriction type | | `data` | `json` `nullable` | Discount type-specific configuration data | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `users` | `BelongsToMany` | `User` | Users who have used this discount | | `customers` | `BelongsToMany` | `Lunar\Models\Customer` | Customers the discount is restricted to | | `customerGroups` | `BelongsToMany` | `Lunar\Models\CustomerGroup` | Customer groups the discount is available to | | `channels` | `MorphToMany` | `Lunar\Models\Channel` | Channels the discount is available on | | `collections` | `BelongsToMany` | `Lunar\Models\Collection` | Collections associated with the discount | | `brands` | `BelongsToMany` | `Lunar\Models\Brand` | Brands associated with the discount | | `discountables` | `HasMany` | `Lunar\Models\Discountable` | All discountable entries (conditions, exclusions, limitations, rewards) | | `discountableConditions` | `HasMany` | `Lunar\Models\Discountable` | Products or variants that must be in the cart to activate the discount | | `discountableExclusions` | `HasMany` | `Lunar\Models\Discountable` | Products or variants excluded from the discount | | `discountableLimitations` | `HasMany` | `Lunar\Models\Discountable` | Products or variants the discount is limited to | | `discountableRewards` | `HasMany` | `Lunar\Models\Discountable` | Reward products or variants (used by BuyXGetY) | ### Scopes | Scope | Description | | :- | :- | | `active()` | Filters to discounts that have started and have not expired | | `usable()` | Filters to discounts where `uses` is less than `max_uses`, or `max_uses` is `null` | | `products($productIds, $types)` | Filters by associated product IDs and discountable types | | `productVariants($variantIds, $types)` | Filters by associated variant IDs and discountable types | | `collections($collectionIds, $types)` | Filters by associated collection IDs and discountable types | | `brands($brandIds, $types)` | Filters by associated brand IDs and discountable types | | `channel($channel)` | Filters by channel | | `customerGroup($customerGroup)` | Filters by customer group | ## Creating a Discount ```php theme={null} use Lunar\Models\Discount; Discount::create([ 'name' => '20% Coupon', 'handle' => '20_coupon', 'coupon' => '20OFF', 'type' => 'Lunar\DiscountTypes\AmountOff', 'data' => [ 'fixed_value' => false, 'percentage' => 20, 'min_prices' => [ 'USD' => 2000, // $20.00 minimum spend ], ], 'starts_at' => '2024-01-01 00:00:00', 'ends_at' => null, 'max_uses' => null, ]); ``` ## Discount Status The `Discount` model provides a `status` attribute that returns the current state of the discount based on its dates and usage. ```php theme={null} use Lunar\Models\Discount; $discount = Discount::find(1); $discount->status; // 'active', 'pending', 'expired', or 'scheduled' ``` | Status | Description | | :- | :- | | `active` | The discount has started and has not expired | | `pending` | The discount has not started yet | | `expired` | The discount has passed its `ends_at` date | | `scheduled` | The discount is scheduled for a future date | ## Resetting the Discount Cache For performance reasons, applicable discounts are cached per request. To reset this cache (for example, after adding a discount code to a cart), call `resetDiscounts()` on the `Discounts` facade: ```php theme={null} use Lunar\Facades\Discounts; Discounts::resetDiscounts(); ``` ## Validating Coupons The `Discounts` facade provides a method to validate whether a coupon code is valid: ```php theme={null} use Lunar\Facades\Discounts; $isValid = Discounts::validateCoupon('20OFF'); ``` The default coupon validator checks that the coupon exists on an active, usable discount. The validator class can be customized in the `config/lunar/discounts.php` configuration file: ```php theme={null} return [ 'coupon_validator' => \Lunar\Base\Validation\CouponValidator::class, ]; ``` ## Discountable The `Discountable` model links products, product variants, or collections to a discount. Each entry has a `type` that determines its role. ```php theme={null} Lunar\Models\Discountable ``` | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `discount_id` | `foreignId` | | | `discountable_type` | `string` | Morph type (e.g., `product`, `product_variant`, `collection`) | | `discountable_id` | `unsignedBigInteger` | Morph ID | | `type` | `string` | The role: `condition`, `exclusion`, `limitation`, or `reward` | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | The `type` field determines how the discountable relates to the discount: * **`condition`** — The product or variant must be in the cart for the discount to activate. * **`exclusion`** — The product or variant is excluded from the discount. * **`limitation`** — The discount only applies to these products or variants. * **`reward`** — These products or variants are given as the reward (used by BuyXGetY). ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `discount` | `BelongsTo` | `Lunar\Models\Discount` | The parent discount | | `discountable` | `MorphTo` | `Product`, `ProductVariant`, or `Collection` | The associated purchasable or collection | ## Built-in Discount Types Lunar ships with two discount types. Both extend `Lunar\DiscountTypes\AbstractDiscountType`. ### AmountOff ```php theme={null} Lunar\DiscountTypes\AmountOff ``` Applies either a percentage or fixed amount discount to eligible cart lines. The `data` column stores the discount configuration: **Percentage discount:** ```php theme={null} use Lunar\Models\Discount; Discount::create([ 'name' => '10% Off', 'handle' => '10_percent_off', 'type' => 'Lunar\DiscountTypes\AmountOff', 'data' => [ 'fixed_value' => false, 'percentage' => 10, 'min_prices' => [ 'USD' => 5000, // $50.00 minimum spend ], ], 'starts_at' => now(), 'ends_at' => null, ]); ``` **Fixed value discount:** ```php theme={null} use Lunar\Models\Discount; Discount::create([ 'name' => '$5 Off', 'handle' => '5_dollars_off', 'type' => 'Lunar\DiscountTypes\AmountOff', 'data' => [ 'fixed_value' => true, 'fixed_values' => [ 'USD' => 500, // $5.00 off (stored in minor units) 'EUR' => 450, ], ], 'starts_at' => now(), 'ends_at' => null, ]); ``` ### BuyXGetY ```php theme={null} Lunar\DiscountTypes\BuyXGetY ``` Allows "buy X, get Y free" style promotions. Condition products are defined through the `discountableConditions` relationship, and reward products through the `discountableRewards` relationship. Both relationships accept products, product variants, or collections. ```php theme={null} use Lunar\Models\Discount; $discount = Discount::create([ 'name' => 'Buy 2 Get 1 Free', 'handle' => 'buy_2_get_1', 'type' => 'Lunar\DiscountTypes\BuyXGetY', 'data' => [ 'min_qty' => 2, 'reward_qty' => 1, 'max_reward_qty' => 5, 'automatically_add_rewards' => false, ], 'starts_at' => now(), 'ends_at' => null, ]); ``` | Data Field | Type | Description | | :- | :- | :- | | `min_qty` | `integer` | Minimum quantity of condition products required to trigger the discount | | `reward_qty` | `integer` | Number of reward items per qualifying group | | `max_reward_qty` | `integer` | Maximum total reward items (optional) | | `automatically_add_rewards` | `boolean` | Whether to automatically add reward items to the cart | > [!NOTE] > > From Lunar 1.5, `BuyXGetY` also enforces the discount's own conditions (minimum spend, customer restrictions, and `max_uses_per_user`) before awarding a reward, in the same way as `Lunar\DiscountTypes\AmountOff`. In earlier versions only `min_qty` gated the discount. See the [upgrade guide](/1.x/getting-started/overview/upgrade-guide#discount-conditions-are-now-honored-by-buyxgety). #### Automatically adding rewards When `automatically_add_rewards` is `true`, qualifying carts have the reward added as a cart line rather than requiring the customer to add it themselves. * Products, product variants, and collections are all supported as the automatically added reward. * A reward quantity greater than one produces a single cart line with that quantity, not one line per item. * Reward lines are stored using Lunar's morph map, so `purchasable_type` matches any other line holding the same purchasable (for example `product_variant`). Queries that filter cart or order lines by morph type include reward lines. * Only rewards that can be fulfilled are selected, so a reward that is out of stock is skipped rather than raising an error when the line is added. #### Collection conditions and rewards Added in 1.5 A `BuyXGetY` discount can match against an entire collection rather than listing every product or variant individually. The match logic walks each cart line's product, checks the collections it belongs to, and compares those against the collections attached as conditions or rewards. ```php theme={null} use Lunar\Models\Collection; use Lunar\Models\Discount; $collection = Collection::find(1); $discount = Discount::create([ 'name' => 'Buy 2 from Summer, Get 1 from Sale', 'handle' => 'summer_sale', 'type' => 'Lunar\DiscountTypes\BuyXGetY', 'data' => [ 'min_qty' => 2, 'reward_qty' => 1, ], ]); $discount->collections()->attach($collection, ['type' => 'condition']); $discount->collections()->attach($collection, ['type' => 'reward']); ``` Conditions and rewards can mix product, variant, and collection discountables on the same discount. ## Custom Discount Types Custom discount types can be created by extending `Lunar\DiscountTypes\AbstractDiscountType`: ```php theme={null} [!WARNING] > > There should only ever be one default language. Setting more than one language as default will likely cause unexpected behavior. # Media Source: https://docs.lunarphp.com/1.x/reference/media Managing images and files on Lunar models using Spatie's Media Library. Lunar uses Spatie's Media Library package to manage images and files across models. ## Overview Lunar uses the [Laravel-medialibrary](https://spatie.be/docs/laravel-medialibrary) package by Spatie to handle media across all models. Rather than reinvent the wheel, Lunar leverages this battle-tested package and adds its own conventions on top, including configurable media definitions, automatic image conversions, and primary image management. ### Supported Models The following models support media out of the box via the `Lunar\Base\Traits\HasMedia` trait: | Model | Class | Has Thumbnail | | - | - | - | | Product | `Lunar\Models\Product` | Yes | | Product Option | `Lunar\Models\ProductOption` | No | | Product Option Value | `Lunar\Models\ProductOptionValue` | No | | Collection | `Lunar\Models\Collection` | Yes | | Brand | `Lunar\Models\Brand` | No | | Asset | `Lunar\Models\Asset` | No | > [!NOTE] > > `Lunar\Models\ProductVariant` does not use the `HasMedia` trait directly. Instead, it uses a many-to-many relationship with media through a pivot table. See [Product Variant Images](#product-variant-images) for details. ## Configuration The media configuration is published at `config/lunar/media.php`. ```php theme={null} use Lunar\Base\StandardMediaDefinitions; return [ 'definitions' => [ 'asset' => StandardMediaDefinitions::class, 'brand' => StandardMediaDefinitions::class, 'collection' => StandardMediaDefinitions::class, 'product' => StandardMediaDefinitions::class, 'product-option' => StandardMediaDefinitions::class, 'product-option-value' => StandardMediaDefinitions::class, ], 'collection' => 'images', 'fallback' => [ 'url' => env('FALLBACK_IMAGE_URL', null), 'path' => env('FALLBACK_IMAGE_PATH', null), ], ]; ``` | Key | Description | | - | - | | `definitions` | Maps model aliases to their media definition class. Each model can have its own definition class to customize collections and conversions. | | `collection` | The default media collection name used across all models. | | `fallback.url` | A fallback URL returned when a model has no media. | | `fallback.path` | A fallback file path returned when a model has no media. | The `definitions` keys use kebab-case aliases derived from the model class name (e.g., `Product` becomes `product`, `ProductOptionValue` becomes `product-option-value`). You can also use the fully qualified class name as the key. ## Adding Media Adding media to a model follows the standard Spatie Media Library API. ```php theme={null} use Lunar\Models\Product; $product = Product::find(123); $product->addMedia($request->file('image'))->toMediaCollection('images'); ``` For more information, see [Associating files](https://spatie.be/docs/laravel-medialibrary/v11/basic-usage/associating-files) in the Spatie documentation. ## Retrieving Media ```php theme={null} use Lunar\Models\Product; $product = Product::find(123); // Get all images $product->getMedia('images'); // Get the first image URL $product->getFirstMediaUrl('images'); // Get a specific conversion URL $product->getFirstMediaUrl('images', 'medium'); ``` For more information, see [Retrieving media](https://spatie.be/docs/laravel-medialibrary/v11/basic-usage/retrieving-media) in the Spatie documentation. ## Primary Images Lunar adds a concept of "primary" images on top of Spatie's media library. Each model can have one image marked as primary per collection, tracked via a `primary` custom property on the media item. ### Thumbnail Relationship Models using the `HasMedia` trait have a `thumbnail` relationship that returns the primary image: ```php theme={null} use Lunar\Models\Product; $product = Product::find(123); // Get the primary image via the thumbnail relationship $product->thumbnail; ``` ### Automatic Primary Management Lunar includes a `MediaObserver` that automatically enforces the following rules: * When a media item is marked as primary, all other items in the same collection are unmarked. * When the primary image is deleted, the first remaining image in the collection is automatically promoted to primary. * When a new image is added to an empty collection, it is automatically marked as primary. ### Setting the Primary Image ```php theme={null} $media = $product->getMedia('images')->first(); $media->setCustomProperty('primary', true)->save(); ``` ## Product Variant Images `ProductVariant` handles media differently from other models. Instead of using the `HasMedia` trait, it uses a many-to-many relationship with the `media` table through a `media_product_variant` pivot table. ```php theme={null} use Lunar\Models\ProductVariant; $variant = ProductVariant::find(456); // Get all images (ordered by position) $variant->images; // Get the thumbnail (primary image, or falls back to the product's thumbnail) $variant->getThumbnail(); ``` The pivot table includes: | Column | Type | Description | | - | - | - | | `primary` | `boolean` | Whether this is the primary image for the variant | | `position` | `smallInteger` | Display order of the image | ## Fallback Images If a model has no media, calling `getFirstMediaUrl` or `getFirstMediaPath` returns an empty string by default. Fallback images can be configured in `config/lunar/media.php` or via environment variables: ```php theme={null} 'fallback' => [ 'url' => env('FALLBACK_IMAGE_URL', null), 'path' => env('FALLBACK_IMAGE_PATH', null), ] ``` These values are passed to Spatie's `useFallbackUrl` and `useFallbackPath` methods on the media collection. ## Default Conversions The `StandardMediaDefinitions` class registers the following image conversions by default: | Conversion | Width | Height | Notes | | - | - | - | - | | `small` | 300 | 300 | Used by the admin panel for thumbnails. Registered globally (runs for all collections). | | `medium` | 500 | 500 | Registered on the `images` collection. | | `large` | 800 | 800 | Registered on the `images` collection. | | `zoom` | 500 | 500 | Registered on the `images` collection. | All conversions use `Fit::Fill` for sizing, a white background, and preserve the original image format. ## Custom Media Definitions To customize the media collections and conversions for a model, create a class that implements `Lunar\Base\MediaDefinitionsInterface`: ```php theme={null} namespace App\Media; use Lunar\Base\MediaDefinitionsInterface; use Spatie\Image\Enums\Fit; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\MediaCollections\MediaCollection; use Spatie\MediaLibrary\MediaCollections\Models\Media; class CustomMediaDefinitions implements MediaDefinitionsInterface { public function registerMediaConversions(HasMedia $model, ?Media $media = null): void { $model->addMediaConversion('small') ->fit(Fit::Fill, 300, 300) ->sharpen(10) ->keepOriginalImageFormat(); } public function registerMediaCollections(HasMedia $model): void { $fallbackUrl = config('lunar.media.fallback.url'); $fallbackPath = config('lunar.media.fallback.path'); // Reset to avoid duplication $model->mediaCollections = []; $collection = $model->addMediaCollection('images'); if ($fallbackUrl) { $collection = $collection->useFallbackUrl($fallbackUrl); } if ($fallbackPath) { $collection = $collection->useFallbackPath($fallbackPath); } $this->registerCollectionConversions($collection, $model); } protected function registerCollectionConversions(MediaCollection $collection, HasMedia $model): void { $conversions = [ 'zoom' => [ 'width' => 500, 'height' => 500, ], 'large' => [ 'width' => 800, 'height' => 800, ], 'medium' => [ 'width' => 500, 'height' => 500, ], ]; $collection->registerMediaConversions(function (Media $media) use ($model, $conversions) { foreach ($conversions as $key => $conversion) { $model->addMediaConversion($key) ->fit( Fit::Fill, $conversion['width'], $conversion['height'] )->keepOriginalImageFormat(); } }); } public function getMediaCollectionTitles(): array { return [ 'images' => 'Images', ]; } public function getMediaCollectionDescriptions(): array { return [ 'images' => '', ]; } } ``` Then register the class in `config/lunar/media.php`: ```php theme={null} 'definitions' => [ 'product' => \App\Media\CustomMediaDefinitions::class, // ... ], ``` ### Regenerating Conversions After changing conversion definitions, regenerate existing conversions using the Spatie artisan command: ```bash theme={null} php artisan media-library:regenerate ``` This creates queue jobs for each media entry to be reprocessed. See the [Spatie documentation](https://spatie.be/docs/laravel-medialibrary/v11/converting-images/regenerating-images) for more options. ## Extending Your Own Models Custom models can be given media support using the Lunar `HasMedia` trait: ```php theme={null} namespace App\Models; use Illuminate\Database\Eloquent\Model; use Lunar\Base\Traits\HasMedia; use Spatie\MediaLibrary\HasMedia as SpatieHasMedia; class YourCustomModel extends Model implements SpatieHasMedia { use HasMedia; } ``` This provides access to all Lunar media features including configurable definitions and automatic conversions. > [!WARNING] > > To use Lunar's media definitions and conversions, models must use the `Lunar\Base\Traits\HasMedia` trait. Using Spatie's `InteractsWithMedia` trait directly bypasses Lunar's media definition system. See the [Spatie documentation](https://spatie.be/docs/laravel-medialibrary/v11/basic-usage/preparing-your-model) for using the library directly. ### Definition Resolution The `HasMedia` trait resolves the media definition class for a model using the following priority: 1. A snake\_case alias in `config('lunar.media.definitions')` (e.g., `product` for `Product`) 2. The fully qualified class name in the config 3. The parent class name in the config (useful for extended models) 4. Falls back to `Lunar\Base\StandardMediaDefinitions` # Orders Source: https://docs.lunarphp.com/1.x/reference/orders Orders represent completed or in-progress purchases, created when a cart is converted at checkout. ## Overview Orders represent completed or in-progress purchases in a store. Orders are linked to carts, and although there is generally only one order per cart, the system supports multiple orders per cart if needed. > [!NOTE] > > All monetary values (such as `sub_total`, `total`, `tax_total`) are cast to `Lunar\DataTypes\Price` objects, providing access to `value`, `formatted()`, and `decimal` properties. ```php theme={null} Lunar\Models\Order ``` ### Fields | Field | Type | Description | | :- | :- | :- | | id | `id` | Primary key | | customer\_id | `foreignId` `nullable` | | | user\_id | `foreignId` `nullable` | The authenticated user who placed the order | | channel\_id | `foreignId` | The channel the order was placed through | | new\_customer | `boolean` | Whether the customer is a first-time buyer | | cart\_id | `foreignId` `nullable` | The cart used to create the order | | status | `string` | The order status | | reference | `string` `nullable` | The generated order reference | | customer\_reference | `string` `nullable` | A reference provided by the customer | | sub\_total | `unsignedBigInteger` | The subtotal minus any discounts, excluding tax | | discount\_total | `unsignedBigInteger` | The discount amount, excluding tax | | discount\_breakdown | `json` `nullable` | Breakdown of applied discounts | | shipping\_breakdown | `json` `nullable` | Breakdown of shipping charges | | shipping\_total | `unsignedBigInteger` | The shipping total including tax | | tax\_breakdown | `json` | Breakdown of applied taxes | | tax\_total | `unsignedBigInteger` | The total amount of tax applied | | total | `unsignedBigInteger` | The grand total including tax | | notes | `text` `nullable` | Additional order notes | | currency\_code | `string` | The currency code the order was placed in | | compare\_currency\_code | `string` `nullable` | The default currency code at the time of the order | | exchange\_rate | `decimal` | The exchange rate between `currency_code` and `compare_currency_code` | | placed\_at | `dateTime` `nullable` | The datetime the order was considered placed | | fingerprint | `string` `nullable` | A hash used to detect cart changes | | meta | `json` `nullable` | Custom metadata | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `channel` | BelongsTo | `Lunar\Models\Channel` | | | `cart` | BelongsTo | `Lunar\Models\Cart` | | | `currency` | BelongsTo | `Lunar\Models\Currency` | Matched on `currency_code` | | `customer` | BelongsTo | `Lunar\Models\Customer` | | | `user` | BelongsTo | User | The authenticatable model from auth config | | `lines` | HasMany | `Lunar\Models\OrderLine` | | | `physicalLines` | HasMany | `Lunar\Models\OrderLine` | Lines where type is `physical` | | `digitalLines` | HasMany | `Lunar\Models\OrderLine` | Lines where type is `digital` | | `shippingLines` | HasMany | `Lunar\Models\OrderLine` | Lines where type is `shipping` | | `productLines` | HasMany | `Lunar\Models\OrderLine` | All lines excluding shipping | | `addresses` | HasMany | `Lunar\Models\OrderAddress` | | | `shippingAddress` | HasOne | `Lunar\Models\OrderAddress` | Address where type is `shipping` | | `billingAddress` | HasOne | `Lunar\Models\OrderAddress` | Address where type is `billing` | | `transactions` | HasMany | `Lunar\Models\Transaction` | | | `captures` | HasMany | `Lunar\Models\Transaction` | Transactions where type is `capture` | | `intents` | HasMany | `Lunar\Models\Transaction` | Transactions where type is `intent` | | `refunds` | HasMany | `Lunar\Models\Transaction` | Transactions where type is `refund` | ## Creating an Order An order can be created directly or, the recommended approach, via a `Lunar\Models\Cart` model. ```php theme={null} use Lunar\Models\Order; use Lunar\Models\Cart; $order = Order::create([/** .. */]); // Recommended approach $order = Cart::first()->createOrder( allowMultipleOrders: false, orderIdToUpdate: null, ); ``` * `allowMultipleOrders` - Carts generally only have one draft order associated. Pass `true` to allow multiple orders per cart. * `orderIdToUpdate` - Optionally pass the ID of an existing draft order to update instead of creating a new one. The order must have a null `placed_at` value and belong to the cart. The underlying class for creating an order is `Lunar\Actions\Carts\CreateOrder`. This can be overridden in `config/lunar/cart.php`: ```php theme={null} return [ // ... 'actions' => [ // ... 'order_create' => CustomCreateOrder::class, ] ]; ``` At minimum, a custom class should extend `Lunar\Actions\AbstractAction`: ```php theme={null} use Lunar\Actions\AbstractAction; use Lunar\Models\Cart; final class CreateOrder extends AbstractAction { public function execute( Cart $cart, bool $allowMultipleOrders = false, ?int $orderIdToUpdate = null ): self { // ... return $this; } } ``` ### Validating a Cart Before Creation To check whether a cart is ready to create an order: ```php theme={null} $cart->canCreateOrder(); ``` This uses the `Lunar\Validation\Cart\ValidateCartForOrderCreation` class, which throws validation exceptions with helpful messages if the cart is not ready. A custom validation class can be specified in `config/lunar/cart.php`: ```php theme={null} return [ // ... 'validators' => [ 'order_create' => [ MyCustomValidator::class, ], ] ]; ``` A custom validator should extend `Lunar\Validation\BaseValidator`: ```php theme={null} use Lunar\Validation\BaseValidator; class MyCustomValidator extends BaseValidator { public function validate(): bool { $cart = $this->parameters['cart']; if ($somethingWentWrong) { return $this->fail('cart', 'There was an issue'); } return $this->pass(); } } ``` ## Order Reference Generation By default, Lunar generates an order reference when creating an order from a cart. The format is: ``` {prefix?}{0..0}{orderId} ``` `{0..0}` indicates the order ID is padded to 8 digits (not including the prefix). The prefix is optional and defined in `config/lunar/orders.php`. ### Custom Generators To use a custom reference generator, update `config/lunar/orders.php`: ```php theme={null} return [ 'reference_generator' => App\Generators\MyCustomGenerator::class, ]; ``` To disable reference generation entirely (not recommended), set the value to `null`. A custom generator must implement `Lunar\Base\OrderReferenceGeneratorInterface`: ```php theme={null} namespace App\Generators; use Lunar\Base\OrderReferenceGeneratorInterface; use Lunar\Models\Contracts\Order; class MyCustomGenerator implements OrderReferenceGeneratorInterface { public function generate(Order $order): string { // ... return 'my-custom-reference'; } } ``` ## Modifying Orders To programmatically change order values or add new behavior, the order system can be extended. See [Order Modifiers](/1.x/extending/orders) for more details. ## Order Status The `placed_at` field determines whether an order is considered draft or placed. The `Lunar\Models\Order` model provides two helper methods: ```php theme={null} $order->isDraft(); $order->isPlaced(); ``` ## Order Lines ```php theme={null} Lunar\Models\OrderLine ``` ### Fields | Field | Type | Description | | :- | :- | :- | | id | `id` | Primary key | | order\_id | `foreignId` | | | purchasable\_type | `string` `nullable` | Polymorphic type for the purchasable item. Empty on shipping lines | | purchasable\_id | `unsignedBigInteger` `nullable` | Polymorphic ID for the purchasable item. Empty on shipping lines | | type | `string` | The line type, e.g. `physical`, `digital`, `shipping` | | description | `string` | A description of the line item | | option | `string` `nullable` | Option information if the item is a variant | | identifier | `string` | An identifier for the purchasable item, typically a SKU | | unit\_price | `unsignedBigInteger` | The unit price of the line | | unit\_quantity | `unsignedSmallInteger` | The unit quantity, typically `1` | | quantity | `unsignedInteger` | The quantity purchased | | sub\_total | `unsignedBigInteger` | The subtotal minus any discounts, excluding tax | | discount\_total | `unsignedBigInteger` | The discount amount, excluding tax | | tax\_breakdown | `json` | Breakdown of applied taxes | | tax\_total | `unsignedBigInteger` | The total amount of tax applied | | total | `unsignedBigInteger` | The grand total including tax | | notes | `text` `nullable` | Additional line notes | | meta | `json` `nullable` | Custom metadata | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `order` | BelongsTo | `Lunar\Models\Order` | | | `purchasable` | MorphTo | — | The polymorphic purchasable item. `null` on shipping lines | | `currency` | HasOneThrough | `Lunar\Models\Currency` | Resolved through the order | > [!NOTE] > > Shipping lines do not have a purchasable. A shipping option is a data transfer object rather than a model, so from Lunar 1.5 shipping lines are stored with no morph and `$line->purchasable` returns `null`. Everything needed to display the line (`description`, `unit_price`, `total`, `meta`) is snapshotted onto the line itself. > > Guard for `null` when iterating `$order->lines`, or use `$order->productLines` to exclude shipping lines: > > ```php theme={null} > foreach ($order->productLines as $line) { > $line->purchasable->sku; > } > ``` ### Creating an Order Line > [!TIP] > > When using the `createOrder` method on a cart, order lines are created automatically. ```php theme={null} use Lunar\Models\OrderLine; OrderLine::create([ // ... ]); // Or via the relationship $order->lines()->create([ // ... ]); ``` ## Order Addresses An order can have many addresses, typically one for billing and one for shipping. ```php theme={null} Lunar\Models\OrderAddress ``` > [!TIP] > > When using the `createOrder` method on a cart, order addresses are created automatically. ### Fields | Field | Type | Description | | :- | :- | :- | | id | `id` | Primary key | | order\_id | `foreignId` | | | country\_id | `foreignId` `nullable` | | | title | `string` `nullable` | | | first\_name | `string` `nullable` | | | last\_name | `string` `nullable` | | | company\_name | `string` `nullable` | | | tax\_identifier | `string` `nullable` | A tax identification number | | line\_one | `string` `nullable` | | | line\_two | `string` `nullable` | | | line\_three | `string` `nullable` | | | city | `string` `nullable` | | | state | `string` `nullable` | | | postcode | `string` `nullable` | | | delivery\_instructions | `string` `nullable` | | | contact\_email | `string` `nullable` | | | contact\_phone | `string` `nullable` | | | type | `string` | The address type: `billing` or `shipping` | | shipping\_option | `string` `nullable` | A unique identifier for the selected shipping option | | meta | `json` `nullable` | Custom metadata | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `order` | BelongsTo | `Lunar\Models\Order` | | | `country` | BelongsTo | `Lunar\Models\Country` | | ### Creating an Order Address ```php theme={null} use Lunar\Models\OrderAddress; OrderAddress::create([ 'order_id' => 1, 'country_id' => 1, 'title' => null, 'first_name' => 'Jacob', 'last_name' => null, 'company_name' => null, 'line_one' => '123 Foo Street', 'line_two' => null, 'line_three' => null, 'city' => 'London', 'state' => null, 'postcode' => 'NW1 1WN', 'delivery_instructions' => null, 'contact_email' => null, 'contact_phone' => null, 'type' => 'shipping', 'shipping_option' => null, ]); // Or via the relationship $order->addresses()->create([ // ... ]); ``` The shipping and billing addresses can be accessed directly: ```php theme={null} $order->shippingAddress; $order->billingAddress; ``` ## Shipping Options > [!TIP] > > A Shipping Tables add-on is planned to simplify shipping configuration in the admin panel. To add shipping options, [extend Lunar](/1.x/extending/shipping) with custom logic. Shipping options can be fetched using the `ShippingManifest` facade: ```php theme={null} \Lunar\Facades\ShippingManifest::getOptions(\Lunar\Models\Cart $cart); ``` This returns a collection of `Lunar\DataTypes\ShippingOption` objects. ### Adding a Shipping Option to the Cart Once a shipping option has been selected, add it to the cart so totals can be recalculated: ```php theme={null} $cart->setShippingOption(\Lunar\DataTypes\ShippingOption $option); ``` ## Transactions ```php theme={null} Lunar\Models\Transaction ``` ### Fields | Field | Type | Description | | :- | :- | :- | | id | `id` | Primary key | | parent\_transaction\_id | `foreignId` `nullable` | A reference to a parent transaction | | order\_id | `foreignId` | | | success | `boolean` | Whether the transaction was successful | | type | `enum` | The transaction type: `capture`, `intent`, or `refund` | | driver | `string` | The payment driver used, e.g. `stripe` | | amount | `unsignedBigInteger` | The transaction amount | | reference | `string` | The reference returned from the payment provider | | status | `string` | The transaction status, e.g. `settled` | | notes | `string` `nullable` | Any relevant notes | | card\_type | `string` `nullable` | The card type, e.g. `visa` | | last\_four | `string` `nullable` | The last four digits of the card | | meta | `json` `nullable` | Custom metadata | | captured\_at | `dateTime` `nullable` | When the transaction was captured | | created\_at | `timestamp` | | | updated\_at | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `order` | BelongsTo | `Lunar\Models\Order` | | | `currency` | HasOneThrough | `Lunar\Models\Currency` | Resolved through the order | ### Creating a Transaction > [!TIP] > > An order having transactions does not mean it has been placed. Lunar determines whether an order is placed based on whether the `placed_at` column has a datetime value, regardless of any transactions. Most stores will want to store transactions against orders to track how much has been paid, the payment method used, and how to issue refunds if needed. ```php theme={null} use Lunar\Models\Transaction; Transaction::create([ //... ]); // Or via the order $order->transactions()->create([ //.. ]); ``` Transactions can be retrieved via relationships: ```php theme={null} $order->transactions; // All transactions $order->captures; // Capture transactions $order->intents; // Intent transactions $order->refunds; // Refund transactions ``` ## Payments Lunar is payment-provider agnostic. Any payment provider can be integrated with a storefront. The key factor for an order is whether the `placed_at` column is populated. Everything else about payment handling is left to the store implementation. Lunar provides helper utilities (as described above) to manage the payment lifecycle. ## Order Notifications Lunar allows specifying which Laravel mailers should be available when updating an order's status. These are configured in `config/lunar/orders.php`: ```php theme={null} 'statuses' => [ 'awaiting-payment' => [ 'label' => 'Awaiting Payment', 'color' => '#848a8c', 'mailers' => [ App\Mail\MyMailer::class, App\Mail\MyOtherMailer::class, ], 'notifications' => [], ], // ... ], ``` When updating an order's status in the admin panel, any configured mailers for the new status are available to select. Email addresses can be chosen, and additional addresses can be added. Lunar stores a render of the sent email in the activity log, providing a clear history of communications. > [!TIP] > > These email notifications are not sent automatically when updating the status programmatically outside of the admin panel. > [!WARNING] > > The `notifications` key is present in the default config but is not currently read anywhere in Lunar — defining notifications here has no effect. Only `mailers` are dispatched. If you need to notify someone (staff, customer, a Slack channel, etc.) when an order's status changes outside the admin panel, listen for the update yourself, for example by observing the `Order` model's `updated` event and checking `$order->wasChanged('status')`. ### Mailer Template When building a mailer template, the `$order` model is available in the view data. When the status is updated, the order is passed through along with any additional content entered. Since additional content may not always be present, check for its existence first. Example template: ```blade theme={null}Your order with reference {{ $order->reference }} has been dispatched!
{{ $order->total->formatted() }}
@if($content ?? null){{ $content }}
@endif @foreach($order->lines as $line) @endforeach ``` ## Order Invoice PDF By default, clicking "Download PDF" in the admin panel when viewing an order generates a basic PDF. The view powering this PDF can be published for customization: ```bash theme={null} php artisan vendor:publish --tag=lunarpanel.pdf ``` This creates a view at `resources/vendor/lunarpanel/pdf/order.blade.php` that can be freely customized. # Payments Source: https://docs.lunarphp.com/1.x/reference/payments Lunar's driver-based payment system for handling payment authorization, capture, and refunds. Lunar uses a driver-based payment system for handling authorization, capture, and refunds. ## Overview Lunar uses a driver-based approach for payments. This means any payment provider can be supported, either through first-party add-ons, community packages, or a custom driver built for the specific needs of a storefront. By default, Lunar ships with an `OfflinePayment` driver suitable for cash-in-hand or manual payment scenarios. For online payments, a driver for the desired payment provider should be installed or created. > [!TIP] > > To learn how to build a custom payment driver, see the [Extending Payments](/1.x/extending/payments) guide. ## Configuration Payment configuration is located in `config/lunar/payments.php`. This file defines the default payment type and a list of available payment types, each mapped to a driver. ```php theme={null} env('PAYMENTS_TYPE', 'cash-in-hand'), 'types' => [ 'cash-in-hand' => [ 'driver' => 'offline', 'authorized' => 'payment-offline', ], 'card' => [ 'driver' => 'stripe', 'authorized' => 'payment-received', ], ], ]; ``` Each type entry supports the following keys: | Key | Description | | :- | :- | | `driver` | The registered payment driver to use for this type | | `authorized` | The order status to set when payment is authorized | Any additional keys defined on a type are passed to the driver via the `setConfig` method automatically. ## Usage ### Getting a payment driver To retrieve a payment driver instance, pass the desired payment type to the `Payments` facade. This returns an instance of the driver registered for that type. ```php theme={null} use Lunar\Facades\Payments; $driver = Payments::driver('card'); ``` If no type is specified, the default type from the configuration is used. ```php theme={null} $driver = Payments::driver(); ``` ### Setting the cart Before authorizing a payment, set the cart on the driver. ```php theme={null} use Lunar\Models\Cart; $driver->cart($cart); ``` ### Passing additional data Some payment providers require additional data such as payment tokens or intent IDs. Pass this data using the `withData` method. ```php theme={null} $driver->withData([ 'payment_token' => $token, ]); ``` ### Setting an order In some cases, it may be necessary to set an existing order on the driver rather than a cart. The `order` method handles this. ```php theme={null} use Lunar\Models\Order; $driver->order($order); ``` ### Authorizing a payment Once the driver is configured, call the `authorize` method to process the payment. This returns a `PaymentAuthorize` response. ```php theme={null} use Lunar\Base\DataTransferObjects\PaymentAuthorize; $response = $driver->authorize(); $response->success; // bool $response->message; // ?string $response->orderId; // ?int $response->paymentType; // ?string ``` ### Method chaining All setter methods on the driver return `self`, allowing for a fluent API. ```php theme={null} use Lunar\Facades\Payments; $response = Payments::driver('card') ->cart($cart) ->withData(['payment_token' => $token]) ->authorize(); ``` ## Response types Payment drivers return one of three data transfer objects depending on the operation. ### PaymentAuthorize ```php theme={null} Lunar\Base\DataTransferObjects\PaymentAuthorize ``` Returned by the `authorize` method. | Property | Type | Description | | :- | :- | :- | | `success` | `bool` | Whether the authorization was successful | | `message` | `?string` | An optional message from the provider | | `orderId` | `?int` | The ID of the created or associated order | | `paymentType` | `?string` | The payment type identifier | ### PaymentCapture ```php theme={null} Lunar\Base\DataTransferObjects\PaymentCapture ``` Returned by the `capture` method when capturing a previously authorized payment. | Property | Type | Description | | :- | :- | :- | | `success` | `bool` | Whether the capture was successful | | `message` | `string` | A message from the provider | ### PaymentRefund ```php theme={null} Lunar\Base\DataTransferObjects\PaymentRefund ``` Returned by the `refund` method when refunding a captured payment. | Property | Type | Description | | :- | :- | :- | | `success` | `bool` | Whether the refund was successful | | `message` | `?string` | An optional message from the provider | ## Events ### PaymentAttemptEvent The `Lunar\Events\PaymentAttemptEvent` is dispatched whenever a payment authorization is attempted. This event receives the `PaymentAuthorize` response object. ```php theme={null} use Lunar\Events\PaymentAttemptEvent; PaymentAttemptEvent::dispatch($paymentAuthorize); ``` This event can be used to log payment attempts, trigger notifications, or perform post-payment processing via a listener. ## Payment checks Some payment providers return verification checks related to 3D Secure, address verification, or other fraud prevention measures. These checks are accessible on a `Lunar\Models\Transaction` model via the `paymentChecks` method. ```php theme={null} foreach ($transaction->paymentChecks() as $check) { $check->successful; // bool $check->label; // string $check->message; // string } ``` > [!NOTE] > > For details on the Transaction model, order creation, and order management, see the [Orders](/1.x/reference/orders) reference. ## Available drivers ### First party | Driver | Package | | :- | :- | | Stripe | [lunarphp/stripe](https://github.com/lunarphp/stripe) | ### Community Community-built payment drivers can be found in the [Add-ons](/1.x/addons/payments/stripe) section. To list a custom driver, reach out on the [Lunar Discord](https://lunarphp.com/discord). # Pricing Source: https://docs.lunarphp.com/1.x/reference/pricing Format and display prices with currency-aware formatting, decimal conversion, and unit pricing support. Lunar provides currency-aware price formatting and display for storefront use. ## Overview When displaying prices on a storefront, it is important to show the correct format relative to the currency the customer is purchasing in. Every storefront is different. Lunar provides a default price formatter that suits most use cases, while also making it straightforward to swap in a custom implementation for stores with specific formatting requirements. ## The Price model ```php theme={null} Lunar\Models\Price ``` | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `customer_group_id` | `foreignId` `nullable` | Associated customer group for tiered pricing | | `currency_id` | `foreignId` | Associated currency | | `priceable_type` | `string` | Morph type for the parent model | | `priceable_id` | `unsignedBigInteger` | Morph ID for the parent model | | `price` | `unsignedBigInteger` | Price value stored in the smallest currency unit (e.g. cents) | | `compare_price` | `unsignedBigInteger` `nullable` | Comparison/original price for displaying discounts | | `min_quantity` | `integer` | Minimum quantity required for this price tier (default: 1) | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | Both the `price` and `compare_price` fields are automatically cast to `Lunar\DataTypes\Price` objects when accessed. ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `priceable` | `MorphTo` | Various | The model this price belongs to (e.g. `ProductVariant`) | | `currency` | `BelongsTo` | `Lunar\Models\Currency` | The currency for this price | | `customerGroup` | `BelongsTo` | `Lunar\Models\CustomerGroup` | Optional customer group for group-specific pricing | ### Tax helper methods The `Lunar\Models\Price` model provides methods for retrieving prices with or without tax applied, based on the `lunar.pricing.stored_inclusive_of_tax` configuration value. ```php theme={null} use Lunar\Models\Price; $price = Price::find(1); $price->priceExTax(); // Lunar\DataTypes\Price $price->priceIncTax(); // Lunar\DataTypes\Price $price->comparePriceIncTax(); // Lunar\DataTypes\Price ``` #### Overriding the tax zone Added in 1.5 Each method accepts an optional `Lunar\Models\TaxZone` to override the zone used when computing the tax rate. When no zone is passed, the store's default tax zone is used. ```php theme={null} use Lunar\Models\Price; use Lunar\Models\TaxZone; $price = Price::find(1); $zone = TaxZone::where('name', 'EU')->first(); $price->priceIncTax($zone); $price->priceExTax($zone); $price->comparePriceIncTax($zone); ``` This is useful when displaying product prices for a known visitor region before the cart is built. Once items are in the cart, the cart's own `tax_zone_id` (see [Setting the Tax Zone](/1.x/reference/carts#setting-the-tax-zone)) drives tax-inclusive line totals. ## The Price data type The `Lunar\DataTypes\Price` class is used throughout Lunar whenever a price value needs formatting. It is not limited to the `Lunar\Models\Price` model. The following models also have attributes that return `Lunar\DataTypes\Price` instances: ### `Lunar\Models\Order` * `sub_total` * `discount_total` * `shipping_total` * `tax_total` * `total` ### `Lunar\Models\OrderLine` * `unit_price` * `sub_total` * `discount_total` * `tax_total` * `total` ### `Lunar\Models\Transaction` * `amount` ## Price formatting The class responsible for price formatting is configured in the `config/lunar/pricing.php` file: ```php theme={null} return [ // ... 'formatter' => \Lunar\Pricing\DefaultPriceFormatter::class, ]; ``` ### DefaultPriceFormatter The `Lunar\Pricing\DefaultPriceFormatter` ships with Lunar and handles most use cases for formatting a price. To demonstrate, start by creating a standard price model: ```php theme={null} use Lunar\Models\Price; $priceModel = Price::create([ // ... 'price' => 1000, // Stored as an integer in the smallest currency unit 'min_quantity' => 1, ]); // Lunar\DataTypes\Price $priceDataType = $priceModel->price; ``` #### Raw value Return the raw integer value as stored in the database: ```php theme={null} $priceDataType->value; // 1000 ``` #### Decimal value Return the decimal representation of the price. The decimal value accounts for the number of decimal places configured on the currency. For example, if the currency has 2 decimal places: ```php theme={null} $priceDataType->decimal(rounding: true); // 10.00 $priceDataType->unitDecimal(rounding: true); // 10.00 ``` These two values are identical in this example. The `unitDecimal` method factors in the `unit_quantity` of the purchasable model. Consider the following: ```php theme={null} use Lunar\Models\ProductVariant; $productVariant = ProductVariant::create([ // ... 'unit_quantity' => 10, ]); ``` By setting `unit_quantity` to 10, Lunar is told that 10 individual units make up this product at this price point. This is useful for items where a single unit would cost less than the smallest currency denomination (e.g. 0.001 EUR). ```php theme={null} $priceModel = $productVariant->prices()->create([ 'price' => 10, // 0.10 EUR 'currency_id' => $currency->id, ]); // Lunar\DataTypes\Price $priceDataType = $priceModel->price; ``` Now the difference becomes clear: ```php theme={null} $priceDataType->decimal(rounding: true); // 0.10 $priceDataType->unitDecimal(rounding: true); // 0.01 ``` The `unitDecimal` method divides by the unit quantity, giving the per-unit cost of `0.01`. #### Formatted currency string The formatted price uses the native PHP [NumberFormatter](https://www.php.net/manual/en/class.numberformatter.php). A locale and formatting style can be specified: ```php theme={null} $priceDataType->formatted('fr'); // 10,00 £GB $priceDataType->formatted('en-gb', \NumberFormatter::SPELLOUT); // ten point zero zero $priceDataType->unitFormatted('en-gb'); // £10.00 ``` ### Full method reference ```php theme={null} $priceDataType->decimal( rounding: false ); $priceDataType->unitDecimal( rounding: false ); $priceDataType->formatted( locale: null, formatterStyle: NumberFormatter::CURRENCY, decimalPlaces: null, trimTrailingZeros: true ); $priceDataType->unitFormatted( locale: null, formatterStyle: NumberFormatter::CURRENCY, decimalPlaces: null, trimTrailingZeros: true ); ``` ## Creating a custom formatter A custom formatter must implement `Lunar\Pricing\PriceFormatterInterface` and accept `$value`, `$currency`, and `$unitQty` as constructor parameters. ```php theme={null} currency) { $this->currency = \Lunar\Models\Currency::getDefault(); } } public function decimal(): float { // ... } public function unitDecimal(): float { // ... } public function formatted(): mixed { // ... } public function unitFormatted(): mixed { // ... } } ``` The methods can accept any number of arguments beyond those defined in the interface. The formatter is not bound to the same parameter signatures as `DefaultPriceFormatter`. Once implemented, register the custom formatter in `config/lunar/pricing.php`: ```php theme={null} return [ // ... 'formatter' => \App\Pricing\CustomPriceFormatter::class, ]; ``` ## Model casting For custom models that need price formatting, Lunar provides a cast class. The only requirement is that the column stores an `integer` value. ```php theme={null} use Illuminate\Database\Eloquent\Model; use Lunar\Base\Casts\Price; class MyModel extends Model { protected $casts = [ // ... 'price' => Price::class, ]; } ``` > [!NOTE] > > The `Lunar\Base\Casts\Price` cast resolves the currency from the model's `currency` relationship. If no currency relationship exists, it falls back to the default currency. # Products Source: https://docs.lunarphp.com/1.x/reference/products Define, categorize, and manage products with variants, pricing, options, and associations. Products are the core catalog model in Lunar, representing items available for sale with variants, pricing, and options. ## Overview Products represent the items available for sale in a store. All custom attributes are defined against the product, and products can have multiple variations. In Lunar, a product always has at least one variant. When a product has only a single variant, the editing experience appears as though the product itself is being edited directly, but behind the scenes the data lives on the variant. Every product belongs to a `ProductType`, which determines which attributes are available during editing. Products can also optionally belong to a `Brand`. ```php theme={null} Lunar\Models\Product ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `brand_id` | `foreignId` `nullable` | Optional brand association | | `product_type_id` | `foreignId` | The product type | | `status` | `string` | Product status (e.g. `published`, `draft`) | | `attribute_data` | `json` `nullable` | Custom attribute data | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | | `deleted_at` | `timestamp` `nullable` | Soft deletes | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `productType` | BelongsTo | `Lunar\Models\ProductType` | The product's type | | `brand` | BelongsTo | `Lunar\Models\Brand` | The product's brand | | `variants` | HasMany | `Lunar\Models\ProductVariant` | All variants of the product | | `variant` | HasOne | `Lunar\Models\ProductVariant` | Single variant convenience accessor | | `prices` | HasManyThrough | `Lunar\Models\Price` | All prices across variants | | `collections` | BelongsToMany | `Lunar\Models\Collection` | Pivot: `position` | | `associations` | HasMany | `Lunar\Models\ProductAssociation` | Outgoing product associations | | `inverseAssociations` | HasMany | `Lunar\Models\ProductAssociation` | Incoming product associations | | `customerGroups` | BelongsToMany | `Lunar\Models\CustomerGroup` | Pivot: `purchasable`, `visible`, `enabled`, `starts_at`, `ends_at` | | `channels` | MorphToMany | `Lunar\Models\Channel` | Pivot: `enabled`, `starts_at`, `ends_at` | | `productOptions` | BelongsToMany | `Lunar\Models\ProductOption` | Pivot: `position` | | `urls` | MorphMany | `Lunar\Models\Url` | SEO-friendly URLs | | `tags` | MorphToMany | `Lunar\Models\Tag` | | | `images` | MorphMany | Media | Product images | | `thumbnail` | MorphOne | Media | Primary thumbnail image | ### Scopes | Scope | Description | | :- | :- | | `status($status)` | Filter by product status | | `channel($channel, $startsAt, $endsAt)` | Filter by channel availability | | `customerGroup($group, $startsAt, $endsAt)` | Filter by customer group visibility | ## Creating a Product ```php theme={null} use Lunar\Models\Product; use Lunar\FieldTypes\Text; use Lunar\FieldTypes\TranslatedText; Product::create([ 'product_type_id' => $productType->id, 'status' => 'published', 'brand_id' => $brand->id, 'attribute_data' => [ 'name' => new TranslatedText(collect([ 'en' => new Text('FooBar'), ])), 'description' => new Text('This is a Foobar product.'), ], ]); ``` > [!WARNING] > > Lunar internally expects and uses the `name` attribute in product attribute data. It must be included in the product type's attributes and populated; otherwise the admin panel may throw unexpected errors. ### Filtering by status ```php theme={null} use Lunar\Models\Product; Product::status('published')->get(); ``` ## Channels Products support multi-channel availability through the `HasChannels` trait. When a product is created, all channels are automatically synced. Each channel can be independently enabled or disabled, with optional start and end dates for scheduled availability. ### Scheduling a channel ```php theme={null} // Enable for a channel immediately $product->scheduleChannel($channel); // Schedule availability to start in 14 days $product->scheduleChannel($channel, now()->addDays(14)); // Accepts a collection of channels $product->scheduleChannel(Channel::get()); ``` ### Filtering by channel ```php theme={null} use Lunar\Models\Product; $products = Product::channel($channel)->get(); ``` ## Customer Groups Products can be assigned to customer groups with optional scheduling. This controls whether the product is visible and purchasable for members of each group. ### Scheduling a customer group ```php theme={null} // Enable for this customer group immediately $product->scheduleCustomerGroup($customerGroup); // Schedule the product to be enabled in 14 days for this customer group $product->scheduleCustomerGroup($customerGroup, now()->addDays(14)); // Accepts an array or collection of customer groups $product->scheduleCustomerGroup(CustomerGroup::get()); ``` ### Filtering by customer group The `customerGroup` scope accepts a single customer group (or ID), or a collection/array of customer groups or IDs. ```php theme={null} use Lunar\Models\Product; $products = Product::customerGroup(CustomerGroup::find(1))->paginate(50); $products = Product::customerGroup([ $groupA, $groupB, ])->paginate(50); ``` ## Product Types Product types categorize products and determine which attributes are available during editing (e.g. Television, T-Shirt, Book, Phone). ```php theme={null} Lunar\Models\ProductType ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `name` | `string` | The product type name | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `products` | HasMany | `Lunar\Models\Product` | All products of this type | | `mappedAttributes` | MorphToMany | `Lunar\Models\Attribute` | All attributes mapped to this type | | `productAttributes` | MorphToMany | `Lunar\Models\Attribute` | Attributes for products | | `variantAttributes` | MorphToMany | `Lunar\Models\Attribute` | Attributes for variants | ### Creating a product type ```php theme={null} use Lunar\Models\ProductType; $productType = ProductType::create([ 'name' => 'Boots', ]); ``` Product types have [Attributes](/1.x/reference/attributes) associated to them. These associated attributes determine which fields are available to products when editing. For example, an attribute of `Screen Type` associated to a `TVs` product type would make that field available on any product with that type. Attributes can be associated using a standard [polymorphic relationship](https://laravel.com/docs/eloquent-relationships#many-to-many-polymorphic-relations): ```php theme={null} $productType->mappedAttributes()->attach([/* attribute ids ... */]); ``` Both `Product` and `ProductVariant` attributes can be associated to a product type, and each will display on the corresponding model when editing. > [!WARNING] > > Deleting an attribute will drop the association and could result in data loss. ### Retrieving the product type relationship ```php theme={null} $product->productType; $product->load(['productType']); ``` ## Product Options Product options define the different variations available for a product. Each `ProductOption` has a set of `ProductOptionValue` models. For example, a `ProductOption` called "Color" could have values like "Blue", "Red", and "Green". > [!TIP] > > Product options and product option values are defined at a system level and are translatable. ### Creating a ProductOption ```php theme={null} use Lunar\Models\ProductOption; $option = ProductOption::create([ 'name' => [ 'en' => 'Color', 'fr' => 'Couleur', ], 'label' => [ 'en' => 'Color', 'fr' => 'Couleur', ], ]); ``` Values can then be created for the option: ```php theme={null} // Lunar\Models\ProductOptionValue $option->values()->createMany([ [ 'name' => [ 'en' => 'Blue', 'fr' => 'Bleu', ], ], [ 'name' => [ 'en' => 'Red', 'fr' => 'Rouge', ], ], ]); ``` This product option and its values are now ready to be used with product variants. ### Product Option Meta Both `ProductOption` and `ProductOptionValue` models include a `meta` field for storing custom information such as color hex values, image links, or other display data. Lunar makes no assumptions about the structure of the `meta` JSON field. Any values can be stored in whatever format the application requires. ## Product Associations Products can be associated with other products as cross-sells, up-sells, or alternates. See the [Associations](/1.x/reference/associations) reference for full details on creating and managing product associations. ## Variants Variants represent the different purchasable permutations of a product, such as "Small Blue T-shirt" or "Size 9 Leather Boots". The product acts as the parent, and variants hold the specific data including pricing, inventory, shipping information, and product identifiers. A product always has at least one variant. When additional variants are generated, Lunar uses the first variant as a baseline for pricing, inventory, and other data. ```php theme={null} Lunar\Models\ProductVariant ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `product_id` | `foreignId` | The parent product | | `tax_class_id` | `foreignId` | Tax classification | | `tax_ref` | `string` `nullable` | Tax reference identifier | | `unit_quantity` | `integer` | Units per single purchase, default: `1` | | `min_quantity` | `integer` | Minimum purchasable quantity, default: `1` | | `quantity_increment` | `integer` | Purchase quantity step, default: `1` | | `sku` | `string` `nullable` | Stock keeping unit | | `gtin` | `string` `nullable` | Global Trade Item Number | | `mpn` | `string` `nullable` | Manufacturer Part Number | | `ean` | `string` `nullable` | European Article Number | | `length_value` | `decimal(10,4)` `nullable` | Length dimension | | `length_unit` | `string` `nullable` | Length unit of measure | | `width_value` | `decimal(10,4)` `nullable` | Width dimension | | `width_unit` | `string` `nullable` | Width unit of measure | | `height_value` | `decimal(10,4)` `nullable` | Height dimension | | `height_unit` | `string` `nullable` | Height unit of measure | | `weight_value` | `decimal(10,4)` `nullable` | Weight value | | `weight_unit` | `string` `nullable` | Weight unit of measure | | `volume_value` | `decimal(10,4)` `nullable` | Volume value | | `volume_unit` | `string` `nullable` | Volume unit of measure | | `shippable` | `boolean` | Whether the variant requires shipping, default: `true` | | `stock` | `integer` | Current stock quantity, default: `0` | | `backorder` | `integer` | Backorder quantity, default: `0` | | `purchasable` | `string` | Purchasability mode: `always` or `in_stock`, default: `always` | | `attribute_data` | `json` `nullable` | Custom attribute data | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | | `deleted_at` | `timestamp` `nullable` | Soft deletes | ### Product Identifiers Each variant can store product identifiers for use in internal systems or external services. **SKU** (Stock Keeping Unit) — A code (usually eight alphanumeric digits) used to track stock levels internally. Each variant of a product typically has a unique SKU. **GTIN** (Global Trade Item Number) — An internationally recognized product identifier, often accompanying a barcode. Useful with services like Google Shopping to help classify products. **MPN** (Manufacturer Part Number) — An identifier from the manufacturer that differentiates a product among similar items from the same brand. **EAN** (European Article Number) — A series of characters that identifies specific products within an inventory system. ### Creating Variants A product variant requires a product, currency (for pricing), and a tax class. ```php theme={null} use Lunar\Models\Product; use Lunar\Models\ProductVariant; use Lunar\Models\TaxClass; use Lunar\Models\Currency; $product = Product::where(...)->first(); $taxClass = TaxClass::where(...)->first(); $currency = Currency::where(...)->first(); ``` Create the product option and its values: ```php theme={null} use Lunar\Models\ProductOption; $option = ProductOption::create([ 'name' => [ 'en' => 'Color', ], 'label' => [ 'en' => 'Color', ], ]); $blueOption = $option->values()->create([ 'name' => [ 'en' => 'Blue', ], ]); $redOption = $option->values()->create([ 'name' => [ 'en' => 'Red', ], ]); ``` Create the variants and attach their option values: ```php theme={null} $blueVariant = ProductVariant::create([ 'product_id' => $product->id, 'tax_class_id' => $taxClass->id, 'sku' => 'blue-product', ]); $blueVariant->values()->attach($blueOption); $redVariant = ProductVariant::create([ 'product_id' => $product->id, 'tax_class_id' => $taxClass->id, 'sku' => 'red-product', ]); $redVariant->values()->attach($redOption); ``` Then create pricing for each variant: ```php theme={null} $blueVariant->prices()->create([ 'price' => 199, 'currency_id' => $currency->id, ]); $redVariant->prices()->create([ 'price' => 199, 'currency_id' => $currency->id, ]); ``` ### Exceptions | Exception | Conditions | | :- | :- | | `Illuminate\Validation\ValidationException` | Thrown if validation fails on the value options array | ## Shipping By default, all product variants are marked as shippable. To mark a variant as non-shippable: ```php theme={null} $variant->update([ 'shippable' => false, ]); ``` ### Dimensions Products can store dimension data on each variant. The available dimensions are: * Length * Width * Height * Weight * Volume For handling unit conversions, Lunar uses the [Cartalyst Converter](https://github.com/cartalyst/converter) package, which supports a wide range of units of measure. Each dimension has a corresponding `_value` and `_unit` column in the database: ```php theme={null} $variant->length_value; $variant->length_unit; $variant->width_value; $variant->width_unit; // etc. ``` ### Configuring measurements Available units of measure can be configured in the `lunar/shipping.php` config file. The defaults include: **Length:** m, mm, cm, ft, in **Weight:** kg, g, lbs **Volume:** l, ml, gal, floz ### Getting and converting measurement values The raw `*_value` and `*_unit` values can be accessed directly, but Lunar also provides an accessor for each dimension that supports conversion: ```php theme={null} $variant->length->to('length.ft')->convert(); ``` #### Volume calculation Volume can be calculated automatically from the length, width, and height dimensions, or set manually: ```php theme={null} $variant->update([ 'length_value' => 50, 'length_unit' => 'mm', 'height_value' => 50, 'height_unit' => 'mm', 'width_value' => 50, 'width_unit' => 'mm', ]); // Returns ml by default $variant->volume->getValue(); // 125.0 // Convert to any supported volume unit $variant->volume->to('volume.l')->convert()->getValue(); // 0.125 // Setting a manual volume overrides the automatic calculation $variant->update([ 'volume_unit' => 'floz', 'volume_value' => 100, ]); $variant->volume->getValue(); // 100 $variant->volume->to('volume.l')->convert()->getValue(); // 2.95735... ``` **Formatted values** ```php theme={null} $variant->length->to('length.cm')->convert()->format(); // 50cm ``` ## Pricing ### Overview Prices are stored in the database as integers. When retrieving a `Price` model, the `price` and `compare_price` attributes are cast to a `Price` datatype with useful helpers for display. | Field | Description | Default | Required | | :- | :- | :- | :- | | `price` | An integer value for the price | `null` | yes | | `compare_price` | A comparison price for display purposes (e.g. RRP) | `null` | no | | `currency_id` | The ID of the related currency | `null` | yes | | `min_quantity` | The minimum quantity required to get this price | `1` | no | | `customer_group_id` | The customer group this price applies to; `null` means all groups | `null` | no | | `priceable_type` | The class reference to the related model that owns the price | `null` | yes | | `priceable_id` | The ID of the related model that owns the price | `null` | yes | ```php theme={null} use Lunar\Models\ProductVariant; use Lunar\Models\Price; $priceable = ProductVariant::create([/* ... */]); Price::create([ 'price' => 199, 'compare_price' => 299, 'currency_id' => 1, 'min_quantity' => 1, 'customer_group_id' => null, 'priceable_type' => $priceable->getMorphClass(), 'priceable_id' => $priceable->id, ]); ``` For full details on price formatting, see the [Pricing Reference](/1.x/reference/pricing). > [!TIP] > > The same formatting methods apply to the `compare_price` attribute. ### Base Pricing Pricing is defined at the variant level, meaning each variant has its own price for each currency. Prices can be created directly or through the relationship: ```php theme={null} use Lunar\Models\ProductVariant; use Lunar\Models\Price; $priceable = ProductVariant::create([/* ... */]); Price::create([ 'price' => 199, 'compare_price' => 299, 'currency_id' => 1, 'min_quantity' => 1, 'customer_group_id' => null, 'priceable_type' => $priceable->getMorphClass(), 'priceable_id' => $priceable->id, ]); // Or via the relationship $variant->prices()->create([/* ... */]); ``` ### Customer Group Pricing Setting the `customer_group_id` column controls which customer group a price applies to. When left as `null`, the price applies to all customer groups. This allows different pricing and quantity breaks per customer group. ### Price Breaks Price breaks adjust the unit price based on purchase quantity. The `min_quantity` column determines when each price tier applies: ```php theme={null} use Lunar\Models\Price; Price::create([ // ... 'price' => 199, 'compare_price' => 399, 'min_quantity' => 1, ]); Price::create([ // ... 'price' => 150, 'compare_price' => 399, 'min_quantity' => 10, ]); ``` In the above example, ordering 1–9 items costs 1.99 per item, while ordering 10 or more costs 1.50 per item. ### Fetching Prices The `PricingManager` facade provides a fluent API for retrieving the correct price based on various criteria. #### Minimum example A quantity of 1 is implied when not passed. ```php theme={null} $pricing = \Lunar\Facades\Pricing::for($variant)->get(); ``` #### With quantities ```php theme={null} $pricing = \Lunar\Facades\Pricing::qty(5)->for($variant)->get(); ``` #### With customer groups If no customer group is passed, Lunar uses the default group and includes pricing that is not specific to any group. ```php theme={null} $pricing = \Lunar\Facades\Pricing::customerGroups($groups)->for($variant)->get(); // Or a single customer group $pricing = \Lunar\Facades\Pricing::customerGroup($group)->for($variant)->get(); ``` #### For a specific user The `PricingManager` assumes the current authenticated user by default. ```php theme={null} // Always return the guest price $pricing = \Lunar\Facades\Pricing::guest()->for($variant)->get(); // Specify a different user $pricing = \Lunar\Facades\Pricing::user($user)->for($variant)->get(); ``` #### With a specific currency If no currency is passed, the default currency is used. ```php theme={null} $pricing = \Lunar\Facades\Pricing::currency($currency)->for($variant)->get(); ``` #### From a model Any model using the `HasPrices` trait (such as `ProductVariant`) exposes a `pricing()` method: ```php theme={null} $pricing = $variant->pricing()->qty(5)->get(); ``` > [!WARNING] > > Fetching a price for a currency that has no pricing defined will throw a `Lunar\Exceptions\MissingCurrencyPriceException`. *** The `get()` method returns a `PricingResponse` object. Unless noted as a collection, each property returns a `Lunar\Models\Price` object. ```php theme={null} // The price that matched the given criteria $pricing->matched; // The base price associated with the variant $pricing->base; // A collection of all price quantity breaks for the given criteria $pricing->priceBreaks; // All customer group pricing for the given criteria $pricing->customerGroupPrices; ``` To retrieve all prices across a product's variants without loading the variants individually, use the `prices` relationship on the product: ```php theme={null} $product->prices; ``` ### Storing Prices Inclusive of Tax Lunar supports storing pricing inclusive of tax, which is useful for charm pricing (e.g. \$9.99) that may not be achievable when storing prices exclusive of tax due to rounding. To enable this, set the `stored_inclusive_of_tax` config value in `lunar/pricing` to `true` and ensure the default tax zone is configured with the correct tax rates. The cart will then automatically calculate tax correctly. To display both tax-inclusive and tax-exclusive prices on product pages: ```php theme={null} $price->priceIncTax(); $price->priceExTax(); $price->comparePriceIncTax(); ``` ### Customizing Prices with Pipelines Pricing pipelines are defined in `config/lunar/pricing.php`: ```php theme={null} 'pipelines' => [ // ], ``` Custom pipelines can modify pricing during resolution: ```php theme={null} pricing->matched; $matchedPrice->price->value = 200; $pricingManager->pricing->matched = $matchedPrice; return $next($pricingManager); } } ``` ```php theme={null} 'pipelines' => [ // ... App\Pipelines\Pricing\CustomPricingPipeline::class, ], ``` > [!TIP] > > Pipelines run from top to bottom. ## Full Example This example walks through creating a pair of Dr. Martens boots with multiple size and color variants.  The steps involved are: * Create the product type * Create the initial product * Create product options and their values * Create the variants ### Set up the product type ```php theme={null} use Lunar\Models\ProductType; $productType = ProductType::create([ 'name' => 'Boots', ]); ``` > [!NOTE] > > This example assumes attributes for name and description already exist and are assigned to the product type. ### Create the initial product ```php theme={null} use Lunar\Models\Product; use Lunar\FieldTypes\Text; use Lunar\FieldTypes\TranslatedText; $product = Product::create([ 'product_type_id' => $productType->id, 'status' => 'published', 'brand_id' => $brandId, 'attribute_data' => [ 'name' => new TranslatedText(collect([ 'en' => new Text('1460 PATENT LEATHER BOOTS'), ])), 'description' => new Text('Even more shades from the archive...'), ], ]); ``` ### Create product options Based on the example above, two options are needed: Size and Color. ```php theme={null} use Lunar\Models\ProductOption; $color = ProductOption::create([ 'name' => [ 'en' => 'Color', ], 'label' => [ 'en' => 'Color', ], ]); $size = ProductOption::create([ 'name' => [ 'en' => 'Size', ], 'label' => [ 'en' => 'Size', ], ]); ``` ### Create product option values ```php theme={null} $color->values()->createMany([ [ 'name' => [ 'en' => 'Black', ], ], [ 'name' => [ 'en' => 'White', ], ], [ 'name' => [ 'en' => 'Pale Pink', ], ], [ 'name' => [ 'en' => 'Mid Blue', ], ], ]); $size->values()->createMany([ [ 'name' => [ 'en' => '3', ], ], [ 'name' => [ 'en' => '6', ], ], ]); ``` ### Create the variants With the options and values defined, variants can be created for each combination. Each variant needs a product, tax class, SKU, and at least one price. ```php theme={null} use Lunar\Models\ProductVariant; use Lunar\Models\TaxClass; use Lunar\Models\Currency; $taxClass = TaxClass::first(); $currency = Currency::first(); $count = 0; foreach ($color->values as $colorValue) { foreach ($size->values as $sizeValue) { $count++; $variant = ProductVariant::create([ 'product_id' => $product->id, 'tax_class_id' => $taxClass->id, 'sku' => "DRBOOT-{$count}", ]); $variant->values()->attach([$colorValue->id, $sizeValue->id]); $variant->prices()->create([ 'price' => 16900, 'currency_id' => $currency->id, ]); } } ``` The resulting variants: | SKU | Color | Size | | :- | :- | :- | | DRBOOT-1 | Black | 3 | | DRBOOT-2 | Black | 6 | | DRBOOT-3 | White | 3 | | DRBOOT-4 | White | 6 | | DRBOOT-5 | Pale Pink | 3 | | DRBOOT-6 | Pale Pink | 6 | | DRBOOT-7 | Mid Blue | 3 | | DRBOOT-8 | Mid Blue | 6 | SKUs, pricing, and other variant details can be adjusted as needed before publishing. # Search Source: https://docs.lunarphp.com/1.x/reference/search Configure and manage search indexing with Laravel Scout, including searchable models, indexers, engine mapping, and artisan commands. Lunar provides search indexing and querying through Laravel Scout with support for multiple search engines. ## Overview Search in Lunar is built on [Laravel Scout](https://laravel.com/docs/scout), providing a flexible, driver-based search system. Scout's database driver offers basic search out of the box, while more powerful engines like [Meilisearch](https://www.meilisearch.com/) and [Typesense](https://typesense.org/) can be swapped in for advanced features such as faceted filtering and relevance tuning. All search configuration lives in `config/lunar/search.php`. This file controls which models are indexed, which search engine each model uses, and which indexer class prepares the data for each model. > [!TIP] > > For building storefront search with faceted filtering, sorting, and structured results, see the [Storefront Search add-on](/1.x/addons/search). It provides a `Search` facade with a consistent API across all search engines. ## Configuration ### Soft Deletes By default, Scout sets the `soft_delete` option to `false`. This must be set to `true` in `config/scout.php`, otherwise soft-deleted models will appear in search results. ```php theme={null} // config/scout.php 'soft_delete' => true, ``` ### Searchable Models The `models` array in `config/lunar/search.php` defines which models are indexed. Lunar registers the following models by default: ```php theme={null} 'models' => [ // These models are required by the system, do not change them. Lunar\Models\Brand::class, Lunar\Models\Collection::class, Lunar\Models\Customer::class, Lunar\Models\Order::class, Lunar\Models\Product::class, Lunar\Models\ProductOption::class, // Below you can add your own models for indexing... // App\Models\Example::class, ], ``` To add custom models to the search index, append them to this array. Custom models must use the `Lunar\Base\Traits\Searchable` trait. ### Engine Mapping By default, Scout uses the driver defined by the `SCOUT_DRIVER` environment variable for all models. This means if `SCOUT_DRIVER` is set to `meilisearch`, every searchable model gets indexed via Meilisearch. This may not always be desirable. For example, indexing orders in a paid service like Algolia alongside products would unnecessarily increase record counts and cost. Lunar allows specifying a different driver per model using the `engine_map` configuration: ```php theme={null} 'engine_map' => [ Lunar\Models\Product::class => 'typesense', Lunar\Models\Order::class => 'meilisearch', Lunar\Models\Collection::class => 'meilisearch', ], ``` Any model not listed in the `engine_map` falls back to the default Scout driver. ## Searchable Trait All searchable Lunar models use the `Lunar\Base\Traits\Searchable` trait. This trait extends Scout's `Searchable` trait and delegates key behavior to an indexer class: * `searchableAs()` — returns the index name * `toSearchableArray()` — returns the data to index * `shouldBeSearchable()` — determines whether the model should be indexed * `searchableUsing()` — returns the engine based on the `engine_map` configuration * `getFilterableAttributes()` — returns filterable fields for the engine * `getSortableAttributes()` — returns sortable fields for the engine The trait resolves the appropriate indexer from the `indexers` config, falling back to the base `Lunar\Search\ScoutIndexer` if no specific indexer is mapped. ## Indexers Each searchable model is paired with an indexer class that controls what data is sent to the search engine. The `indexers` config maps models to their indexer: ```php theme={null} 'indexers' => [ Lunar\Models\Brand::class => Lunar\Search\BrandIndexer::class, Lunar\Models\Collection::class => Lunar\Search\CollectionIndexer::class, Lunar\Models\Customer::class => Lunar\Search\CustomerIndexer::class, Lunar\Models\Order::class => Lunar\Search\OrderIndexer::class, Lunar\Models\Product::class => Lunar\Search\ProductIndexer::class, Lunar\Models\ProductOption::class => Lunar\Search\ProductOptionIndexer::class, ], ``` ### Default Indexer The base `Lunar\Search\ScoutIndexer` class indexes: * The model's `id` * Any attributes marked as `searchable` It also handles `TranslatedText` attribute fields, creating locale-suffixed entries (e.g., `name_en`, `name_fr`) in the index. ### Product Indexer The `Lunar\Search\ProductIndexer` indexes the following fields: | Field | Source | | :- | :- | | `id` | Product ID | | `status` | Product status | | `product_type` | Product type name | | `brand` | Brand name (if present) | | `created_at` | Unix timestamp | | `thumbnail` | Thumbnail URL (small variant) | | `skus` | Array of variant SKUs | | Attribute handles | Values from searchable attributes | **Sortable fields:** `created_at`, `updated_at`, `skus`, `status` **Filterable fields:** `__soft_deleted`, `skus`, `status` ### Order Indexer The `Lunar\Search\OrderIndexer` indexes the following fields: | Field | Source | | :- | :- | | `id` | Order ID | | `channel` | Channel name | | `reference` | Order reference | | `customer_reference` | Customer reference | | `status` | Order status | | `placed_at` | Placement timestamp | | `created_at` | Unix timestamp | | `sub_total` | Sub-total value | | `total` | Total value | | `currency_code` | Currency code | | `charges` | Transaction references | | `lines` | Product line descriptions and identifiers | | `{type}_first_name`, `{type}_last_name`, etc. | Address fields prefixed by type (shipping/billing) | | `tags` | Array of tag values | **Sortable fields:** `customer_id`, `user_id`, `channel_id`, `created_at`, `updated_at`, `total` **Filterable fields:** `customer_id`, `user_id`, `status`, `placed_at`, `channel_id`, `tags`, `__soft_deleted` ### Customer Indexer The `Lunar\Search\CustomerIndexer` indexes the following fields: | Field | Source | | :- | :- | | `id` | Customer ID | | `name` | Full name | | `company_name` | Company name | | `tax_identifier` | Tax identifier | | `account_ref` | Account reference | | `created_at` | Unix timestamp | | `user_emails` | Array of associated user emails | | Meta fields | Any meta key-value pairs | | Attribute handles | Values from searchable attributes | **Sortable fields:** `created_at`, `updated_at`, `name`, `company_name` **Filterable fields:** `__soft_deleted`, `name`, `company_name` ### Brand Indexer The `Lunar\Search\BrandIndexer` indexes the following fields: | Field | Source | | :- | :- | | `id` | Brand ID | | `name` | Brand name | | `created_at` | Unix timestamp | | Attribute handles | Values from searchable attributes | **Sortable fields:** `created_at`, `updated_at`, `name` **Filterable fields:** `__soft_deleted`, `name` ### Collection Indexer The `Lunar\Search\CollectionIndexer` indexes the following fields: | Field | Source | | :- | :- | | `id` | Collection ID | | `created_at` | Unix timestamp | | Attribute handles | Values from searchable attributes | **Sortable fields:** `created_at`, `updated_at`, `name` **Filterable fields:** `__soft_deleted`, `name` ### ProductOption Indexer The `Lunar\Search\ProductOptionIndexer` indexes the following fields: | Field | Source | | :- | :- | | `id` | ProductOption ID | | `name_{locale}` | Option name per locale | | `label_{locale}` | Option label per locale | | `option_{id}_{locale}` | Option value names per locale | **Sortable fields:** `created_at`, `updated_at` **Filterable fields:** `__soft_deleted` ## Indexing Records To import or refresh search indexes, use the `lunar:search:index` artisan command: ```sh theme={null} php artisan lunar:search:index ``` This imports all models listed in the `models` configuration. ### Command Options | Option | Description | | :- | :- | | `models` | One or more model class names to index (space-separated). Merged with config models by default. | | `--ignore` | Only index the models specified in the command, ignoring the config file. | | `--refresh` | Delete existing records from the index before reimporting. | | `--flush` | Delete records from the index without reimporting. Cannot be combined with `--refresh`. | ```sh theme={null} # Refresh only the product index php artisan lunar:search:index "Lunar\Models\Product" --refresh # Flush the order index php artisan lunar:search:index "Lunar\Models\Order" --flush # Index only specific models, ignoring config php artisan lunar:search:index "Lunar\Models\Product" "Lunar\Models\Brand" --ignore ``` ## Meilisearch Setup When using Meilisearch, run the setup command to configure filterable and sortable attributes on Meilisearch indexes: ```sh theme={null} php artisan lunar:meilisearch:setup ``` This command reads the filterable and sortable fields from each model's indexer and applies them to the corresponding Meilisearch index. ## Storefront Search Add-on For storefront search features such as faceted filtering, sorting, pagination, and structured response data, install the [Storefront Search add-on](/1.x/addons/search): ```sh theme={null} composer require lunarphp/search ``` The add-on provides a `Search` facade with support for Meilisearch, Typesense, and database drivers, returning consistent `SearchResults` objects with hits, facets, and pagination. ## Extending Search To customize what data is indexed for a model, create a custom indexer class. See the [Extending Search](/1.x/extending/search) guide for details on creating custom indexers, adding sortable and filterable fields, and mapping searchable attributes. # Tags Source: https://docs.lunarphp.com/1.x/reference/tags Tags provide a way to relate otherwise unrelated models, enabling features like dynamic collections. ## Overview Tags provide a way to relate otherwise unrelated models in the system. They also impact other features such as Dynamic Collections. For example, two products "Blue T-Shirt" and "Blue Shoes" are unrelated by nature, but adding a `BLUE` tag to each product allows a Dynamic Collection to include any products with that tag. ```php theme={null} Lunar\Models\Tag ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `value` | `string` | The tag value | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | > [!TIP] > > Tags are automatically converted to uppercase when saved via the `syncTags` method. ## Enabling tags To enable tagging on a model, add the `HasTags` trait: ```php theme={null} 'TAG ONE']), Tag::firstOrCreate(['value' => 'TAG TWO']), Tag::firstOrCreate(['value' => 'TAG THREE']), ]); $model = SomethingWithTags::first(); $model->syncTags($tags); ``` The `syncTags` method accepts a collection of `Tag` models. Tags are automatically converted to uppercase when saved. The sync process runs via a queued job (`Lunar\Jobs\SyncTags`), so changes may not be reflected immediately if using an asynchronous queue driver. # Taxation Source: https://docs.lunarphp.com/1.x/reference/taxation Lunar provides configurable tax rules for calculating sales tax on orders. ## Overview Lunar provides manual tax rules to implement the correct sales tax for each order. For complex taxation scenarios (e.g. US states), integrating with a service such as [TaxJar](https://www.taxjar.com/) is recommended. ## Tax Classes Tax Classes are assigned to products and allow classification into taxable groups that may have differing tax rates. ```php theme={null} Lunar\Models\TaxClass ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `name` | `string` | e.g. `Clothing` | | `default` | `boolean` | Whether this is the default tax class | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ```php theme={null} use Lunar\Models\TaxClass; $taxClass = TaxClass::create([ 'name' => 'Clothing', ]); ``` ## Tax Zones Tax Zones specify a geographic zone for tax rates to be applied. They can be based on countries, states, or zip/postcodes. ```php theme={null} Lunar\Models\TaxZone ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `name` | `string` | e.g. `UK` | | `zone_type` | `string` | `country`, `states`, or `postcodes` | | `price_display` | `string` | `tax_inclusive` or `tax_exclusive` | | `active` | `boolean` | Whether the zone is active | | `default` | `boolean` | Whether the zone is the default | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ```php theme={null} use Lunar\Models\TaxZone; $taxZone = TaxZone::create([ 'name' => 'UK', 'zone_type' => 'country', 'price_display' => 'tax_inclusive', 'active' => true, 'default' => true, ]); ``` ### Tax Zone Countries ```php theme={null} Lunar\Models\TaxZoneCountry ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `tax_zone_id` | `foreignId` `nullable` | | | `country_id` | `foreignId` `nullable` | | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ```php theme={null} $taxZone->countries()->create([ 'country_id' => \Lunar\Models\Country::first()->id, ]); ``` ### Tax Zone States ```php theme={null} Lunar\Models\TaxZoneState ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `tax_zone_id` | `foreignId` `nullable` | | | `state_id` | `foreignId` `nullable` | | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ```php theme={null} $taxZone->states()->create([ 'state_id' => \Lunar\Models\State::first()->id, ]); ``` > [!NOTE] > > State lookups are scoped to the address country, so a state zone only applies to addresses in that state's own country. This matters because state codes are reused across countries: `WA` is both Washington and Western Australia. Scoping was added in Lunar 1.5; earlier versions matched a state zone against any country. ### Tax Zone Postcodes ```php theme={null} Lunar\Models\TaxZonePostcode ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `tax_zone_id` | `foreignId` `nullable` | | | `country_id` | `foreignId` `nullable` | | | `postcode` | `string` | Supports wildcards, e.g. `9021*` | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Tax Zone Customer Groups ```php theme={null} Lunar\Models\TaxZoneCustomerGroup ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `tax_zone_id` | `foreignId` `nullable` | | | `customer_group_id` | `foreignId` `nullable` | | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Zone resolution `Lunar\Actions\Taxes\GetTaxZone` resolves the tax zone for an address, checking each type of zone in turn and returning the first match: 1. **Postcode** — matched against the address postcode, honoring wildcards. 2. **State** — matched against the address state, scoped to the address country. 3. **Country** — matched against the address country. 4. **Default** — the tax zone flagged as the default, returned when nothing above matches. ```php theme={null} use Lunar\Actions\Taxes\GetTaxZone; $taxZone = app(GetTaxZone::class)->execute($address); ``` Passing no address (or an address with none of these fields set) returns the default tax zone. A cart can also override this resolution entirely, see [Carts → Setting the Tax Zone](/1.x/reference/carts#setting-the-tax-zone). ## Tax Rates Tax Zones have one or many tax rates. For example, a zone might have a tax rate for the state and also the city, which collectively make up the total tax amount. ```php theme={null} Lunar\Models\TaxRate ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `tax_zone_id` | `foreignId` `nullable` | | | `priority` | `tinyInteger` | The priority order for this rate (default `1`) | | `name` | `string` | e.g. `UK` | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Tax Rate Amounts ```php theme={null} Lunar\Models\TaxRateAmount ``` | Field | Type | Description | | :- | :- | :- | | `id` | `id` | Primary key | | `tax_class_id` | `foreignId` `nullable` | | | `tax_rate_id` | `foreignId` `nullable` | | | `percentage` | `decimal(7,3)` | e.g. `6` for 6% | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ## Settings * Shipping and other specific costs are assigned to tax classes in the settings. * Tax calculation can be based on the shipping or billing address. * A default Tax Zone can be configured. ## Extending Sometimes the standard tax calculations are not sufficient, and custom logic may be needed, perhaps connecting to a tax service such as TaxJar. Lunar allows custom tax drivers to be implemented. See the [Extending Taxation](/1.x/extending/taxation) section for more information. # URLs Source: https://docs.lunarphp.com/1.x/reference/urls Create SEO-friendly slugs for products, collections, brands, and custom models. URLs provide SEO-friendly slugs for models such as products, collections, and brands. ## Overview URLs provide SEO-friendly slugs for models such as products, collections, and brands. Instead of exposing database IDs in storefront routes: ``` /products/1 ``` A URL slug allows routes like: ``` /products/apple-iphone ``` URLs are polymorphic, so any Eloquent model can support them. Each URL belongs to a language, and each model can have one default URL per language. > [!NOTE] > > URLs are not to be confused with Laravel routes. They provide a slug-based lookup mechanism for storefront routing, not route definitions. ## Model ```php theme={null} Lunar\Models\Url ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `id` | `bigIncrements` | Primary key | | `language_id` | `foreignId` | The language this URL belongs to | | `element_type` | `string` | Morph type of the parent model | | `element_id` | `unsignedBigInteger` | Morph ID of the parent model | | `slug` | `string` | The URL slug | | `default` | `boolean` | Whether this is the default URL for this element and language combination | | `created_at` | `timestamp` | | | `updated_at` | `timestamp` | | ### Relationships | Relationship | Type | Related Model | Description | | :- | :- | :- | :- | | `element` | MorphTo | Polymorphic | The parent model (e.g. Product, Collection, Brand) | | `language` | BelongsTo | `Lunar\Models\Language` | The language this URL is for | ### Scopes | Scope | Description | | :- | :- | | `default()` | Filter to URLs where `default` is `true` | ## Creating a URL URLs can be created directly or through a model's `urls()` relationship. ```php theme={null} use Lunar\Models\Url; Url::create([ 'slug' => 'apple-iphone', 'language_id' => $language->id, 'element_type' => $product->getMorphClass(), 'element_id' => $product->id, 'default' => true, ]); // Or through the relationship $product->urls()->create([ 'slug' => 'apple-iphone', 'language_id' => $language->id, 'default' => true, ]); ``` ### Default URL behavior Only one URL can be the default per element and language combination. When a new URL is created or updated with `default` set to `true`, any existing default URL for that same element and language is automatically set to `false`. ```php theme={null} $urlA = $product->urls()->create([ 'slug' => 'apple-iphone', 'language_id' => 1, 'default' => true, ]); $urlA->default; // true $urlB = $product->urls()->create([ 'slug' => 'apple-iphone-16', 'language_id' => 1, 'default' => true, ]); $urlA->refresh()->default; // false $urlB->default; // true ``` This behavior is scoped to each language independently. Setting a default for one language does not affect defaults in another language. ```php theme={null} // This URL is for a different language, so $urlB remains the default for language 1 $urlC = $product->urls()->create([ 'slug' => 'apple-iphone-fr', 'language_id' => 2, 'default' => true, ]); $urlB->refresh()->default; // true (still default for language 1) $urlC->default; // true (default for language 2) ``` ## Deleting a URL When a default URL is deleted, Lunar automatically promotes another URL for the same element and language to become the new default. ```php theme={null} $urlA = $product->urls()->create([ 'slug' => 'apple-iphone', 'language_id' => 1, 'default' => true, ]); $urlB = $product->urls()->create([ 'slug' => 'apple-iphone-16', 'language_id' => 1, 'default' => false, ]); $urlA->delete(); $urlB->refresh()->default; // true ``` ## Adding URL support to models Lunar ships with URL support on the following models: * `Lunar\Models\Product` * `Lunar\Models\Collection` * `Lunar\Models\Brand` To add URL support to a custom model, use the `HasUrls` trait: ```php theme={null} urls; // The default URL (where default is true) $model->defaultUrl; // The URL for the application's current locale $model->localeUrl; // The URL for a specific locale (matches against the language code) $model->localeUrl('fr')->first(); ``` > [!NOTE] > > When a model using the `HasUrls` trait is deleted (hard delete only), all associated URLs are automatically removed. ## Automatic URL generation Lunar can automatically generate a URL when a model with the `HasUrls` trait is created. This is controlled by the `generator` option in `config/lunar/urls.php`. ```php theme={null} true, 'generator' => UrlGenerator::class, ]; ``` | Option | Type | Default | Description | | :- | :- | :- | :- | | `required` | `bool` | `true` | Whether URLs are required when creating or editing models in the admin panel. Has no effect if a generator is configured. | | `generator` | `string\|null` | `UrlGenerator::class` | The class responsible for generating URLs on model creation. Set to `null` to disable automatic generation. | ### Default generator behavior The built-in `Lunar\Generators\UrlGenerator` performs the following steps when a model is created: 1. Checks whether the model already has any URLs (skips generation if it does). 2. Reads the model's `name` column, falling back to the `name` attribute (via `attr('name')`). 3. Converts the name to a slug using `Str::slug()`. 4. Ensures uniqueness by appending a numeric suffix if the slug already exists (e.g. `test-product`, `test-product-2`, `test-product-3`). 5. Creates the URL as the default for the system's default language. ### Custom generator To customize URL generation, create a class with a `handle` method that accepts an Eloquent model: ```php theme={null} true, 'generator' => \App\Generators\CustomUrlGenerator::class, ]; ``` To disable automatic generation entirely, set the generator to `null`: ```php theme={null} return [ 'required' => true, 'generator' => null, ]; ``` # Storefront Session Source: https://docs.lunarphp.com/1.x/storefront-utils/storefront-session The StorefrontSession facade manages session-bound resources like the active channel, currency, and customer. ## Overview The `StorefrontSession` facade helps manage session-bound resources that a storefront typically needs, such as the active channel, currency, customer, and customer groups. ```php theme={null} use Lunar\Facades\StorefrontSession; ``` When the facade is first resolved, it automatically calls `initChannel()`, `initCustomerGroups()`, `initCurrency()`, and `initCustomer()` to restore any previously set values from the session or fall back to defaults. ## Channels ### Initialize the Channel This will set the channel based on what has been previously stored in the session, otherwise it will use the default channel. ```php theme={null} StorefrontSession::initChannel(); ``` > [!NOTE] > > This is automatically called when the facade is resolved. ### Set the Channel ```php theme={null} use Lunar\Models\Channel; $channel = Channel::where('handle', 'webstore')->first(); StorefrontSession::setChannel($channel); ``` The `setChannel` method accepts a `Channel` model instance. The channel's handle is stored in the session so it can be restored on subsequent requests. ### Get the Channel Returns the currently active `Channel` model. ```php theme={null} StorefrontSession::getChannel(); ``` ## Customer Groups ### Initialize the Customer Groups This will set the customer groups based on what has been previously stored in the session, otherwise it will use the default customer group. ```php theme={null} StorefrontSession::initCustomerGroups(); ``` > [!NOTE] > > This is automatically called when the facade is resolved. ### Set the Customer Groups ```php theme={null} use Lunar\Models\CustomerGroup; $retail = CustomerGroup::where('handle', 'retail')->first(); $wholesale = CustomerGroup::where('handle', 'wholesale')->first(); // Set multiple customer groups StorefrontSession::setCustomerGroups(collect([$retail, $wholesale])); // Set a single customer group (calls setCustomerGroups under the hood) StorefrontSession::setCustomerGroup($retail); ``` ### Get the Customer Groups Returns a `Collection` of `CustomerGroup` models. ```php theme={null} StorefrontSession::getCustomerGroups(); ``` ### Reset the Customer Groups Clears the customer groups from the session and resets the collection to empty. ```php theme={null} StorefrontSession::resetCustomerGroups(); ``` ## Customer ### Initialize the Customer This will set the customer based on what has been previously stored in the session, otherwise it will retrieve the latest customer associated with the authenticated user. ```php theme={null} StorefrontSession::initCustomer(); ``` > [!NOTE] > > This is automatically called when the facade is resolved. ### Set the Customer ```php theme={null} use Lunar\Models\Customer; $customer = Customer::find($customerId); StorefrontSession::setCustomer($customer); ``` > [!WARNING] > > If a user is authenticated and the given customer does not belong to that user, a `Lunar\Exceptions\CustomerNotBelongsToUserException` will be thrown. ### Get the Customer Returns the currently active `Customer` model, or `null` if no customer has been set. ```php theme={null} StorefrontSession::getCustomer(); ``` ## Currencies ### Initialize the Currency This will set the currency based on what has been previously stored in the session, otherwise it will use the default currency. ```php theme={null} StorefrontSession::initCurrency(); ``` > [!NOTE] > > This is automatically called when the facade is resolved. ### Set the Currency ```php theme={null} use Lunar\Models\Currency; $currency = Currency::where('code', 'USD')->first(); StorefrontSession::setCurrency($currency); ``` The `setCurrency` method accepts a `Currency` model instance. The currency code is stored in the session so it can be restored on subsequent requests. ### Get the Currency Returns the currently active `Currency` model. ```php theme={null} StorefrontSession::getCurrency(); ``` ## Clearing the Session To remove all storefront session data (channel, currency, customer, and customer groups), call the `forget` method. ```php theme={null} StorefrontSession::forget(); ``` This clears the stored values from the session but does not delete any database records. # Welcome to the New Lunar Docs Source: https://docs.lunarphp.com/logs/2025/new-docs We’ve rebuilt the Lunar documentation from the ground up. The mission was simple: make it faster to find what you need, clearer to understand, and easier to explore. The new docs are powered by [Mintlify](https://www.mintlify.com/), giving you a faster interface, improved search, and smooth navigation whether you’re on desktop or mobile. You’ll notice a cleaner structure around the core concepts — getting started, configuration, extending Lunar — all organized to match how developers actually build. This launch isn’t just a redesign — it’s the foundation for the next chapter. As we approach Lunar v2, expect deeper guides, architectural overviews, and examples from live production sites. Our goal is to make Lunar not only powerful, but deeply understandable. If you spot something missing or unclear, open an issue or suggest an edit — collaboration keeps this mission on course. Welcome aboard the new Lunar docs. # Lunar 1.4.0 Source: https://docs.lunarphp.com/logs/2026/v1-4-0 Stable release on the Filament v3 line, adding a shipping management permission and fixing product variant handling in the admin panel. Lunar 1.4.0 is now available. This stable release adds permission enforcement for the Table Rate Shipping add-on and fixes two related product variant bugs in the admin panel. > [!NOTE] > > Lunar 1.4 is the latest stable release supporting Filament v3. Lunar 1.5, currently in beta, upgrades the admin panel to Filament v4. Projects that need to remain on Filament v3 should stay on the 1.4 release line. ## `shipping:manage` permission The Table Rate Shipping add-on now registers and enforces a `shipping:manage` permission on the Shipping Methods, Shipping Zones, and Shipping Exclusion Lists resources in the admin panel. A migration creates the permission automatically; staff members who previously had unrestricted access need to be assigned the new permission (or a role that includes it) to continue managing shipping. See [Table Rate Shipping](/1.x/addons/table-rate-shipping) for details. ## Product variant fixes Two related bugs in the admin panel's product options handling are fixed: * Products with a sparse option matrix (for example, Size and Color combinations that do not all have a variant) no longer show the first variant's SKU under the wrong option labels. * Newly added option permutations now save correctly. The new variant copies its tax class and pricing deterministically from the oldest sibling variant, instead of failing because no tax class was set. ## Upgrading ```sh theme={null} composer update lunarphp/lunar php artisan migrate php artisan optimize:clear ``` The migration in this release creates the `shipping:manage` permission for the Table Rate Shipping add-on. After migrating, assign the permission to any staff members or roles that manage shipping. See the [1.4 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#14). [View the full release on GitHub](https://github.com/lunarphp/lunar/releases/tag/1.4.0). # Lunar 1.5.0 Source: https://docs.lunarphp.com/logs/2026/v1-5-0 Stable release of the 1.5 cycle, bringing Filament v4, Laravel 13 and PHP 8.3 support, a Lunar-maintained nested set package, and a broad round of discount, shipping, tax, and payment fixes. Lunar 1.5.0 is now available. This is the stable release of the 1.5 cycle, closing out the work that shipped across six betas: a Filament v4 admin panel, Laravel 13 and PHP 8.3 support, and a wide round of new capabilities and fixes across discounts, shipping, tax, and payments. > [!WARNING] > > **Filament v4 only.** Lunar 1.5 upgrades the admin panel to Filament v4 and drops support for Filament v3. Projects that need to stay on Filament v3 should remain on the [1.4 release line](/logs/2026/v1-4-0), which is the final Lunar version built on Filament v3. ## Framework support Lunar 1.5 requires PHP 8.3 or later and Laravel 12 or 13. PHP 8.2 and Laravel 11 have reached end of life and are no longer supported. The admin panel is built on Filament v4. Projects with custom Filament resources, pages, widgets, or actions need to follow the [Filament v4 upgrade guide](https://filamentphp.com/docs/4.x/upgrade-guide) alongside the Lunar upgrade. The `lunarphp/filament3-2fa` package is no longer required, as Filament v4 provides its own multi-factor authentication primitives. See the [installation requirements](/1.x/getting-started/setup/installation) for the full list. ## High impact changes ### Nested set package replaced Collections build their tree using a nested set implementation, and Lunar now ships its own maintained fork. `kalnoy/nestedset` is replaced by [`lunarphp/nestedset`](https://github.com/lunarphp/nestedset), kept current for Laravel 12 and 13. The API is unchanged, so tree queries continue to work as before, but the namespaces have moved from `Kalnoy\Nestedset` to `Lunar\Nestedset`. Application code that imports `NodeTrait`, `QueryBuilder`, or `NestedSetServiceProvider` directly needs updating. See [Collections](/1.x/reference/collections#nested-collections). ### Order line purchasable morph is now nullable Shipping order lines previously stored a placeholder morph pointing at `Lunar\DataTypes\ShippingOption`, a data transfer object rather than a model. Reading `$orderLine->purchasable` on a shipping line, or eager loading `lines.purchasable` across an order, raised a fatal error as a result. The `purchasable_type` and `purchasable_id` columns on `order_lines` are now nullable, and shipping lines are stored with no morph at all. A migration nulls the placeholder on existing shipping lines, scoped to that exact class so custom morphs are left untouched. `$orderLine->purchasable` now returns `null` for shipping lines instead of failing, so storefront code iterating `$order->lines` should guard for `null` or iterate `$order->productLines` instead. ### Discount conditions honored by BuyXGetY `Lunar\DiscountTypes\BuyXGetY` never checked the discount's own conditions, so minimum spend, customer restrictions, and `max_uses_per_user` were all ignored and only `min_qty` gated the reward. These are now enforced, matching `AmountOff`. Live BuyXGetY discounts configured with a minimum spend or customer restriction will start applying it, so review them before upgrading to confirm they reflect what the store intends to offer. ### Stripe amount conversion `StripeManager` passed the stored cart total straight through to Stripe for all but three currency codes, assuming the currency's configured `decimal_places` matched the sub-unit Stripe expects. A currency configured with four decimal places was overcharged by a factor of 100. Amounts are now converted back to the major unit using the currency's `decimal_places`, then re-scaled to the sub-unit Stripe requires for that currency code. Stores using a currency whose `decimal_places` is not `2` should verify the amounts sent to Stripe after upgrading. See [Stripe](/1.x/addons/payments/stripe#amount-conversion). ## Discounts A focused round of work on discount correctness: * Coupon codes now apply immediately on stores that also have an always-on discount. The memoized discount set was reused across carts within a request, which excluded coupon discounts and left the total unchanged until the page was reloaded. * Re-creating a draft order for the same cart no longer consumes another use of its discounts. A card decline followed by a retry previously exhausted the coupon and re-priced the same order without it. Carts now track their own consumed discounts through `consumedDiscountIds()`. * `BuyXGetY` supports a specific product variant as an automatically added reward. This previously raised a fatal error during cart calculation, taking down the basket rather than just checkout. * A multi-quantity `BuyXGetY` reward is added as one line with that quantity, rather than one line per item. * Automatically added reward lines are stored using Lunar's morph map, so their `purchasable_type` matches every other line holding the same purchasable. * Automatic rewards only select items that can be fulfilled, so an out-of-stock reward is skipped rather than raising an error. * Collection breadcrumbs are shown in the admin panel's discount selection lists, making collections with the same name distinguishable. * Discount usage lookups are memoized per cart instance, cutting repeated draft-order queries on every calculate. ## Carts and orders * Switching the session currency now reprices the cart. `CartSession::setCurrency()` updated the cart's `currency_id` but left the loaded relationships in place, so the next calculate priced every line in the previous currency. See [Carts](/1.x/reference/carts#setting-the-currency). * Shipping modifiers can safely calculate the cart. A modifier that did so previously re-entered the modifier pipeline and exhausted the stack, which surfaced only once a shipping address with a selected option was present. * Order creation no longer duplicates addresses of the same type. Existing addresses are matched on type alone, so rebuilding a draft order with a changed address updates it in place. * `Cart::lines()` and `Order::lines()` order by `id`, and `ProductVariant::values()` orders by `position`. These relationships previously left row order to the database engine, which is stable on MySQL but not on PostgreSQL, where it could change a cart's fingerprint after an unrelated update. * Order lines for digital products appear on the generated invoice PDF. The template iterated physical lines only, silently omitting non-shippable products and services. ## Tax * State tax zones are scoped to the address country. A state zone previously matched any address with a matching state code or name in any country, so a shopper in Western Australia could be charged Washington State sales tax. See [Taxation](/1.x/reference/taxation#zone-resolution). * `SystemTaxDriver` resolves the default tax zone through `TaxZone::getDefault()`, removing duplicate queries during cart calculation. ## Shipping * Weight tiers on the `ship-by` driver are evaluated in the shipping method's configured `weight_unit`, defaulting to `kg`. Each cart line's weight is converted from its own unit first, so a cart mixing grams and kilograms totals correctly. Methods that set a unit other than `kg` need their tier thresholds re-entered in that unit. See [Table Rate Shipping](/1.x/addons/table-rate-shipping#weight-tiers). * The admin tier form shows the configured unit and rejects decimal weight tiers, instead of silently truncating them. * Shipping Zone create and update no longer fail validation with "The selected countries is invalid" when limiting a zone to specific countries or states. * The Shipping permission is translated in the admin panel. ## Admin panel * A new `Lunar\Admin\Events\ProductVariantInventoryUpdated` event is dispatched when stock is saved on the product or variant inventory pages, bringing inventory changes in line with the panel's other resource events. See [Extending the Admin Panel](/1.x/admin/extending/overview#events). * Attribute `default_value` is exposed in the admin panel and applied when creating records. * Media custom properties are no longer dropped on create or edit. Keys contributed through a `RelationManagerExtension` are persisted, and keys the edit form does not render survive a save. * Customers can be deleted individually, rather than only through the bulk action. * Product option mapping no longer shows the first variant's SKU against unmatched option permutations, and newly added permutations save correctly, inheriting their tax class and pricing from the oldest sibling variant. * The Unit Quantity field on product variants enforces a minimum of `1`, preventing a division by zero when the item is added to a cart. * Boolean order metadata is displayed as Yes or No rather than a raw value. * Product variant widget labels are translated. * Whitespace is trimmed from panel form inputs. ## Developer experience * A [Laravel Boost](https://github.com/laravel/boost) skill ships with the core package, installable with `php artisan boost:add-skill lunarphp/lunar`. It orients an AI assistant in a Lunar project and points it at current documentation. See [AI Development](/1.x/getting-started/overview/ai-development#laravel-boost-skill). * Date parameters on the channel and customer group scoping and scheduling traits accept `DateTimeInterface`, so applications using `Date::use(CarbonImmutable::class)` no longer hit a `TypeError` during cart and discount calculation. * `HasDefaultRecord::getDefault()` is annotated as nullable, matching what it returns when no record is flagged as the default. * The `$formatterStyle` parameter on `DefaultPriceFormatter` is typed `int`, matching the `NumberFormatter` constants passed to it. * Route facade imports are fixed in the Opayo and PayPal route files. ## Upgrading ```sh theme={null} composer update lunarphp/lunar php artisan migrate php artisan optimize:clear ``` Upgrading from 1.4 or earlier involves breaking changes, including the Filament v3 to v4 migration. Follow the [1.5 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) in full, and test on a staging environment first. Upgrading from `1.5.0-beta.6` requires the migration in this release, which makes the order line purchasable morph nullable and clears the placeholder morph from existing shipping lines. ## Thanks This release includes contributions from @kha333n, @wakqasahmed, @ryanmitchell, @bpotmalnik, @Huncsuga, @wychoong, @xlvis7, @alecgarcia, @punyflash, @sgregor, @yazdanghalavand, @mathis-gp, and @glennjacobs. [View the full release on GitHub](https://github.com/lunarphp/lunar/releases/tag/1.5.0). # Lunar 1.5.0-beta.1 Source: https://docs.lunarphp.com/logs/2026/v1-5-0-beta-1 First beta of the 1.5 cycle, introducing Filament v4 for the admin panel and a new shipping management permission. The first beta of the 1.5 cycle is available. This release focuses on the admin panel and brings the underlying Filament framework up to its latest major version. > [!WARNING] > > This is a pre-release. Pin to `1.5.0-beta.1` in `composer.json` and review the [upgrade guide](/1.x/getting-started/overview/upgrade-guide) before installing on a production project. ## What's new ### Filament v4 The admin panel has been upgraded to Filament v4. The upgrade modernises the resource APIs the panel is built on and unlocks the latest Filament features for projects extending the panel. Projects with custom Filament resources, pages, or widgets will need to follow the [Filament v4 upgrade guide](https://filamentphp.com/docs/4.x/upgrade-guide) alongside the Lunar upgrade. The Lunar upgrade guide covers the framework-level changes that affect Lunar installations specifically. As part of this work, the two-factor authentication columns on the `staff` table have been renamed to align with Filament v4's multi-factor authentication primitives. A Lunar migration handles the rename automatically. ### `shipping:manage` permission The Table Rate Shipping add-on now enforces a dedicated `shipping:manage` permission on the Shipping Methods, Shipping Zones, and Shipping Exclusion Lists resources. The permission is created automatically by a migration. Staff who previously managed shipping need to be assigned the new permission (or a role that includes it) to retain access. See the [Table Rate Shipping](/1.x/addons/table-rate-shipping) page for details. ## Upgrading Follow the [1.5 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) for the full set of steps and breaking changes. ## Feedback Beta feedback is welcome through [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) or the [Discord](https://lunarphp.com/discord) community. [View the full release on GitHub](https://github.com/lunarphp/lunar/releases/tag/1.5.0-beta.1). # Lunar 1.5.0-beta.2 Source: https://docs.lunarphp.com/logs/2026/v1-5-0-beta-2 Second beta of the 1.5 cycle: Laravel 13 support, table rate shipping improvements, and a new shipping discount type. The second beta of the 1.5 cycle is now available, building on `1.5.0-beta.1` with framework updates, new shipping features, and a sweep of bug fixes. > [!WARNING] > > This is a pre-release. Pin to `1.5.0-beta.2` in `composer.json` and review the [upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) before installing on a production project. ## Framework support ### Laravel 13, PHP 8.3+ Lunar 1.5 now requires Laravel 12 or Laravel 13 and PHP 8.3 or later. Laravel 11 and PHP 8.2 have reached end of life and are no longer supported. See the [installation requirements](/1.x/getting-started/setup/installation) and the [upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) for the full list of changes. > [!NOTE] > > This release includes groundwork for Laravel 13, but it cannot run on Laravel 13 itself. Upgrading to Laravel 13 requires Lunar [1.5.0-beta.3](/logs/2026/v1-5-0-beta-3) or later. ## Table Rate Shipping This beta introduces several improvements to the Table Rate Shipping add-on. ### Availability schedules The single daily `cutoff` time on shipping methods has been replaced by a richer availability schedule, allowing finer control over when each method is offered. A migration drops the `cutoff` column; existing cutoff times are migrated automatically. ### Min and max weight Shipping methods can now define optional minimum and maximum cart weights. Methods whose constraints are not met are excluded from the rate resolver's results. ### Per-currency base prices Shipping rates now support a base price per currency, not just the store's default currency. ### Shipping discount type A new `Lunar\Shipping\DiscountTypes\ShippingDiscount` discount type targets the shipping portion of the cart. Discounts can replace the price for specific shipping methods (or all methods) with a fixed value per currency or a percentage off — enough to express common scenarios like free shipping or flat-rate promotions. ### Callable tax rate calculator The `shipping_rate_tax_calculation` config now accepts a callable for projects that need bespoke logic to determine the shipping tax class. See [Table Rate Shipping](/1.x/addons/table-rate-shipping) for the full updated documentation. ## Core changes * The `card_type` column on the `transactions` table is now nullable and no longer length-constrained. * Cart retrieval now prefers the latest unmerged active cart, avoiding a case where merged source carts could be selected after login/logout cycles. * Buy X Get Y discounts now record their use in `$cart->discounts` so usage tracking works correctly. ## Fixes and polish A range of smaller fixes ship in this beta, including: weight unit defaults on new product variants, attribute field type compatibility on the Filament v4 panel, deterministic activity log ordering for same-second events, number field type hydration, list field rendering, and validation for shipping dimensions. ## Upgrading Follow the [1.5 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) for the full set of steps and breaking changes. [View the full release on GitHub](https://github.com/lunarphp/lunar/releases/tag/1.5.0-beta.2). # Lunar 1.5.0-beta.3 Source: https://docs.lunarphp.com/logs/2026/v1-5-0-beta-3 Third beta of the 1.5 cycle, focused on attribute handling fixes, new locales, and polish for the Filament v4 panel. The third beta of the 1.5 cycle is now available. This release focuses on stabilising the Filament v4 admin panel, fixing a number of attribute-handling issues, and adding new locales contributed by the community. > [!WARNING] > > This is a pre-release. Pin to `1.5.0-beta.3` in `composer.json` and review the [upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) before installing on a production project. ## Attribute fixes A focused pass on attribute handling resolves several issues that surfaced on Filament v4: * Duplicated translated names in attribute resources are now prevented. * Translated rich text attributes hydrate and persist correctly. * Dropdown lookup state is normalized when editing attributes. * Translated text synthesis in the admin defensively handles edge-case payloads. ## Admin panel improvements * The Dashboard page now exposes a `getColumns` Lunar hook, allowing add-ons and extensions to control the column count. * Handles (for example, on collection groups, customer groups, channels, and attribute groups) are sanitized to a standardised format on save. Existing valid handles are unaffected. * The Product Options resource list is now searchable by both label and handle, and the indexer no longer mis-indexes the name field. * Scout search now works correctly with soft-deleted resources, aligned with the recommended `soft_delete` configuration. ## New locales The admin panel ships with three new community-contributed translations: * Bulgarian (`bg`) * Arabic (`ar`) * Persian (`fa`) ## Dependency updates The `kalnoy/nestedset` constraint has been widened to support Laravel 13, matching the wider 1.5 framework support. ## Upgrading No additional manual steps are required when moving from `1.5.0-beta.2`. Run the usual upgrade sequence: ```sh theme={null} composer update lunarphp/lunar php artisan migrate php artisan optimize:clear ``` If upgrading from `1.4` or earlier, follow the [1.5 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) in full. [View the full release on GitHub](https://github.com/lunarphp/lunar/releases/tag/1.5.0-beta.3). # Lunar 1.5.0-beta.4 Source: https://docs.lunarphp.com/logs/2026/v1-5-0-beta-4 Fourth beta of the 1.5 cycle, with new discount, shipping, and tax-zone capabilities plus a wide round of bug fixes. The fourth beta of the 1.5 cycle is now available. This release rounds out a number of new capabilities across discounts, shipping, and tax-zone handling, and ships a broad pass of fixes contributed by the community. > [!WARNING] > > This is a pre-release. Pin to `1.5.0-beta.4` in `composer.json` and review the [upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) before installing on a production project. ## New capabilities ### Cart-level tax zones The `carts` table now carries an optional `tax_zone_id`. Setting it through `Cart::setTaxZone()` lets line totals be calculated tax-inclusive before a shipping address is captured, which is helpful when the customer's region is already known from middleware. The `Price` model's `priceIncTax`, `priceExTax`, and `comparePriceIncTax` methods also accept an optional `TaxZone` so product display prices can be calculated for an arbitrary zone. See [Carts → Setting the Tax Zone](/1.x/reference/carts#setting-the-tax-zone) and [Pricing → Tax helper methods](/1.x/reference/pricing#tax-helper-methods). ### Configurable postcode resolvers Postcode formats vary by country, so the table-rate shipping add-on now resolves postcodes through registerable resolvers implementing `Lunar\Shipping\Interfaces\PostcodeResolverInterface`. The default UK-style resolver remains in place, and country-specific resolvers can be added through the `Postcode` facade. See [Postcode Resolvers](/1.x/addons/table-rate-shipping#postcode-resolvers). ### Collection rewards in BuyXGetY discounts `BuyXGetY` discounts can now use collections as the reward, in addition to products and variants. Collection conditions and rewards are wired through the same `discount->collections()` relationship and can be combined freely with product or variant discountables. See [BuyXGetY](/1.x/reference/discounts#buyxgety). ### File attribute disk and directory The File field type accepts new `disk` and `directory` configuration values, letting file attributes write to a configured filesystem disk and subdirectory. ### Extending relation-style admin pages `RelationPageExtension` now exposes an `extendTable` hook for relation-style pages such as `ManageProductVariants`, `ManageCollectionProducts`, and `ManageVariantMedia`. Columns, actions, filters, and query modifiers can be applied without replacing the page class. See [RelationPageExtension](/1.x/admin/extending/pages#relationpageextension). ## Fixes and hardening A wide round of fixes lands in this beta: * Editing tier or customer-group prices in the admin no longer triggers a `Price` cast error. * File attribute uploads are persisted correctly after save. * Stripe phantom payment bugs and zero-decimal currency conversions are fixed. * `ProductVariant` casts the real `shippable` attribute (the cast previously referenced an unused `requires_shipping` key). * Customer deletion now respects the configured foreign key constraints. * Attribute handle uniqueness is scoped by `attribute_type`, allowing the same handle on different attribute types. * The standalone `CouponValidator` enforces `max_uses_per_user`. * Products keep their navigation visibility when single-variant variants are deleted. * Soft-deleted purchasables are handled gracefully in cart lines. * The cart shipping breakdown is reset on every calculate, preventing stale entries. * Discount stop flags are now honored mid-apply loop. * Brand deletion nulls the `brand_id` on related products instead of cascading. * Tag values are normalized through a model mutator on save. * Telemetry rate-limiting is defensive against missing cache stores and HTTP failures. * Search indexers load related models more efficiently. * Weight-based shipping rate breakpoints evaluate correctly across band boundaries. * A composite unique index has been added to `product_product_option`. * Payment types validate amounts before transacting. ## New locales * Croatian (`hr`) * Mongolian (`mn`) ## Upgrading ```sh theme={null} composer update lunarphp/lunar php artisan migrate php artisan optimize:clear ``` The migration in this release adds a nullable `tax_zone_id` to the `carts` table. No additional manual steps are required when upgrading from `1.5.0-beta.3`. If upgrading from `1.4` or earlier, follow the [1.5 section of the upgrade guide](/1.x/getting-started/overview/upgrade-guide#15) in full. [View the full release on GitHub](https://github.com/lunarphp/lunar/releases/tag/1.5.0-beta.4). # Lunar 2.0 alpha Source: https://docs.lunarphp.com/logs/2026/v2-0-0-alpha The first alpha of Lunar 2.0, with a new Inertia.js admin panel, fulfilments, per-location inventory, regions, and a rebuilt pricing engine. The first alpha of Lunar 2.0 is available, alongside a new set of [v2.x documentation](/2.x/getting-started/overview/introduction). Lunar 2.0 is the largest release in the project's history: the core has been restructured around a cleaner extension model, and a brand-new admin panel replaces Filament as the recommended way to run a store. > [!WARNING] > > This is an alpha. APIs may still change between alpha releases, and production use is not recommended yet. Review the [upgrade guide](/2.x/getting-started/overview/upgrade-guide) before trying it against a copy of an existing store, and always work from a database backup. ## What's new ### A new admin panel Lunar 2.0 ships a new first-party admin panel built on Inertia.js and Vue, published as `lunarphp/panel`. It covers the full catalog, sales, and settings surface, adds a customizable widget dashboard, global search, autosaved edit drafts with conflict detection, and mandatory two-factor authentication for staff. It is extended through a PHP `Section` API paired with Vue components, so add-ons can register pages, table columns, slots, widgets, and search sources without touching panel source. The Filament-based admin from v1 remains available as `lunarphp/admin` for projects that prefer it. See the [admin panel introduction](/2.x/admin/introduction) for how the packages relate. ### Core changes * **Fulfilments** — orders are now fulfilled through dedicated fulfilment records with methods, carriers, and tracking. See [Fulfilments](/2.x/reference/fulfilments). * **Inventory** — stock is tracked per variant per location, with movements, reservations, and reconciliation. See [Inventory](/2.x/reference/inventory). * **Regions** — a new concept grouping channel, currency, language, and tax behavior for a market. See [Regions](/2.x/reference/regions). * **Storefront context** — a single session-backed context feeds pricing and availability. See [Storefront Session](/2.x/storefront-utils/storefront-session). * **Pricing engine** — prices flow through a dedicated `PriceValue` type and a fluent pricing API. See [Pricing](/2.x/reference/pricing). * **Cleaner extension model** — the `Lunar\Core\...` namespace, verb methods on models backed by swappable action contracts, and container bindings in place of config-based class substitution. See [Extending Lunar](/2.x/extending/models). ## Upgrading from 1.x The new `lunarphp/upgrade` package automates much of the move: Rector rules rewrite namespaces and renamed APIs, and guided data migrations transform a v1 database. The [upgrade guide](/2.x/getting-started/overview/upgrade-guide) walks through the full process and the manual checklist. ## Feedback Alpha feedback is welcome through [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) or the [Discord](https://lunarphp.com/discord) community. # Lunar Flight Plan Source: https://docs.lunarphp.com/logs/flight-plan Where Lunar is heading through the v2 cycle: what has shipped, what is next, and what follows. The Flight Plan sets out where the Lunar project is heading, how the pieces fit together, and when each part is expected to land. ## Introduction Lunar's goal has always been the same: to be the most flexible, modern e-commerce foundation for Laravel developers. v2 brings that into sharper focus. What follows is the result of community input and conversations with the people building stores on Lunar today. Plans evolve as work progresses, so this page is updated as milestones ship. ## Where v2 is today Alpha available now The first alphas of Lunar 2.0 are published. Read the [2.0 alpha announcement](/logs/2026/v2-0-0-alpha) and the [v2.x documentation](/2.x/getting-started/overview/introduction) to try it against a copy of an existing store. | Milestone | Target | | - | - | | Alpha | Available now | | Beta | October 2026 | | Stable v2.0.0 | End of 2026 | The alpha is for evaluation and feedback only. APIs can still change between alpha releases, and production use is not recommended until the stable release. ## What v2.0.0 brings v2.0.0 is the foundational release. It introduces breaking changes that improve how Lunar works under the hood, alongside new core concepts. Most of this is already in the alpha: * Reworked custom attributes * A dedicated pricing engine with significant performance improvements to price fields * Cart performance improvements * New core concepts including regions and storefront context * Fulfilments and per-location inventory in core * A cleaner extension model built on native Laravel seams Full release notes will follow closer to the stable release. Together these changes give Lunar a stronger, more consistent base to build the rest of the v2 cycle on. ## The new admin panel In the alpha The big change in the v2 cycle is a new admin panel, built on Inertia.js and Vue, published as `lunarphp/panel`. It ships in the alpha today with the full catalog, sales, and settings surface, a customizable widget dashboard, global search, autosaved edit drafts, and mandatory two-factor authentication for staff. It is faster, cleaner, and built for the kinds of stores Lunar is increasingly used to run. But the bigger story is the **proper extension points** underneath. v1's extension surface grew organically and worked, but it was not always predictable. v2 draws a firm line between core and extensions, and that line is what makes everything else on this page possible. The panel continues to be refined through the beta. See the [admin panel documentation](/2.x/admin/introduction) for the current state. ## Inventory and fulfilment in core In the alpha v2 brings inventory and fulfilment into core at a basic level. Stock is tracked per variant per location with movements and reservations, and orders are fulfilled through dedicated fulfilment records with methods, carriers, and tracking. See [Inventory](/2.x/reference/inventory) and [Fulfilments](/2.x/reference/fulfilments). These are things almost every store needs in some form, and having them in core gives Lunar a consistent base to build on. The aim is not to ship a full warehouse management system in core. It is to provide the right primitives, in the right place, so simpler stores get what they need out of the box and the more demanding ones have something solid to extend. ## Returns Later in the v2 cycle Returns and RMA (return merchandise authorization) build on the fulfilment and inventory primitives above, including routing returned goods through an inspection state before they become sellable again. This arrives in a later minor release during the v2 cycle. It also sets up the deeper enhancements and ERP-grade functionality that come through Lunar Eclipse later. ## A better story for Filament developers In the alpha One of the clearest pieces of feedback from the v1 community has been around control. Filament developers want to own the look, feel, and behavior of their admin, and that has been harder to achieve with Lunar than it should be. v2 changes that with a dedicated Filament package, `lunarphp/filament`. It is a bridge that exposes Lunar's components and widgets as building blocks Filament developers can compose freely inside their own panels. Rather than working within a Lunar-shaped Filament admin, developers get the pieces and build the UX they want. The package supports **Filament v5** and is versioned separately from Lunar itself. That lets it follow Filament's own release cycle more closely, so Filament developers are not waiting on a Lunar release to get support for the latest Filament version. This is the model for Lunar going forward. Lunar provides the commerce primitives, and the framework used to build the admin stays under the developer's control. The existing Filament admin, `lunarphp/admin`, carries on through v2, so nobody has to migrate the day v2 lands. From v3, the admin package is phased out, but the bridge package stays. See the [Filament add-on documentation](/2.x/addons/filament/overview). ## Storefront starter kit With the stable v2.0.0 release Alongside the panel, Lunar is shipping a storefront starter kit, also built on Inertia.js and Vue. The idea is straightforward: get a developer from zero to a working, customizable storefront in minutes, fully integrated with Lunar's checkout. It is not a locked-in theme. It is a starting point, designed to be owned and shaped by the team building on it. The v1 starter kit has not yet been updated for v2. Until the new kit ships, the [storefront guides](/2.x/guides/catalog-menu) walk through building a storefront against v2 from scratch. ## Checkout With the stable v2.0.0 release Checkout is a dedicated, open source checkout layer for Lunar, planned to release alongside the storefront starter kit. Building it as its own component keeps it cleanly separated from the storefront and the admin, which means it can move at its own pace and get the kind of focused attention this part of e-commerce deserves. The open source checkout will also be the foundation for a future hosted product, with additional capabilities on top for stores that want a managed setup. More on that in due course. ## Built for developers and AI agents Lunar is plain Laravel and Eloquent, with no proprietary DSL, which makes it a natural fit for agentic development. The documentation already ships an [MCP server, `llms.txt`, and Markdown export](/2.x/getting-started/overview/ai-development), and the 1.x core package includes a Laravel Boost skill. Planned for the v2 cycle: * A Laravel Boost skill for v2, shipped with the core package * A first-party storefront REST API * MCP servers for the admin panel, the storefront, and developer tooling ## Add-on development and a marketplace Later in the v2 cycle With proper extension points comes a proper path for third-party development. v2 is built from the ground up to support an add-on ecosystem, with a marketplace giving developers somewhere to publish, distribute, and monetize their work. This is how Lunar grows beyond what any one team can build. ## Lunar Eclipse Following the stable v2.0.0 release Lunar Eclipse extends the platform with the features serious operators ask for: B2B, trade, and ERP capabilities, built on top of the open core. It is the main commercial route for Lunar, and it funds the long-term development of everything else on this page. More on Eclipse soon. ## Product bundles Selling a kit ("camera body + bag + SD card") as one product has never had a clean answer in Lunar: a normal product tracks stock independently of its parts, and a discount is a promotion, not a product. v2 adds two small seams to core, component order lines and a resolver behind a variant's stock answers, and a first-party `lunarphp/bundles` add-on built on them. A bundle is an ordinary product variant with a component list: stock is derived from the components, the price is fixed or derived from the components with a saving, and the order records one component line per part so fulfilment, stock commitment, and returns work unchanged. Configurable bundles let the customer choose from option groups. The panel gets a bundle editor on the product pages and nests component lines in the order view. See [Bundles](/2.x/addons/bundles) for the documentation. Alpha, v2 cycle *** ## Stay Involved Plans evolve based on community feedback and real-world implementations. Follow progress, contribute ideas, or join discussions on [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) and [Discord](https://lunarphp.com/discord). # Neon Digital Source: https://docs.lunarphp.com/support/alliance/neon-digital * Location: Essex, United Kingdom * Website: [neondigital.co.uk](https://neondigital.co.uk?utm_source=lunar\&utm_medium=referral\&utm_campaign=lunar_alliance) Neon Digital is the founding agency behind Lunar and a leading Laravel-focused studio in the UK. With over a decade of experience delivering large-scale e-commerce solutions, Neon combines technical expertise with real-world understanding of B2B and D2C commerce. Their work powers brands including Orbital Fasteners, Edwardes Bros, Powerflex, and Plumo, with a strong focus on performance, maintainability, and long-term client partnerships. Neon continues to lead the development of Lunar’s core platform, while helping other agencies and merchants successfully adopt it. # Thought Collective Source: https://docs.lunarphp.com/support/alliance/thought-collective * Location: Dublin, Ireland & Belfast, Northern Ireland * Website: [thoughtcollective.com](https://www.thoughtcollective.com?utm_source=lunar\&utm_medium=referral\&utm_campaign=lunar_alliance) Thought Collective bring over 20 years of experience designing and developing award-winning digital experiences for clients across a wide range of industries. Whether you’re building a high-performing online store, a complex multi-vendor marketplace, or a bespoke commerce platform powered by Lunar, we have the expertise and insight to help you achieve your strategic goals. Based from offices in Belfast and Dublin, our team of brand strategists, UX designs, developers, and digital marketeers will bring all their skills and ideas the table to ensure the success of your project. # Weby Digital Source: https://docs.lunarphp.com/support/alliance/weby-digital * Location: Kuala Lumpur, Malaysia * Website: [weby.digital](https://weby.digital?utm_source=lunar\&utm_medium=referral\&utm_campaign=lunar_alliance) At Weby Digital, we craft custom software solutions designed around each business’s unique goals. Specializing in e-commerce platforms powered by Lunar, we believe that no two businesses are the same — and neither should their solutions be. Our team blends technical expertise with real-world understanding to help businesses across Malaysia, Singapore, and Indonesia build, scale, and sustain powerful online platforms in the growing ASEAN digital landscape. Whether you’re launching your first online store or revamping an existing system, Weby Digital delivers solutions that work seamlessly, grow intelligently, and truly reflect your brand’s potential. Let’s build something made just for you. # Community Support Source: https://docs.lunarphp.com/support/community Free help from the community We’re here to help you get the most out of Lunar. Whether you need quick answers from the community or dedicated assistance from our team, we offer multiple ways to get support for your Lunar-powered project. ## Community Support Lunar is an open-source project, and we have an active community of developers who are happy to help. If you’re looking for general advice or troubleshooting tips, try the following: [Discord Community](https://lunarphp.com/discord) – Join the discussion, ask questions, and collaborate with other Lunar users. [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) – Browse existing topics or start a new discussion about features and issues. [Bug Reports](https://github.com/lunarphp/lunar/issues) – Found a bug? Report it on our GitHub repository so we can improve Lunar. Community support is a great way to get help from other developers and contributors, though response times may vary. If you need dedicated expertise or hands-on project support, explore the Lunar Alliance — a network of trusted partners who work alongside us to help you deliver with confidence. # Overview Source: https://docs.lunarphp.com/support/lunar-alliance Working together to build the future of Laravel e-commerce The Lunar Alliance is a collective of trusted agencies and independent developers who work alongside the Lunar team to deliver world-class e-commerce experiences. Members of the Alliance share our values of craftsmanship, transparency, and innovation — helping businesses of all sizes get the most out of the Lunar ecosystem. Whether you need implementation support, a custom integration, or ongoing technical partnership, the Alliance is here to help. ### Why the Alliance exists Lunar’s vision has always been bigger than a single product — it’s a growing ecosystem. The Alliance exists to: * Connect merchants and developers with experienced Laravel e-commerce experts * Strengthen the open-source community through collaboration and shared knowledge * Ensure consistent quality and best practices across real-world Lunar projects Each Alliance member is independently operated but closely aligned with Lunar’s principles and technical roadmap. ### How it works * You choose your partner — work directly with an Alliance member suited to your project. * You stay in control — each partner manages their own pricing, process, and delivery. * We stay connected — the Lunar core team collaborates regularly with Alliance members to share feedback, insights, and early access to new features. *** ## Current Alliance Members * [Neon Digital](/support/alliance/neon-digital) * [Thought Collective](/support/alliance/thought-collective) * [Weby Digital](/support/alliance/weby-digital) *** ## Join the Lunar Alliance If your agency or freelance practice delivers exceptional Lunar-based e-commerce work and you share our open-source values, we’d love to hear from you. Apply to join the Lunar Alliance # Lunar 2.0 alpha Source: https://docs.lunarphp.com/logs/2026/v2-0-0-alpha The first alpha of Lunar 2.0, with a new Inertia.js admin panel, fulfilments, per-location inventory, regions, and a rebuilt pricing engine. The first alpha of Lunar 2.0 is available, alongside a new set of [v2.x documentation](/2.x/getting-started/overview/introduction). Lunar 2.0 is the largest release in the project's history: the core has been restructured around a cleaner extension model, and a brand-new admin panel replaces Filament as the recommended way to run a store. > [!WARNING] > > This is an alpha. APIs may still change between alpha releases, and production use is not recommended yet. Review the [upgrade guide](/2.x/getting-started/overview/upgrade-guide) before trying it against a copy of an existing store, and always work from a database backup. ## What's new ### A new admin panel Lunar 2.0 ships a new first-party admin panel built on Inertia.js and Vue, published as `lunarphp/panel`. It covers the full catalog, sales, and settings surface, adds a customizable widget dashboard, global search, autosaved edit drafts with conflict detection, and mandatory two-factor authentication for staff. It is extended through a PHP `Section` API paired with Vue components, so add-ons can register pages, table columns, slots, widgets, and search sources without touching panel source. The Filament-based admin from v1 remains available as `lunarphp/admin` for projects that prefer it. See the [admin panel introduction](/2.x/admin/introduction) for how the packages relate. ### Core changes * **Fulfilments** — orders are now fulfilled through dedicated fulfilment records with methods, carriers, and tracking. See [Fulfilments](/2.x/reference/fulfilments). * **Inventory** — stock is tracked per variant per location, with movements, reservations, and reconciliation. See [Inventory](/2.x/reference/inventory). * **Regions** — a new concept grouping channel, currency, language, and tax behavior for a market. See [Regions](/2.x/reference/regions). * **Storefront context** — a single session-backed context feeds pricing and availability. See [Storefront Session](/2.x/storefront-utils/storefront-session). * **Pricing engine** — prices flow through a dedicated `PriceValue` type and a fluent pricing API. See [Pricing](/2.x/reference/pricing). * **Cleaner extension model** — the `Lunar\Core\...` namespace, verb methods on models backed by swappable action contracts, and container bindings in place of config-based class substitution. See [Extending Lunar](/2.x/extending/models). ## Upgrading from 1.x The new `lunarphp/upgrade` package automates much of the move: Rector rules rewrite namespaces and renamed APIs, and guided data migrations transform a v1 database. The [upgrade guide](/2.x/getting-started/overview/upgrade-guide) walks through the full process and the manual checklist. ## Feedback Alpha feedback is welcome through [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) or the [Discord](https://lunarphp.com/discord) community. # Lunar Flight Plan Source: https://docs.lunarphp.com/logs/flight-plan Where Lunar is heading through the v2 cycle: what has shipped, what is next, and what follows. The Flight Plan sets out where the Lunar project is heading, how the pieces fit together, and when each part is expected to land. ## Introduction Lunar's goal has always been the same: to be the most flexible, modern e-commerce foundation for Laravel developers. v2 brings that into sharper focus. What follows is the result of community input and conversations with the people building stores on Lunar today. Plans evolve as work progresses, so this page is updated as milestones ship. ## Where v2 is today Alpha available now The first alphas of Lunar 2.0 are published. Read the [2.0 alpha announcement](/logs/2026/v2-0-0-alpha) and the [v2.x documentation](/2.x/getting-started/overview/introduction) to try it against a copy of an existing store. | Milestone | Target | | - | - | | Alpha | Available now | | Beta | October 2026 | | Stable v2.0.0 | End of 2026 | The alpha is for evaluation and feedback only. APIs can still change between alpha releases, and production use is not recommended until the stable release. ## What v2.0.0 brings v2.0.0 is the foundational release. It introduces breaking changes that improve how Lunar works under the hood, alongside new core concepts. Most of this is already in the alpha: * Reworked custom attributes * A dedicated pricing engine with significant performance improvements to price fields * Cart performance improvements * New core concepts including regions and storefront context * Fulfilments and per-location inventory in core * A cleaner extension model built on native Laravel seams Full release notes will follow closer to the stable release. Together these changes give Lunar a stronger, more consistent base to build the rest of the v2 cycle on. ## The new admin panel In the alpha The big change in the v2 cycle is a new admin panel, built on Inertia.js and Vue, published as `lunarphp/panel`. It ships in the alpha today with the full catalog, sales, and settings surface, a customizable widget dashboard, global search, autosaved edit drafts, and mandatory two-factor authentication for staff. It is faster, cleaner, and built for the kinds of stores Lunar is increasingly used to run. But the bigger story is the **proper extension points** underneath. v1's extension surface grew organically and worked, but it was not always predictable. v2 draws a firm line between core and extensions, and that line is what makes everything else on this page possible. The panel continues to be refined through the beta. See the [admin panel documentation](/2.x/admin/introduction) for the current state. ## Inventory and fulfilment in core In the alpha v2 brings inventory and fulfilment into core at a basic level. Stock is tracked per variant per location with movements and reservations, and orders are fulfilled through dedicated fulfilment records with methods, carriers, and tracking. See [Inventory](/2.x/reference/inventory) and [Fulfilments](/2.x/reference/fulfilments). These are things almost every store needs in some form, and having them in core gives Lunar a consistent base to build on. The aim is not to ship a full warehouse management system in core. It is to provide the right primitives, in the right place, so simpler stores get what they need out of the box and the more demanding ones have something solid to extend. ## Returns Later in the v2 cycle Returns and RMA (return merchandise authorization) build on the fulfilment and inventory primitives above, including routing returned goods through an inspection state before they become sellable again. This arrives in a later minor release during the v2 cycle. It also sets up the deeper enhancements and ERP-grade functionality that come through Lunar Eclipse later. ## A better story for Filament developers In the alpha One of the clearest pieces of feedback from the v1 community has been around control. Filament developers want to own the look, feel, and behavior of their admin, and that has been harder to achieve with Lunar than it should be. v2 changes that with a dedicated Filament package, `lunarphp/filament`. It is a bridge that exposes Lunar's components and widgets as building blocks Filament developers can compose freely inside their own panels. Rather than working within a Lunar-shaped Filament admin, developers get the pieces and build the UX they want. The package supports **Filament v5** and is versioned separately from Lunar itself. That lets it follow Filament's own release cycle more closely, so Filament developers are not waiting on a Lunar release to get support for the latest Filament version. This is the model for Lunar going forward. Lunar provides the commerce primitives, and the framework used to build the admin stays under the developer's control. The existing Filament admin, `lunarphp/admin`, carries on through v2, so nobody has to migrate the day v2 lands. From v3, the admin package is phased out, but the bridge package stays. See the [Filament add-on documentation](/2.x/addons/filament/overview). ## Storefront starter kit With the stable v2.0.0 release Alongside the panel, Lunar is shipping a storefront starter kit, also built on Inertia.js and Vue. The idea is straightforward: get a developer from zero to a working, customizable storefront in minutes, fully integrated with Lunar's checkout. It is not a locked-in theme. It is a starting point, designed to be owned and shaped by the team building on it. The v1 starter kit has not yet been updated for v2. Until the new kit ships, the [storefront guides](/2.x/guides/catalog-menu) walk through building a storefront against v2 from scratch. ## Checkout With the stable v2.0.0 release Checkout is a dedicated, open source checkout layer for Lunar, planned to release alongside the storefront starter kit. Building it as its own component keeps it cleanly separated from the storefront and the admin, which means it can move at its own pace and get the kind of focused attention this part of e-commerce deserves. The open source checkout will also be the foundation for a future hosted product, with additional capabilities on top for stores that want a managed setup. More on that in due course. ## Built for developers and AI agents Lunar is plain Laravel and Eloquent, with no proprietary DSL, which makes it a natural fit for agentic development. The documentation already ships an [MCP server, `llms.txt`, and Markdown export](/2.x/getting-started/overview/ai-development), and the 1.x core package includes a Laravel Boost skill. Planned for the v2 cycle: * A Laravel Boost skill for v2, shipped with the core package * A first-party storefront REST API * MCP servers for the admin panel, the storefront, and developer tooling ## Add-on development and a marketplace Later in the v2 cycle With proper extension points comes a proper path for third-party development. v2 is built from the ground up to support an add-on ecosystem, with a marketplace giving developers somewhere to publish, distribute, and monetize their work. This is how Lunar grows beyond what any one team can build. ## Lunar Eclipse Following the stable v2.0.0 release Lunar Eclipse extends the platform with the features serious operators ask for: B2B, trade, and ERP capabilities, built on top of the open core. It is the main commercial route for Lunar, and it funds the long-term development of everything else on this page. More on Eclipse soon. ## Product bundles Selling a kit ("camera body + bag + SD card") as one product has never had a clean answer in Lunar: a normal product tracks stock independently of its parts, and a discount is a promotion, not a product. v2 adds two small seams to core, component order lines and a resolver behind a variant's stock answers, and a first-party `lunarphp/bundles` add-on built on them. A bundle is an ordinary product variant with a component list: stock is derived from the components, the price is fixed or derived from the components with a saving, and the order records one component line per part so fulfilment, stock commitment, and returns work unchanged. Configurable bundles let the customer choose from option groups. The panel gets a bundle editor on the product pages and nests component lines in the order view. See [Bundles](/2.x/addons/bundles) for the documentation. Alpha, v2 cycle *** ## Stay Involved Plans evolve based on community feedback and real-world implementations. Follow progress, contribute ideas, or join discussions on [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) and [Discord](https://lunarphp.com/discord). # Neon Digital Source: https://docs.lunarphp.com/support/alliance/neon-digital * Location: Essex, United Kingdom * Website: [neondigital.co.uk](https://neondigital.co.uk?utm_source=lunar\&utm_medium=referral\&utm_campaign=lunar_alliance) Neon Digital is the founding agency behind Lunar and a leading Laravel-focused studio in the UK. With over a decade of experience delivering large-scale e-commerce solutions, Neon combines technical expertise with real-world understanding of B2B and D2C commerce. Their work powers brands including Orbital Fasteners, Edwardes Bros, Powerflex, and Plumo, with a strong focus on performance, maintainability, and long-term client partnerships. Neon continues to lead the development of Lunar’s core platform, while helping other agencies and merchants successfully adopt it. # Thought Collective Source: https://docs.lunarphp.com/support/alliance/thought-collective * Location: Dublin, Ireland & Belfast, Northern Ireland * Website: [thoughtcollective.com](https://www.thoughtcollective.com?utm_source=lunar\&utm_medium=referral\&utm_campaign=lunar_alliance) Thought Collective bring over 20 years of experience designing and developing award-winning digital experiences for clients across a wide range of industries. Whether you’re building a high-performing online store, a complex multi-vendor marketplace, or a bespoke commerce platform powered by Lunar, we have the expertise and insight to help you achieve your strategic goals. Based from offices in Belfast and Dublin, our team of brand strategists, UX designs, developers, and digital marketeers will bring all their skills and ideas the table to ensure the success of your project. # Weby Digital Source: https://docs.lunarphp.com/support/alliance/weby-digital * Location: Kuala Lumpur, Malaysia * Website: [weby.digital](https://weby.digital?utm_source=lunar\&utm_medium=referral\&utm_campaign=lunar_alliance) At Weby Digital, we craft custom software solutions designed around each business’s unique goals. Specializing in e-commerce platforms powered by Lunar, we believe that no two businesses are the same — and neither should their solutions be. Our team blends technical expertise with real-world understanding to help businesses across Malaysia, Singapore, and Indonesia build, scale, and sustain powerful online platforms in the growing ASEAN digital landscape. Whether you’re launching your first online store or revamping an existing system, Weby Digital delivers solutions that work seamlessly, grow intelligently, and truly reflect your brand’s potential. Let’s build something made just for you. # Community Support Source: https://docs.lunarphp.com/support/community Free help from the community We’re here to help you get the most out of Lunar. Whether you need quick answers from the community or dedicated assistance from our team, we offer multiple ways to get support for your Lunar-powered project. ## Community Support Lunar is an open-source project, and we have an active community of developers who are happy to help. If you’re looking for general advice or troubleshooting tips, try the following: [Discord Community](https://lunarphp.com/discord) – Join the discussion, ask questions, and collaborate with other Lunar users. [GitHub Discussions](https://github.com/lunarphp/lunar/discussions) – Browse existing topics or start a new discussion about features and issues. [Bug Reports](https://github.com/lunarphp/lunar/issues) – Found a bug? Report it on our GitHub repository so we can improve Lunar. Community support is a great way to get help from other developers and contributors, though response times may vary. If you need dedicated expertise or hands-on project support, explore the Lunar Alliance — a network of trusted partners who work alongside us to help you deliver with confidence. # Overview Source: https://docs.lunarphp.com/support/lunar-alliance Working together to build the future of Laravel e-commerce The Lunar Alliance is a collective of trusted agencies and independent developers who work alongside the Lunar team to deliver world-class e-commerce experiences. Members of the Alliance share our values of craftsmanship, transparency, and innovation — helping businesses of all sizes get the most out of the Lunar ecosystem. Whether you need implementation support, a custom integration, or ongoing technical partnership, the Alliance is here to help. ### Why the Alliance exists Lunar’s vision has always been bigger than a single product — it’s a growing ecosystem. The Alliance exists to: * Connect merchants and developers with experienced Laravel e-commerce experts * Strengthen the open-source community through collaboration and shared knowledge * Ensure consistent quality and best practices across real-world Lunar projects Each Alliance member is independently operated but closely aligned with Lunar’s principles and technical roadmap. ### How it works * You choose your partner — work directly with an Alliance member suited to your project. * You stay in control — each partner manages their own pricing, process, and delivery. * We stay connected — the Lunar core team collaborates regularly with Alliance members to share feedback, insights, and early access to new features. *** ## Current Alliance Members * [Neon Digital](/support/alliance/neon-digital) * [Thought Collective](/support/alliance/thought-collective) * [Weby Digital](/support/alliance/weby-digital) *** ## Join the Lunar Alliance If your agency or freelance practice delivers exceptional Lunar-based e-commerce work and you share our open-source values, we’d love to hear from you. Apply to join the Lunar Alliance