Skip to content

Customers

Complete reference for the User model, addresses, and customer management in Shopper.

Customers are users who have the customer role (user by default, set in shopper.admin.roles.user) and can place orders in your store. Shopper extends your Laravel User model with e-commerce specific fields and relationships.

User Model Integration

Shopper doesn't create a separate Customer model. Instead, it extends your existing App\Models\User model (the model set in auth.providers.users.model) with the InteractsWithShopper trait and ShopperUser contract.

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Shopper\Models\Contracts\ShopperUser;
use Shopper\Traits\InteractsWithShopper;

class User extends Authenticatable implements ShopperUser
{
    use InteractsWithShopper;
    use Notifiable;

    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
        'gender',
        'phone_number',
        'birth_date',
        'avatar_type',
        'avatar_location',
        'opt_in',
        'email_verified_at',
        'last_login_ip',
    ];
}

The admin customer form, the anonymize action and the admin profile page write users with Eloquent's create() and update(), and Laravel ignores every attribute that is not fillable. Declare the columns above as fillable. The Shopper migration renames the name column of the Laravel skeleton to last_name, so name leaves the list. Keep the skeleton's Notifiable trait: the admin uses it to email their credentials to a new customer.

The InteractsWithShopper trait provides:

  • HasRoles (Spatie Permission) for role-based access control
  • HasDiscounts for customer-specific discount eligibility, through the discounts() relation
  • HasProfilePhoto for avatar management, through the picture attribute

It also casts birth_date, email_verified_at and last_login_at to Carbon dates, gender to GenderType and opt_in to a boolean.

Database Schema

User Table Modifications

Shopper's migrations modify the standard Laravel users table: they rename name to last_name, make password nullable and add the other columns below.

ColumnTypeNullableDefaultDescription
idbigintnoautoPrimary key
first_namestringyesnullFirst name
last_namestringno-Last name (the name column of the Laravel skeleton, renamed)
emailstringno-Email address (unique)
passwordstringyesnullPassword (nullable for social auth)
store_two_factor_secrettextyesnullEncrypted two-factor secret, see Two-Factor Authentication
store_two_factor_recovery_codestextyesnullEncrypted two-factor recovery codes
email_verified_attimestampyesnullEmail verification date
genderstringyesnullGender enum value
phone_numberstringyesnullPhone number
birth_datedateyesnullBirth date
avatar_typestringnoavatar_uiavatar_ui (generated from the name) or storage (uploaded file)
avatar_locationstringyesnullAvatar file path
timezonestringyesnullUser timezone
opt_inbooleannofalseMarketing email consent
last_login_attimestampyesnullLast login timestamp
last_login_ipstringyesnullLast login IP address

Address Table

Addresses are stored in the sh_user_addresses table (sh_ is the default table prefix):

ColumnTypeNullableDefaultDescription
idbigintnoautoPrimary key
first_namestringno-First name
last_namestringno-Last name
company_namestringyesnullCompany name
street_addressstringno-Street address
street_address_plusstringyesnullAdditional address line
postal_codestringno-Postal/ZIP code
citystringno-City
statestringyesnullState/province/region
phone_numberstringyesnullPhone number
shipping_defaultbooleannofalseDefault shipping address
billing_defaultbooleannofalseDefault billing address
typestringyesnullAddress type enum
metadatajsonbyesnullExtra JSON data (the model has no cast for it: add an array cast in a custom Address model)
country_idbigintyesnullFK to countries (set to null when the country is deleted)
user_idbigintno-FK to users (the address is deleted with the user)

Gender Type

The GenderType enum defines available gender options:

use Shopper\Core\Enum\GenderType;

GenderType::Male    // male
GenderType::Female  // female

GenderType::Male->getLabel(); // "Male", translated

Address Type

The AddressType enum defines address categories:

use Shopper\Core\Enum\AddressType;

AddressType::Billing   // billing
AddressType::Shipping  // shipping

AddressType::Billing->getLabel(); // "Billing Address", translated

Relationships

Orders

orders() returns the orders whose customer_id is the user's ID, using the model set in shopper.models.order.

// Get all customer orders
$customer->orders; // Collection of Order models

// Get recent orders
$customer->orders()
    ->latest()
    ->take(5)
    ->get();

Addresses

// Get all customer addresses
$customer->addresses; // Collection of Address models

// Get default shipping address
$customer->addresses()
    ->where('shipping_default', true)
    ->first();

// Get default billing address
$customer->addresses()
    ->where('billing_default', true)
    ->first();

Query Scopes

use App\Models\User;

// Get only customers (users with the shopper.admin.roles.user role)
User::query()->customers()->get();

// Get administrators (shopper.admin.roles.admin or shopper.admin.roles.manager role)
User::query()->administrators()->get();

Role Checking

// Check if user has the shopper.admin.roles.admin role
$user->isAdmin();

// Check if user has the shopper.admin.roles.manager role
$user->isManager();

// Check if user can open the admin panel: admin, manager, or the access_dashboard permission
$user->canAccessDashboard();

// Check if email is verified
$user->isVerified();

Computed Attributes

// Get full name (the last name alone when first_name is empty)
$customer->full_name; // "John Doe"

// Get the birth date text shown in the admin ("Not defined" when empty)
$customer->birth_date_formatted;

// Format the birth date yourself: it is cast to a Carbon instance
$customer->birth_date?->isoFormat('LL'); // "January 15, 1990"

// Get role display names as a comma-separated string ("N/A" without roles)
$customer->roles_label; // "User, VIP"

// Get profile picture URL
$customer->picture; // Avatar URL (ui-avatars or uploaded)

Address Model

The model used is Shopper\Core\Models\Address. It implements Shopper\Core\Models\Contracts\Address and is configurable via config/shopper/models.php.

Extending the Address Model

namespace App\Models;

use Shopper\Core\Models\Address as BaseAddress;

class Address extends BaseAddress
{
    // Add your customizations here
}

Your class must extend Shopper\Core\Models\Address: Shopper throws a Shopper\Core\Exceptions\InvalidModelConfigurationException otherwise. Set the address key in config/shopper/models.php and keep the other keys:

return [
    'address' => \App\Models\Address::class,
];

Address Relationships

Each address belongs to a user and optionally to a country:

$address->user;    // The customer who owns this address
$address->country; // The Country model (nullable)

Address Methods

The Address model provides helpers for checking default status:

$address->isShippingDefault(); // true if this is the default shipping address
$address->isBillingDefault();  // true if this is the default billing address
$address->full_name;           // "John Doe" (computed from first_name + last_name)

Creating Customers

Basic Customer

use App\Models\User;
use Shopper\Core\Enum\GenderType;
use Illuminate\Support\Facades\Hash;

$customer = User::query()->create([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => 'john@example.com',
    'password' => Hash::make('password'),
    'gender' => GenderType::Male,
    'email_verified_at' => now(),
]);

// Assign customer role
$customer->assignRole(config('shopper.admin.roles.user'));

These calls need the fillable columns listed in User Model Integration.

Customer with Address

use App\Models\User;
use Shopper\Core\Enum\AddressType;
use Shopper\Core\Enum\GenderType;
use Shopper\Core\Models\Country;

$customer = User::query()->create([
    'first_name' => 'Jane',
    'last_name' => 'Doe',
    'email' => 'jane@example.com',
    'gender' => GenderType::Female,
    'phone_number' => '+1234567890',
    'opt_in' => true,
]);

$customer->assignRole(config('shopper.admin.roles.user'));

// Add shipping address
$customer->addresses()->create([
    'first_name' => 'Jane',
    'last_name' => 'Doe',
    'street_address' => '123 Main Street',
    'city' => 'New York',
    'state' => 'NY',
    'postal_code' => '10001',
    'country_id' => Country::query()->where('cca2', 'US')->value('id'),
    'type' => AddressType::Shipping,
    'shipping_default' => true,
]);

Retrieving Customers

use App\Models\User;

// Get all customers
$customers = User::query()
    ->customers()
    ->latest()
    ->get();

// Search customers
$customers = User::query()
    ->customers()
    ->where(function ($query) use ($search) {
        $query->where('first_name', 'like', "%{$search}%")
            ->orWhere('last_name', 'like', "%{$search}%")
            ->orWhere('email', 'like', "%{$search}%");
    })
    ->get();

// Get customer with addresses and orders
$customer = User::query()
    ->with(['addresses', 'orders'])
    ->findOrFail($id);

// Get customers who opted in for marketing
$marketingList = User::query()
    ->customers()
    ->where('opt_in', true)
    ->get();

// Get verified customers only
$verified = User::query()
    ->customers()
    ->whereNotNull('email_verified_at')
    ->get();

Managing Addresses

use Shopper\Core\Enum\AddressType;
use Shopper\Core\Models\Address;

// Create address for customer
$address = Address::query()->create([
    'user_id' => $customer->id,
    'first_name' => 'John',
    'last_name' => 'Doe',
    'street_address' => '456 Oak Avenue',
    'city' => 'Los Angeles',
    'postal_code' => '90001',
    'country_id' => $countryId,
    'type' => AddressType::Billing,
    'billing_default' => true,
]);

// Make another address the default shipping address:
// the observer removes the flag from the previous default
$newDefault = Address::query()->find($addressId);
$newDefault->update(['shipping_default' => true]);

Observer Behavior

When a user is deleted, the InteractsWithShopper trait automatically:

  • Detaches all roles
  • Deletes all addresses
// When deleting a user:
$customer->delete();
// Roles are detached and addresses are deleted automatically

Orders are kept: the database sets their customer_id to null.

Shopper\Core\Observers\AddressObserver runs when an address is created or updated. When the address has shipping_default set, the observer removes the flag from the customer's previous default shipping address, and it does the same for billing_default. The flags are exclusive per customer whatever the address type.

Role Configuration

Roles are defined in config/shopper/admin.php:

return [
    'roles' => [
        'admin' => 'administrator',
        'manager' => 'manager',
        'user' => 'user',
    ],
];

The Shopper seeder creates the three roles with these names, so set them before you seed.

Permissions

The admin panel generates five permissions for customer management:

PermissionDescription
browse_customersView the customers list
read_customersView a single customer profile
add_customersCreate new customers
edit_customersGenerated for your own screens: the 2.x customer page is read-only and does not check it
delete_customersAnonymize a customer (the admin has no delete action)

Anonymizing replaces the first and last names with "Deleted" and "Customer" (translated) and the email with an @anonymized.local address, clears the phone number, avatar, birth date and last login IP, turns opt_in off and deletes the customer's addresses. Orders are kept.

Components

To customize the admin UI for customer management:

php artisan shopper:component:publish customer

Creates config/shopper/components/customer.php:

use Shopper\Livewire;
use Shopper\Livewire\Components;

return [
    'pages' => [
        'customer-index' => Livewire\Pages\Customers\Index::class,
        'customer-create' => Livewire\Pages\Customers\Create::class,
        'customer-show' => Livewire\Pages\Customers\Show::class,
    ],
    'components' => [
        'customers.addresses' => Components\Customers\Addresses::class,
        'customers.orders' => Components\Customers\Orders::class,
        'customers.profile' => Components\Customers\Profile::class,
    ],
];

Storefront Example

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Shopper\Core\Enum\AddressType;
use Shopper\Core\Models\Country;

class AccountController extends Controller
{
    public function show()
    {
        $customer = auth()->user();

        return view('account.show', [
            'customer' => $customer,
            'orders' => $customer->orders()->latest()->paginate(10),
            'addresses' => $customer->addresses,
        ]);
    }

    public function updateProfile(Request $request)
    {
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'phone_number' => 'nullable|string|max:20',
            'birth_date' => 'nullable|date',
            'opt_in' => 'boolean',
        ]);

        auth()->user()->update($validated);

        return back()->with('success', 'Profile updated successfully');
    }

    public function storeAddress(Request $request)
    {
        $validated = $request->validate([
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'street_address' => 'required|string',
            'city' => 'required|string',
            'postal_code' => 'required|string',
            'country_id' => ['required', Rule::exists(Country::class, 'id')],
            'type' => 'required|in:billing,shipping',
        ]);

        auth()->user()->addresses()->create([
            ...$validated,
            'type' => AddressType::from($validated['type']),
        ]);

        return back()->with('success', 'Address added successfully');
    }
}

Use Cases

ScopeDescription
customers()Users with 'user' role
administrators()Users with 'admin' or 'manager' role
MethodDescription
isAdmin()Check if user has admin role
isManager()Check if user has manager role
canAccessDashboard()Check if user is an admin, a manager, or has the access_dashboard permission
isVerified()Check if email is verified

Last updated on

Edit on GitHub