rawaby88/muid

Laravel package for generating prefixed, validatable unique identifiers similar to Stripe's ID format

Maintainers

Details

github.com/rawaby88/muid

Source

Issues

Installs: 417

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/rawaby88/muid

v5.0.2 2026-01-19 09:28 UTC

This package is auto-updated.

Last update: 2026-01-19 09:53:14 UTC


README

A Laravel package for generating prefixed, validatable unique identifiers similar to Stripe's ID format.

┌─────────────────────────────────────────────────────────────────────────┐
│                           MUID FORMAT OVERVIEW                          │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  ORDERED (time-sortable, like Stripe)                                   │
│  ┌──────┬───┬──────────┬─────────────────────────┐                      │
│  │ usr  │ _ │ 2HNtGjK8 │ mX4pQ7rS9vWxYz1234     │  → VARCHAR(36)       │
│  └──────┴───┴──────────┴─────────────────────────┘                      │
│  prefix(4) │ timestamp(8) │ random(23)                                  │
│                                                                         │
│  PADDED (human-readable sequential)                                     │
│  ┌──────┬───┬───────────┐                                               │
│  │ inv  │ _ │ 0000042   │  → BIGINT (stores: 42)                        │
│  └──────┴───┴───────────┘                                               │
│  prefix(3) │ padded sequence(7)                                         │
│                                                                         │
│  INCREMENTAL (simple sequential)                                        │
│  ┌──────┬───┬────┐                                                      │
│  │ ord  │ _ │ 42 │  → BIGINT (stores: 42)                               │
│  └──────┴───┴────┘                                                      │
│  prefix(3) │ sequence                                                   │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

Table of Contents

Installation

composer require rawaby88/muid

Publish the configuration:

php artisan vendor:publish --tag=muid-config

Quick Comparison

Aspect HasMuid (Ordered) HasIntegerMuid (Padded/Incremental)
Database Type VARCHAR(36) BIGINT AUTO_INCREMENT
Example ID usr_2HNtGjK8mX4pQ7rS inv_0000042
Storage in DB usr_2HNtGjK8mX4pQ7rS 42
Generated By PHP (timestamp + random) Database (auto-increment)
Race Conditions None (unique by design) None (DB handles it)
Sortable Yes (time-based) Yes (sequential)
Human Readable No Yes
Best For Users, Products, Posts Invoices, Orders, Tickets

Strategy Overview

Available Strategies

┌─────────────────────────────────────────────────────────────────────────────┐
│                              MUID STRATEGIES                                 │
├─────────────────┬───────────────┬──────────────┬────────────────────────────┤
│ Strategy        │ Trait         │ Storage      │ Output Example             │
├─────────────────┼───────────────┼──────────────┼────────────────────────────┤
│ ordered         │ HasMuid       │ VARCHAR(36)  │ usr_2HNtGjK8mX4pQ7rS9vWx   │
│ incremental     │ HasIntegerMuid│ BIGINT       │ ord_1, ord_2, ord_3        │
│ padded          │ HasIntegerMuid│ BIGINT       │ inv_0000001, inv_0000002   │
└─────────────────┴───────────────┴──────────────┴────────────────────────────┘

How Each Strategy Stores Data

Ordered Strategy (HasMuid)

┌──────────────────────────────────────────────────────────────┐
│                    DATABASE TABLE: users                      │
├──────────────────────────────────┬───────────────────────────┤
│ id (VARCHAR 36)                  │ name                      │
├──────────────────────────────────┼───────────────────────────┤
│ usr_2HNtGjK8mX4pQ7rS9vWx         │ John Doe                  │
│ usr_2HNtGjL3nY5qR8sT0uVy         │ Jane Smith                │
│ usr_2HNtGjM9oZ6rS9tU1vWz         │ Bob Wilson                │
└──────────────────────────────────┴───────────────────────────┘
                    ↓
         What you see in PHP:
         $user->id = "usr_2HNtGjK8mX4pQ7rS9vWx"

Incremental Strategy (HasIntegerMuid)

┌──────────────────────────────────────────────────────────────┐
│                    DATABASE TABLE: orders                     │
├──────────────────────────────────┬───────────────────────────┤
│ id (BIGINT AUTO_INCREMENT)       │ total                     │
├──────────────────────────────────┼───────────────────────────┤
│ 1                                │ 99.99                     │
│ 2                                │ 149.50                    │
│ 3                                │ 75.00                     │
└──────────────────────────────────┴───────────────────────────┘
                    ↓
         What you see in PHP:
         $order->id   = 1           (raw integer)
         $order->muid = "ord_1"     (formatted with prefix)

Padded Strategy (HasIntegerMuid)

┌──────────────────────────────────────────────────────────────┐
│                   DATABASE TABLE: invoices                    │
├──────────────────────────────────┬───────────────────────────┤
│ id (BIGINT AUTO_INCREMENT)       │ amount                    │
├──────────────────────────────────┼───────────────────────────┤
│ 1                                │ 500.00                    │
│ 2                                │ 1250.00                   │
│ 42                               │ 899.99                    │
└──────────────────────────────────┴───────────────────────────┘
                    ↓
         What you see in PHP:
         $invoice->id   = 42              (raw integer)
         $invoice->muid = "inv_0000042"   (formatted with padding)

HasMuid Trait (String-based)

When to Use

Use HasMuid for:

  • User accounts
  • Products / Items
  • Posts / Articles
  • Comments
  • Any entity that needs globally unique IDs
  • Distributed systems
  • When you need time-sortable IDs

Basic Usage

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Rawaby88\Muid\Concerns\HasMuid;

class User extends Model
{
    use HasMuid;

    public function muidPrefix(): string
    {
        return 'usr';
    }
}

Migration

Schema::create('users', function (Blueprint $table) {
    $table->primaryMuid();           // VARCHAR(36) primary key
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});

What Gets Created

$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

echo $user->id;  // "usr_2HNtGjK8mX4pQ7rS9vWx"

Anatomy of an Ordered MUID

                    MUID STRUCTURE (Standard 36 chars)
┌─────────────────────────────────────────────────────────────────┐
│                                                                 │
│   usr_2HNtGjK8mX4pQ7rS9vWxYz1234                               │
│   └─┬─┘└───┬───┘└─────────┬─────────┘                          │
│     │      │              │                                     │
│  Prefix  Timestamp     Random                                   │
│  (2-8)   (8 chars)    (remaining)                              │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Component Breakdown:
┌──────────┬────────┬─────────────────────────────────────────────┐
│ Part     │ Length │ Description                                 │
├──────────┼────────┼─────────────────────────────────────────────┤
│ Prefix   │ 2-8    │ Model identifier (usr, prod, cus)           │
│ _        │ 1      │ Separator                                   │
│ Timestamp│ 8      │ Base62 encoded milliseconds (sortable)      │
│ Random   │ varies │ Cryptographically random Base62 chars       │
└──────────┴────────┴─────────────────────────────────────────────┘

Example with 'user' prefix (36 char max):
┌──────┬───┬──────────┬─────────────────────────┐
│ user │ _ │ r8c5ray3 │ DxmcNs59NDmVUD76ogiKXpH │
├──────┼───┼──────────┼─────────────────────────┤
│ 4    │ 1 │ 8        │ 23                      │ = 36 chars total
└──────┴───┴──────────┴─────────────────────────┘
   ↑              ↑              ↑
Prefix      Timestamp       Random Bits
(blue)      (green)         (yellow)

Customization Options

class Product extends Model
{
    use HasMuid;

    // Custom prefix (2-8 characters)
    public function muidPrefix(): string
    {
        return 'prod';
    }

    // Custom max length (affects body size)
    public function muidMaxLength(): int
    {
        return 24;  // Shorter IDs: prod_2HNtGjK8mX4pQ7
    }

    // Which columns get MUIDs
    public function muidColumns(): array
    {
        return ['id', 'public_id'];  // Multiple MUID columns
    }
}

Size Variations

Size Max Length Example Use Case
Standard 36 chars usr_2HNtGjK8mX4pQ7rS9vWxYz Default, most cases
Small 24 chars usr_2HNtGjK8mX4pQ7rS When storage matters
Tiny 16 chars usr_2HNtGjK8mX Short URLs, codes
// In your model
public function muidMaxLength(): int
{
    return config('muid.lengths.small');  // 24
}

// Or use different migration macros
$table->primarySmallMuid();  // 24 chars
$table->primaryTinyMuid();   // 16 chars

HasIntegerMuid Trait (Integer-based)

When to Use

Use HasIntegerMuid for:

  • Invoice numbers
  • Order numbers
  • Ticket numbers
  • Reference numbers
  • Any sequential, human-readable IDs
  • When customers need to reference IDs verbally

Basic Usage

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Rawaby88\Muid\Concerns\HasIntegerMuid;

class Invoice extends Model
{
    use HasIntegerMuid;

    public function muidPrefix(): string
    {
        return 'inv';
    }

    public function muidStrategy(): string
    {
        return 'padded';  // or 'incremental'
    }

    public function muidPaddingLength(): int
    {
        return 7;  // inv_0000001
    }
}

Migration

Schema::create('invoices', function (Blueprint $table) {
    $table->primaryIntegerMuid();  // BIGINT AUTO_INCREMENT
    $table->decimal('amount', 10, 2);
    $table->timestamps();
});

Incremental vs Padded

┌─────────────────────────────────────────────────────────────┐
│                    INCREMENTAL STRATEGY                      │
├─────────────────────────────────────────────────────────────┤
│  Database: 1, 2, 3, 42, 100, 1000                           │
│  Display:  ord_1, ord_2, ord_3, ord_42, ord_100, ord_1000   │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                      PADDED STRATEGY                         │
├─────────────────────────────────────────────────────────────┤
│  Database: 1, 2, 3, 42, 100, 1000                           │
│  Display:  inv_0000001, inv_0000002, inv_0000003,           │
│            inv_0000042, inv_0000100, inv_0001000            │
└─────────────────────────────────────────────────────────────┘

Anatomy of Integer MUIDs

               INCREMENTAL MUID STRUCTURE
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   ord_42                                                    │
│   └─┬─┘└┬┘                                                  │
│     │   │                                                   │
│  Prefix Sequence                                            │
│  (2-8)  (integer)                                           │
│                                                             │
│   Database stores: 42 (BIGINT)                              │
│   Display shows:   ord_42                                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

                 PADDED MUID STRUCTURE
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   inv_0000042                                               │
│   └─┬─┘└──┬───┘                                             │
│     │     │                                                 │
│  Prefix  Padded Sequence                                    │
│  (2-8)   (zero-padded integer)                              │
│                                                             │
│   Database stores: 42 (BIGINT)                              │
│   Display shows:   inv_0000042 (padded to 7 digits)         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Component Breakdown:
┌───────────┬─────────────┬───────────────────────────────────┐
│ Part      │ Incremental │ Padded                            │
├───────────┼─────────────┼───────────────────────────────────┤
│ Prefix    │ ord         │ inv                               │
│ Separator │ _           │ _                                 │
│ Sequence  │ 42          │ 0000042 (padding_length: 7)       │
├───────────┼─────────────┼───────────────────────────────────┤
│ DB Value  │ 42          │ 42                                │
│ Display   │ ord_42      │ inv_0000042                       │
└───────────┴─────────────┴───────────────────────────────────┘

Accessing the ID

$invoice = Invoice::create(['amount' => 500.00]);

// Different ways to access the ID
$invoice->id;          // 1 (raw integer from database)
$invoice->muid;        // "inv_0000001" (formatted string)
$invoice->getRawId();  // 1 (explicit raw access)

// In JSON/Array output
$invoice->toArray();
// [
//     'id' => 1,
//     'muid' => 'inv_0000001',
//     'amount' => 500.00,
//     ...
// ]

Finding Records by MUID

// All of these work:
Invoice::find(42);                    // By raw integer
Invoice::findByMuid('inv_42');        // By incremental format
Invoice::findByMuid('inv_0000042');   // By padded format

// Route model binding works with MUID strings
Route::get('/invoices/{invoice}', function (Invoice $invoice) {
    // URL: /invoices/inv_0000042
    // $invoice is resolved correctly
});

Customizing Padding

class Ticket extends Model
{
    use HasIntegerMuid;

    public function muidPrefix(): string
    {
        return 'TKT';
    }

    public function muidStrategy(): string
    {
        return 'padded';
    }

    public function muidPaddingLength(): int
    {
        return 5;  // TKT_00001, TKT_00002, etc.
    }
}

Padding Examples

Padding Length ID 1 ID 42 ID 1000
3 inv_001 inv_042 inv_1000 (overflow)
5 inv_00001 inv_00042 inv_01000
7 inv_0000001 inv_0000042 inv_0001000
10 inv_0000000001 inv_0000000042 inv_0000001000

Migration Macros

String-based Columns (for HasMuid)

Schema::create('users', function (Blueprint $table) {
    // Primary Keys
    $table->primaryMuid();                    // id VARCHAR(36) PRIMARY KEY
    $table->primaryMuid('user_id');           // Custom column name
    $table->primarySmallMuid();               // id VARCHAR(24) PRIMARY KEY
    $table->primaryTinyMuid();                // id VARCHAR(16) PRIMARY KEY

    // Regular Columns
    $table->muid('external_id');              // VARCHAR(36)
    $table->smallMuid('short_id');            // VARCHAR(24)
    $table->tinyMuid('code');                 // VARCHAR(16)

    // Foreign Keys (with index)
    $table->foreignMuid('team_id');           // VARCHAR(36) + INDEX
    $table->foreignSmallMuid('ref_id');       // VARCHAR(24) + INDEX
    $table->foreignTinyMuid('link_id');       // VARCHAR(16) + INDEX

    // Nullable
    $table->nullableMuid('parent_id');        // VARCHAR(36) NULLABLE
    $table->nullableSmallMuid('alt_id');      // VARCHAR(24) NULLABLE
    $table->nullableTinyMuid('opt_code');     // VARCHAR(16) NULLABLE

    // Polymorphic Relations
    $table->muidMorphs('taggable');           // taggable_type + taggable_id
    $table->nullableMuidMorphs('likeable');   // Nullable polymorphic
    $table->muidSmallMorphs('commentable');   // With small MUID
    $table->muidTinyMorphs('viewable');       // With tiny MUID
});

Integer-based Columns (for HasIntegerMuid)

Schema::create('invoices', function (Blueprint $table) {
    // Primary Key (auto-increment)
    $table->primaryIntegerMuid();             // id BIGINT AUTO_INCREMENT PRIMARY KEY
    $table->primaryIntegerMuid('invoice_id'); // Custom column name

    // Regular Columns
    $table->integerMuid('sequence');          // BIGINT

    // Foreign Keys (with index)
    $table->foreignIntegerMuid('order_id');   // BIGINT + INDEX

    // Nullable
    $table->nullableIntegerMuid('ref_id');    // BIGINT NULLABLE

    // Polymorphic Relations
    $table->integerMuidMorphs('trackable');   // trackable_type + trackable_id (BIGINT)
    $table->nullableIntegerMuidMorphs('auditable');
});

Column Comparison Table

Macro Type Length Index Nullable
primaryMuid() VARCHAR 36 PRIMARY No
primarySmallMuid() VARCHAR 24 PRIMARY No
primaryTinyMuid() VARCHAR 16 PRIMARY No
muid() VARCHAR 36 No No
foreignMuid() VARCHAR 36 Yes No
nullableMuid() VARCHAR 36 No Yes
primaryIntegerMuid() BIGINT - PRIMARY No
integerMuid() BIGINT - No No
foreignIntegerMuid() BIGINT - Yes No
nullableIntegerMuid() BIGINT - No Yes

Real-World Scenarios

Scenario 1: E-commerce Platform

// Users - globally unique, time-sortable
class User extends Model
{
    use HasMuid;
    public function muidPrefix(): string { return 'usr'; }
}
// Result: usr_2HNtGjK8mX4pQ7rS

// Products - globally unique
class Product extends Model
{
    use HasMuid;
    public function muidPrefix(): string { return 'prod'; }
}
// Result: prod_3JMuHkL9nY5qR8

// Orders - sequential, human-readable for customer service
class Order extends Model
{
    use HasIntegerMuid;
    public function muidPrefix(): string { return 'ORD'; }
    public function muidStrategy(): string { return 'padded'; }
    public function muidPaddingLength(): int { return 8; }
}
// Result: ORD_00000001
// Customer: "Hi, I have a question about order ORD_00000042"

// Invoices - sequential, for accounting
class Invoice extends Model
{
    use HasIntegerMuid;
    public function muidPrefix(): string { return 'INV'; }
    public function muidStrategy(): string { return 'padded'; }
    public function muidPaddingLength(): int { return 6; }
}
// Result: INV_000001

Database Schema:

-- Users table (string IDs)
CREATE TABLE users (
    id VARCHAR(36) PRIMARY KEY,  -- usr_2HNtGjK8mX4pQ7rS
    name VARCHAR(255),
    email VARCHAR(255)
);

-- Orders table (integer IDs, displayed with prefix)
CREATE TABLE orders (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,  -- 1, 2, 3...
    user_id VARCHAR(36),                    -- Reference to user
    total DECIMAL(10,2)
);

-- Invoices table (integer IDs)
CREATE TABLE invoices (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,  -- 1, 2, 3...
    order_id BIGINT,                        -- Reference to order
    amount DECIMAL(10,2)
);

Scenario 2: Support Ticket System

class Ticket extends Model
{
    use HasIntegerMuid;

    public function muidPrefix(): string
    {
        return 'TKT';
    }

    public function muidStrategy(): string
    {
        return 'padded';
    }

    public function muidPaddingLength(): int
    {
        return 6;
    }
}

Customer Interaction:

Customer: "I need help with ticket TKT_000042"
Support:  "Let me pull up TKT_000042 for you..."

// In code:
$ticket = Ticket::findByMuid('TKT_000042');
// or
$ticket = Ticket::find(42);

Scenario 3: Multi-tenant SaaS

// Tenant/Organization - unique across all tenants
class Organization extends Model
{
    use HasMuid;
    public function muidPrefix(): string { return 'org'; }
}
// Result: org_2HNtGjK8mX4pQ7rS

// Projects within an organization
class Project extends Model
{
    use HasMuid;
    public function muidPrefix(): string { return 'proj'; }
}
// Result: proj_3JMuHkL9nY5qR8

// Tasks - can use integer for simplicity within project
class Task extends Model
{
    use HasIntegerMuid;
    public function muidPrefix(): string { return 'task'; }
    public function muidStrategy(): string { return 'incremental'; }
}
// Result: task_1, task_2, task_3

Scenario 4: API with External Integrations

class Payment extends Model
{
    use HasMuid;

    public function muidPrefix(): string
    {
        return 'pay';
    }

    // Use small MUID to save bandwidth
    public function muidMaxLength(): int
    {
        return 24;
    }
}

// API Response
{
    "id": "pay_2HNtGjK8mX4pQ7rS",
    "amount": 99.99,
    "currency": "USD",
    "status": "completed"
}

Validation

Using the ValidMuid Rule

use Rawaby88\Muid\Rules\ValidMuid;

// Basic validation
$request->validate([
    'user_id' => ['required', new ValidMuid],
]);

// With specific prefix
$request->validate([
    'user_id' => ['required', ValidMuid::withPrefix('usr')],
    'order_id' => ['required', ValidMuid::withPrefix('ord')],
]);

// With specific strategy
$request->validate([
    'order_id' => ['required', ValidMuid::withStrategy('ordered')],
]);

// Combining prefix and strategy
$request->validate([
    'invoice_id' => ['required', ValidMuid::for('inv', 'padded')],
]);

Static Factory Methods

ValidMuid::make();                    // Any valid MUID
ValidMuid::withPrefix('usr');         // Must have 'usr' prefix
ValidMuid::withStrategy('ordered');   // Must be ordered strategy
ValidMuid::for('inv', 'padded');      // Specific prefix and strategy

Validation Error Messages

// Invalid format
"The user_id must be a valid MUID."

// Wrong prefix
"The user_id must be a valid MUID with prefix 'usr'."

Parsing & Extracting

Using the Muid Facade

use Rawaby88\Muid\Facades\Muid;

// Generate MUIDs
Muid::generate('usr');                    // usr_2HNtGjK8mX4pQ7rS9vWx
Muid::generate('usr', 'ordered');         // Explicit strategy
Muid::generate('usr', 'ordered', 24);     // With max length

// Size shortcuts
Muid::standard('usr');  // 36 chars
Muid::small('usr');     // 24 chars
Muid::tiny('usr');      // 16 chars

// Validation
Muid::isValid('usr_2HNtGjK8mX4pQ7rS9vWx');           // true
Muid::isValid('usr_2HNtGjK8mX4pQ7rS9vWx', 'usr');   // true (correct prefix)
Muid::isValid('usr_2HNtGjK8mX4pQ7rS9vWx', 'cus');   // false (wrong prefix)
Muid::isValid('invalid');                            // false

// Extraction
Muid::extractPrefix('usr_abc123');   // 'usr'
Muid::extractBody('usr_abc123');     // 'abc123'

Parsing MUID Components

$components = Muid::parse('usr_2HNtGjK8mX4pQ7rS9vWx');

$components->prefix;      // 'usr'
$components->body;        // '2HNtGjK8mX4pQ7rS9vWx'
$components->strategy;    // 'ordered'
$components->timestamp;   // 1705000000000 (milliseconds since epoch)
$components->random;      // 'mX4pQ7rS9vWx'

// Get as DateTime
$components->getDateTime();  // DateTimeImmutable object

// Check properties
$components->isTimeSortable();   // true (has timestamp)
$components->isIncremental();    // false (no sequence)
$components->hasSignature();     // false (signatures disabled)

// Convert to array
$components->toArray();
// [
//     'prefix' => 'usr',
//     'body' => '2HNtGjK8mX4pQ7rS9vWx',
//     'strategy' => 'ordered',
//     'timestamp' => 1705000000000,
//     'random' => 'mX4pQ7rS9vWx',
//     'signature' => null,
//     'sequence' => null,
// ]

Parsing Different Strategies

// Ordered MUID
$ordered = Muid::parse('usr_2HNtGjK8mX4pQ7rS9vWx');
$ordered->timestamp;  // 1705000000000
$ordered->sequence;   // null

// Incremental MUID
$incremental = Muid::parse('ord_42', 'incremental');
$incremental->sequence;   // 42
$incremental->timestamp;  // null

// Padded MUID
$padded = Muid::parse('inv_0000042', 'padded');
$padded->sequence;   // 42
$padded->body;       // '0000042'

Configuration

Full Configuration File

// config/muid.php
return [
    /*
    |--------------------------------------------------------------------------
    | Default Strategy
    |--------------------------------------------------------------------------
    | Options: 'ordered', 'incremental', 'padded'
    */
    'default_strategy' => 'ordered',

    /*
    |--------------------------------------------------------------------------
    | Column Lengths
    |--------------------------------------------------------------------------
    | Maximum length for string-based MUIDs (includes prefix + separator)
    */
    'lengths' => [
        'tiny' => 16,      // usr_2HNtGjK8mX (short codes)
        'small' => 24,     // usr_2HNtGjK8mX4pQ7rS (compact)
        'standard' => 36,  // usr_2HNtGjK8mX4pQ7rS9vWxYz (default)
    ],

    /*
    |--------------------------------------------------------------------------
    | Incremental Settings
    |--------------------------------------------------------------------------
    */
    'incremental' => [
        'padding_length' => 7,        // inv_0000001
        'padding_character' => '0',   // Character used for padding
        'per_prefix' => true,         // Each prefix has own sequence
    ],

    /*
    |--------------------------------------------------------------------------
    | Signature Settings (Optional)
    |--------------------------------------------------------------------------
    | Enable to add checksum validation to MUIDs
    */
    'signature' => [
        'enabled' => false,
        'length' => 4,
        'algorithm' => 'xxh64',
    ],

    /*
    |--------------------------------------------------------------------------
    | Encoding
    |--------------------------------------------------------------------------
    | 'base62': a-zA-Z0-9 (compact, case-sensitive)
    | 'base36': a-z0-9 (case-insensitive, longer)
    */
    'encoding' => [
        'type' => 'base62',
    ],

    /*
    |--------------------------------------------------------------------------
    | Prefix Rules
    |--------------------------------------------------------------------------
    */
    'prefix' => [
        'min_length' => 2,
        'max_length' => 8,
        'pattern' => '/^[a-z][a-z0-9]*$/i',
    ],
];

Encoding Comparison

Encoding Characters Case Sensitive Example
base62 0-9, A-Z, a-z Yes usr_2HNtGjK8mX
base36 0-9, a-z No usr_2hntgjk8mx

API Reference

Muid Facade Methods

Method Description Return
generate($prefix, $strategy?, $maxLength?) Generate a MUID string
standard($prefix, $strategy?) Generate 36-char MUID string
small($prefix, $strategy?) Generate 24-char MUID string
tiny($prefix, $strategy?) Generate 16-char MUID string
isValid($muid, $prefix?, $strategy?) Validate a MUID bool
parse($muid, $strategy?) Parse MUID components MuidComponents|null
extractPrefix($muid) Get prefix from MUID string|null
extractBody($muid) Get body from MUID string|null
getGenerator($strategy) Get generator instance MuidGenerator
getAvailableStrategies() List strategies array

HasMuid Trait Methods

Method Description Default
muidPrefix() Define the prefix Class basename
muidStrategy() Define the strategy 'ordered'
muidMaxLength() Define max length 36
muidColumns() Columns with MUIDs ['id']
newMuid() Generate new MUID -
isValidMuid($muid) Validate for model -

HasIntegerMuid Trait Methods

Method Description Default
muidPrefix() Define the prefix Class basename
muidStrategy() 'incremental' or 'padded' 'incremental'
muidPaddingLength() Padding for padded strategy 7
getMuidAttribute() Get formatted MUID -
getRawId() Get raw integer ID -
formatMuid($id) Format int as MUID -
parseMuid($muid) Extract int from MUID -
isValidMuid($muid) Validate for model -
findByMuid($muid) Find by MUID string -
findByMuidOrFail($muid) Find or throw -

Testing

composer test

License

MIT License. See LICENSE for details.