Carriers
Complete reference for the Carrier model, shipping options, and delivery management in Shopper.
Carriers represent shipping providers and their delivery options. Shopper uses a two-level structure with carriers (the shipping company) and carrier options (specific delivery methods with prices per zone).
Shopper provides a flexible shipping system that supports both manual rate configuration and real-time API integration with major carriers like UPS, FedEx, and USPS.
Models
Shopper uses two models to manage shipping:
| Model | Purpose |
|---|---|
Shopper\Core\Models\Carrier | The shipping provider (UPS, FedEx, local delivery) |
Shopper\Core\Models\CarrierOption | Specific delivery methods with pricing per zone |
The Carrier model implements Shopper\Core\Models\Contracts\Carrier and uses the HasSlug and HasZones traits. It is not configurable via config/shopper/models.php.
Database Schema
Carrier Table
| Column | Type | Nullable | Default | Description |
|---|---|---|---|---|
id | bigint | no | auto | Primary key |
name | string | no | - | Carrier name |
slug | string | yes | null | URL-friendly identifier (unique). The value you pass is slugified and suffixed (-1, -2) when taken; nothing is generated when you omit it. The admin form fills it from the name |
driver | string | yes | null | Shipping driver code (manual, ups, fedex, usps or a custom driver). null is treated as manual; the admin form stores manual |
link_url | string | yes | null | Carrier website URL |
description | string | yes | null | Carrier description |
shipping_amount | integer | yes | null | Amount in cents. Shopper does not read this column: rates come from the driver or from carrier options |
is_enabled | boolean | no | false | Carrier visibility |
metadata | json | yes | null | Additional custom data |
created_at | timestamp | yes | null | Creation timestamp |
updated_at | timestamp | yes | null | Last update timestamp |
CarrierOption Table
| Column | Type | Nullable | Default | Description |
|---|---|---|---|---|
id | bigint | no | auto | Primary key |
name | string | no | - | Option name, unique per zone (unique index on name and zone_id) |
description | string(255) | yes | null | Option description |
price | integer | no | - | Shipping price (cents) |
is_enabled | boolean | no | false | Option visibility |
carrier_id | bigint | no | - | FK to carrier |
zone_id | bigint | no | - | FK to zone |
metadata | json | yes | null | Additional custom data |
created_at | timestamp | yes | null | Creation timestamp |
updated_at | timestamp | yes | null | Last update timestamp |
Shipping Drivers
Shopper uses a driver-based architecture for shipping, similar to Laravel's Mail or Queue systems. This allows you to connect carriers directly to shipping provider APIs for real-time rate calculation, or use manual rates stored in your database.
Available Drivers
| Driver | Code | Description |
|---|---|---|
| Manual | manual | Rates come from CarrierOption records in your database |
| UPS | ups | Real-time rates from UPS API |
| FedEx | fedex | Real-time rates from FedEx API |
| USPS | usps | Real-time rates from USPS API |
Driver Configuration
All driver credentials are stored in your .env file. Publish the shipping configuration file to customize drivers:
php artisan vendor:publish --tag=shopper-configThe shopper-config tag publishes every Shopper config file; files already in config/shopper are kept unless you add --force (Laravel's vendor:publish behavior). This creates config/shopper/shipping.php:
return [
'drivers' => [
'ups' => [
'enabled' => env('SHIPPING_UPS_ENABLED', false),
'sandbox' => env('SHIPPING_SANDBOX', false),
'credentials' => [
'client_id' => env('UPS_CLIENT_ID'),
'client_secret' => env('UPS_CLIENT_SECRET'),
'user_id' => env('UPS_USER_ID'),
'account_number' => env('UPS_ACCOUNT_NUMBER'),
],
],
'fedex' => [
'enabled' => env('SHIPPING_FEDEX_ENABLED', false),
'sandbox' => env('SHIPPING_SANDBOX', false),
'credentials' => [
'client_id' => env('FEDEX_CLIENT_ID'),
'client_secret' => env('FEDEX_CLIENT_SECRET'),
'account_number' => env('FEDEX_ACCOUNT_NUMBER'),
],
],
'usps' => [
'enabled' => env('SHIPPING_USPS_ENABLED', false),
'sandbox' => env('SHIPPING_SANDBOX', false),
'credentials' => [
'client_id' => env('USPS_CLIENT_ID'),
'client_secret' => env('USPS_CLIENT_SECRET'),
],
],
],
'units' => env('SHIPPING_UNITS', 'metric'),
];The published file also contains canada_post and purolator entries. No built-in driver reads them: to use those carriers, register a custom driver under the same code. Shopper does not apply the units value to packages for you: read it with config('shopper.shipping.units') when you build your Package objects.
Add the credentials to your .env file:
SHIPPING_UPS_ENABLED=true
SHIPPING_SANDBOX=true
UPS_CLIENT_ID=your-client-id
UPS_CLIENT_SECRET=your-client-secret
UPS_USER_ID=your-user-id
UPS_ACCOUNT_NUMBER=your-account-numberA driver is ready when its credentials are filled: UPS needs all four values above, FedEx needs client_id, client_secret and account_number, USPS needs client_id and client_secret. The enabled flag only decides whether the driver appears in Shipping::configuredDrivers(). Rate calculation and the admin carrier form check the credentials, not this flag.
Using the Shipping Facade
The Shipping facade provides access to the shipping manager and all registered drivers:
use Shopper\Shipping\Facades\Shipping;
$driver = Shipping::driver('ups');
$allDrivers = Shipping::availableDrivers();
$configured = Shipping::configuredDrivers();
$isReady = Shipping::isConfigured('fedex');driver()returns aShippingDriverinstance. Called without a name, it returns themanualdriver. An unknown name throws anInvalidArgumentException.availableDrivers()returns the driver codes:manual,ups,fedex,uspsand every custom driver you registered.configuredDrivers()returns a collection of driver instances keyed by code:manualplus the drivers whoseenabledflag istrue.isConfigured()returnstruewhen the driver's credentials are filled, andfalsefor an unknown driver.
Carrier Driver Integration
The Carrier model has no driver methods of its own: the CarrierRateService resolves the driver from the carrier's driver column, and logo() asks that driver for its logo URL:
use Shopper\Core\Models\Carrier;
use Shopper\Shipping\Services\CarrierRateService;
$carrier = Carrier::query()->where('driver', 'ups')->first();
$service = app(CarrierRateService::class);
$driver = $service->resolveDriver($carrier);
$isConfigured = $service->isDriverConfigured($carrier);
$logo = $carrier->logo();resolveDriver() returns null when the carrier's driver is empty or manual. When a carrier has a driver whose credentials are set, Shopper uses that driver to fetch real-time rates from the carrier's API. When no driver is assigned, the driver is manual, or its credentials are missing, rates come from the CarrierOption records in your database.
Calculating Shipping Rates
The CarrierRateService provides a unified way to get shipping rates, regardless of whether the carrier uses an API driver or manual configuration.
use Shopper\Shipping\Services\CarrierRateService;
use Shopper\Shipping\DataTransferObjects\Address;
use Shopper\Shipping\DataTransferObjects\Package;
$service = app(CarrierRateService::class);
$from = new Address(
firstName: 'Store',
lastName: 'Warehouse',
street: '123 Warehouse St',
city: 'Los Angeles',
postalCode: '90001',
state: 'CA',
country: 'US',
);
$to = new Address(
firstName: 'John',
lastName: 'Doe',
street: '456 Customer Ave',
city: 'New York',
postalCode: '10001',
state: 'NY',
country: 'US',
);
$packages = [
new Package(
length: 30,
width: 20,
height: 15,
weight: 2.5,
unit: 'metric',
),
];The country of an Address is the two-letter ISO code (US, CA, FR), which the drivers send to the carrier API. A Package takes unit: 'metric' (centimeters and kilograms, the default) or unit: 'imperial' (inches and pounds). The built-in drivers convert packages to the units their API expects.
Getting Rates for a Carrier
$rates = $service->getRatesForCarrier(
carrier: $carrier,
from: $from,
to: $to,
packages: $packages,
zone: $zone,
);For carriers with an API driver whose credentials are set, rates are fetched from the carrier's API. For manual carriers, rates come from the enabled CarrierOption records of the specified zone. The zone argument is optional: without it, every enabled option of the carrier is returned, priced in the store's default currency. When the carrier API fails, the driver throws a Shopper\Shipping\Exceptions\ShippingException.
Getting Rates for a Zone
To get all available shipping rates for a zone across its enabled carriers:
$rates = $service->getRatesForZone(
zone: $zone,
from: $from,
to: $to,
packages: $packages,
);Only carriers attached to the zone are included (see zone carriers). getRatesForZone() does not catch a ShippingException: when one carrier API fails, the call throws and returns no rate at all. To keep the other carriers' rates, call getRatesForCarrier() for each carrier yourself:
use Shopper\Core\Models\Carrier;
use Shopper\Shipping\Exceptions\ShippingException;
$rates = $zone->carriers()->enabled()->get()->flatMap(function (Carrier $carrier) use ($service, $from, $to, $packages, $zone) {
try {
return $service->getRatesForCarrier($carrier, $from, $to, $packages, $zone);
} catch (ShippingException $exception) {
report($exception);
return collect();
}
});ShippingRate DTO
Both methods return a collection of ShippingRate objects:
foreach ($rates as $rate) {
$rate->serviceCode;
$rate->serviceName;
$rate->amount;
$rate->currency;
$rate->carrierCode;
$rate->estimatedDays;
$rate->estimatedDelivery;
$rate->formattedAmount();
$rate->toArray();
}amount is in cents and formattedAmount() formats it with shopper_money_format(). For a manual rate, serviceCode is the CarrierOption id, serviceName its name, currency the zone's currency code, carrierCode the carrier slug (its name when the slug is empty), and estimatedDays and estimatedDelivery are null.
Custom Shipping Drivers
Shopper's shipping system is designed for extensibility. You can create custom drivers for any shipping provider not included by default, such as DHL, Canada Post, Colissimo, or regional carriers.
Creating a Driver
A shipping driver must implement the ShippingDriver contract. The easiest approach is to extend the abstract Driver class, which provides sensible defaults for optional methods.
Create your driver class:
namespace App\Shipping\Drivers;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Shopper\Shipping\Drivers\Driver;
use Shopper\Shipping\DataTransferObjects\Address;
use Shopper\Shipping\DataTransferObjects\Package;
use Shopper\Shipping\DataTransferObjects\ShippingRate;
use Shopper\Shipping\Exceptions\ShippingException;
final class DhlDriver extends Driver
{
public function __construct(
private readonly string $apiKey,
private readonly string $accountNumber,
private readonly bool $sandbox = false,
) {}
public function code(): string
{
return 'dhl';
}
public function name(): string
{
return 'DHL Express';
}
public function logo(): ?string
{
return asset('images/carriers/dhl.svg');
}
public function isConfigured(): bool
{
return filled($this->apiKey) && filled($this->accountNumber);
}
public function supportsLabels(): bool
{
return false;
}
public function supportsTracking(): bool
{
return false;
}
public function calculateRates(Address $from, Address $to, array $packages): Collection
{
if (! $this->isConfigured()) {
throw ShippingException::notConfigured('dhl');
}
$packages = $this->normalizePackages($packages);
$response = Http::withHeaders([
'DHL-API-Key' => $this->apiKey,
])->post($this->getApiUrl().'/rates', [
'accountNumber' => $this->accountNumber,
'originAddress' => $this->formatAddress($from),
'destinationAddress' => $this->formatAddress($to),
'packages' => $this->formatPackages($packages),
]);
if ($response->failed()) {
throw ShippingException::apiError('dhl', $response->body());
}
return collect($response->json('products'))->map(fn (array $product) => new ShippingRate(
serviceCode: $product['productCode'],
serviceName: $product['productName'],
amount: is_no_division_currency($product['priceCurrency'])
? (int) $product['totalPrice']
: (int) round($product['totalPrice'] * 100),
currency: $product['priceCurrency'],
carrierCode: 'dhl',
estimatedDays: $product['deliveryCapabilities']['estimatedDeliveryDays'] ?? null,
));
}
private function getApiUrl(): string
{
return $this->sandbox
? 'https://express.api.dhl.com/mydhlapi/test'
: 'https://express.api.dhl.com/mydhlapi';
}
private function formatAddress(Address $address): array
{
return [
'postalCode' => $address->postalCode,
'cityName' => $address->city,
'countryCode' => $address->country,
];
}
private function formatPackages(array $packages): array
{
return array_map(fn (Package $p) => [
'weight' => $p->weight,
'dimensions' => [
'length' => $p->length,
'width' => $p->width,
'height' => $p->height,
],
], $packages);
}
}The Driver Contract
The ShippingDriver contract defines the following methods:
| Method | Return | Description |
|---|---|---|
code() | string | Unique identifier for the driver |
name() | string | Human-readable name displayed in the admin |
logo() | ?string | URL to the carrier's logo |
isConfigured() | bool | Whether required credentials are set |
supportsRealTimeRates() | bool | Whether the driver can fetch rates from an API |
supportsLabels() | bool | Whether the driver can generate shipping labels |
supportsTracking() | bool | Whether the driver can track shipments |
calculateRates() | Collection | Get shipping rates for the given addresses and packages |
createShipment() | Shipment | Create a shipment and get the label |
track() | TrackingInfo | Get tracking information for a shipment |
The abstract Driver class provides default implementations for logo() (returns null), supportsRealTimeRates(), supportsLabels(), and supportsTracking() (all return true), and throws ShippingException::notSupported() for createShipment() and track(). Override these methods as needed for your driver: a driver that keeps the default createShipment() and track() should return false from supportsLabels() and supportsTracking(). None of the built-in drivers creates labels or tracks shipments: their createShipment() and track() throw ShippingException::notSupported().
The amount of a ShippingRate is an integer in cents. Convert the decimal price of a carrier API with round() and skip the multiplication for zero-decimal currencies (is_no_division_currency()), as the built-in drivers do. See zero-decimal currencies.
Registering the Driver
Register your custom driver in a service provider using the extend method on the Shipping facade. Add the provider to bootstrap/providers.php, or put the extend call in the boot() method of your AppServiceProvider:
namespace App\Providers;
use App\Shipping\Drivers\DhlDriver;
use Illuminate\Support\ServiceProvider;
use Shopper\Shipping\Facades\Shipping;
class ShippingServiceProvider extends ServiceProvider
{
public function boot(): void
{
Shipping::extend('dhl', function (): DhlDriver {
$config = config('shopper.shipping.drivers.dhl', []);
return new DhlDriver(
apiKey: $config['credentials']['api_key'] ?? '',
accountNumber: $config['credentials']['account_number'] ?? '',
sandbox: $config['sandbox'] ?? false,
);
});
}
}The closure receives the driver name as a parameter and must return an instance of ShippingDriver. Drivers are resolved lazily, meaning the closure is only called when the driver is first accessed.
Adding Configuration
Add your driver configuration to config/shopper/shipping.php:
'drivers' => [
// ... existing drivers
'dhl' => [
'enabled' => env('SHIPPING_DHL_ENABLED', false),
'sandbox' => env('SHIPPING_SANDBOX', false),
'credentials' => [
'api_key' => env('DHL_API_KEY'),
'account_number' => env('DHL_ACCOUNT_NUMBER'),
],
],
],Once registered, your driver appears automatically in the carrier form dropdown and can be assigned to carriers like any built-in driver.
Driver Capabilities
The abstract Driver class provides a normalizePackages() helper method that converts between metric and imperial units. This is useful since different carriers expect different unit systems:
public function calculateRates(Address $from, Address $to, array $packages): Collection
{
$packages = $this->normalizePackages($packages, 'imperial');
// ...
}Pass 'metric' for carriers expecting centimeters and kilograms, or 'imperial' for those expecting inches and pounds.
Relationships
Carrier Options
$carrier->options;
$carrier->options()->enabled()->get();
$carrier->options()->create([
'name' => 'Express Delivery',
'price' => 1500,
'zone_id' => $zoneId,
'is_enabled' => true,
]);Zones
The HasZones trait links a carrier to zones through the zone_has_relations pivot table. CarrierRateService::getRatesForZone() only uses carriers attached to the zone, and the admin shipping option form only lists them (see zone carriers):
$carrier->zones;
$carrier->zones()->attach($zoneId);Zone (CarrierOption)
$option->zone;
CarrierOption::query()
->where('zone_id', $zoneId)
->enabled()
->get();Carrier (CarrierOption)
$option->carrier;
$option->isEnabled();Query Scopes
use Shopper\Core\Models\Carrier;
use Shopper\Core\Models\CarrierOption;
Carrier::query()->enabled()->get();
CarrierOption::query()->enabled()->get();Price Handling
CarrierOption prices are stored in cents:
$option = CarrierOption::query()->create([
'name' => 'Standard Shipping',
'price' => 1000,
'zone_id' => $zoneId,
'carrier_id' => $carrierId,
]);
shopper_money_format($option->price, $zone->currency->code);1000 is 10.00 in a currency with cents. For a zero-decimal currency such as XAF or JPY, the price is stored in whole units and shopper_money_format() does not divide it (see zero-decimal currencies).
Creating Carriers
Manual Carrier
For carriers where you define rates manually in the database:
use Shopper\Core\Models\Carrier;
$carrier = Carrier::query()->create([
'name' => 'Local Delivery',
'slug' => 'local-delivery',
'description' => 'Same-day delivery within city limits',
'is_enabled' => true,
]);
$carrier->zones()->attach($localZoneId);
$carrier->options()->createMany([
[
'name' => 'Standard',
'price' => 500,
'zone_id' => $localZoneId,
'is_enabled' => true,
],
[
'name' => 'Express (2 hours)',
'price' => 1500,
'zone_id' => $localZoneId,
'is_enabled' => true,
],
]);API-Connected Carrier
For carriers using a shipping driver to fetch real-time rates:
$carrier = Carrier::query()->create([
'name' => 'UPS',
'slug' => 'ups',
'driver' => 'ups',
'link_url' => 'https://ups.com',
'is_enabled' => true,
]);
$carrier->zones()->attach($nationalZoneId);With an API driver whose credentials are set, you don't need to create CarrierOption records. Rates are fetched directly from the carrier's API when needed. Until the credentials are set, the carrier falls back to its CarrierOption records.
Free Shipping Option
$freeShipping = Carrier::query()->create([
'name' => 'Free Shipping',
'slug' => 'free-shipping',
'description' => 'Free standard shipping',
'is_enabled' => true,
]);
$freeShipping->zones()->attach($domesticZoneId);
$freeShipping->options()->create([
'name' => 'Free Standard Delivery',
'price' => 0,
'zone_id' => $domesticZoneId,
'is_enabled' => true,
'metadata' => [
'min_order_amount' => 5000,
'estimated_days' => '5-7',
],
]);Shopper stores metadata as is and never reads these keys: your checkout must hide the option when the cart total is below min_order_amount (in cents) and display estimated_days itself.
Retrieving Carriers
use Shopper\Core\Models\Carrier;
use Shopper\Core\Models\CarrierOption;
$carriers = Carrier::query()
->enabled()
->with(['options' => fn ($q) => $q->enabled()])
->get();
$carrier = Carrier::query()
->where('slug', 'fedex')
->first();
$carrier = Carrier::findBySlug('fedex');
$options = CarrierOption::query()
->where('zone_id', $zoneId)
->enabled()
->with('carrier')
->orderBy('price')
->get();
$cheapest = CarrierOption::query()
->where('zone_id', $zoneId)
->enabled()
->orderBy('price')
->first();findBySlug() comes from the HasSlug trait and throws a ModelNotFoundException when no carrier has that slug.
Working with Orders
use Shopper\Core\Enum\ShipmentStatus;
use Shopper\Core\Models\Order;
use Shopper\Core\Models\OrderShipping;
$order->shippingOption;
$order->shippings;
OrderShipping::query()->create([
'order_id' => $order->id,
'carrier_id' => $carrierId,
'status' => ShipmentStatus::Pending,
'tracking_number' => 'TRACK123456',
'tracking_url' => 'https://fedex.com/track/TRACK123456',
]);shippingOption is the CarrierOption the customer picked (shipping_option_id on the order), and shippings are the order's shipments. Create a shipment with the Pending status: shipped_at is set when you record the carrier pickup (see Creating Shipments).
Storefront Example
Checkout Shipping Selection
The origin address for shipping calculations should come from your store's inventory (warehouse). Shopper uses the Inventory model to represent physical locations where products are stored and shipped from.
namespace App\Http\Controllers;
use Shopper\Cart\Facades\Cart;
use Shopper\Cart\Models\Cart as CartModel;
use Shopper\Cart\Models\CartAddress;
use Shopper\Cart\Models\CartLine;
use Shopper\Core\Enum\Dimension\Weight;
use Shopper\Core\Models\Inventory;
use Shopper\Core\Models\Zone;
use Shopper\Shipping\Services\CarrierRateService;
use Shopper\Shipping\DataTransferObjects\Address;
use Shopper\Shipping\DataTransferObjects\Package;
class CheckoutController extends Controller
{
public function __construct(
private readonly CarrierRateService $rateService,
) {}
public function showShipping(?int $inventoryId = null)
{
$cart = Cart::current() ?? abort(404);
$address = $cart->shippingAddress() ?? abort(404);
$inventory = $this->getShippingInventory($inventoryId);
$zone = $this->getCustomerZone($cart, $address);
$from = $this->getInventoryAddress($inventory);
$to = $this->getCustomerAddress($address);
$packages = $this->getCartPackages($cart);
$shippingOptions = $this->rateService->getRatesForZone(
zone: $zone,
from: $from,
to: $to,
packages: $packages,
);
return view('checkout.shipping', compact('shippingOptions'));
}
private function getShippingInventory(?int $inventoryId = null): Inventory
{
if ($inventoryId) {
return Inventory::query()->findOrFail($inventoryId);
}
return Inventory::query()->default()->firstOrFail();
}
private function getInventoryAddress(Inventory $inventory): Address
{
return new Address(
firstName: $inventory->name,
lastName: '',
street: $inventory->street_address,
street2: $inventory->street_address_plus,
city: $inventory->city,
postalCode: $inventory->postal_code,
state: $inventory->state ?? '',
country: $inventory->country->cca2,
phone: $inventory->phone_number,
email: $inventory->email,
);
}
private function getCustomerAddress(CartAddress $address): Address
{
return new Address(
firstName: $address->first_name ?? '',
lastName: $address->last_name,
street: $address->address_1,
city: $address->city,
postalCode: $address->postal_code,
state: $address->state ?? '',
country: $address->country->cca2,
company: $address->company,
street2: $address->address_2,
phone: $address->phone,
);
}
private function getCartPackages(CartModel $cart): array
{
$weight = $cart->lines()->with('purchasable')->get()->sum(
fn (CartLine $line): float => $this->weightInKilograms($line) * $line->quantity
);
return [
new Package(
length: 40,
width: 30,
height: 20,
weight: $weight,
),
];
}
private function weightInKilograms(CartLine $line): float
{
$value = (float) $line->purchasable->weight_value;
return match ($line->purchasable->weight_unit) {
Weight::G => $value / 1000,
Weight::LBS => $value * 0.453592,
default => $value,
};
}
private function getCustomerZone(CartModel $cart, CartAddress $address): Zone
{
return $cart->zone ?? Zone::query()
->enabled()
->whereHas('countries', fn ($query) => $query->whereKey($address->country_id))
->firstOrFail();
}
}Products and variants have their own dimensions (width_value, height_value, depth_value), but adding them up does not give the size of a box. This example ships everything in one 40 x 30 x 20 cm box and sums the weights (weight_value converted from weight_unit). Replace the box with your own packing rules.
If your store has multiple warehouses, you can pass the inventory ID to ship from a specific location. This is useful for selecting the nearest warehouse to the customer or the one with available stock:
return redirect()->route('checkout.shipping', ['inventoryId' => $nearestInventory->id]);Use Cases
| Carrier | Options |
|---|---|
| USPS | Priority Mail, Ground Advantage, Media Mail |
| FedEx | Ground, Express, Overnight |
| UPS | Ground, 2-Day, Next Day Air |
| DHL | Express, Economy, Freight |
| Local | Same-Day, Pick-up |
| Scenario | Implementation |
|---|---|
| Flat rate shipping | Manual carrier with single option at fixed price |
| Free shipping threshold | Store min_order_amount in the option's metadata and check it in your checkout |
| Zone-based pricing | Create options per zone for manual carriers |
| Real-time rates | Assign a shipping driver to the carrier and set the driver's credentials |
| Hybrid approach | Manual carriers for local, API drivers for national/international |
Last updated on
Edit on GitHub