PHP code example of daikazu / laravel-frontdoor

1. Go to this page and download the library: Download daikazu/laravel-frontdoor library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

daikazu / laravel-frontdoor example snippets


'accounts' => [
    'driver' => 'testing',

    'drivers' => [
        'testing' => [
            'users' => [
                '[email protected]' => [
                    'name' => 'Jane Doe',
                ],
                '[email protected]' => [
                    'name' => 'John Smith',
                ],
            ],
        ],
    ],
],

'accounts' => [
    'driver' => 'testing',

    'drivers' => [
        'testing' => [
            'users' => [
                '[email protected]' => [
                    'name' => 'Admin User',
                    'phone' => '+1-555-0100',
                    'metadata' => ['role' => 'admin'],
                ],
            ],
        ],
    ],
],

'registration' => [
    'enabled' => true,
],

'accounts' => [
    'driver' => 'salesforce',

    'drivers' => [
        'salesforce' => \App\Frontdoor\SalesforceAccountDriver::class,
    ],
],

'accounts' => [
    'driver' => \App\Frontdoor\SalesforceAccountDriver::class,
],



namespace App\Frontdoor;

use App\Models\User;
use Daikazu\LaravelFrontdoor\Contracts\AccountData;
use Daikazu\LaravelFrontdoor\Contracts\AccountDriver;
use Daikazu\LaravelFrontdoor\Support\SimpleAccountData;

class DatabaseAccountDriver implements AccountDriver
{
    public function findByEmail(string $email): ?AccountData
    {
        $user = User::where('email', $email)->first();

        if (! $user) {
            return null;
        }

        return new SimpleAccountData(
            id: (string) $user->id,
            name: $user->name,
            email: $user->email,
            phone: $user->phone,
            avatarUrl: $user->avatar_url,
            metadata: ['role' => $user->role],
        );
    }

    public function exists(string $email): bool
    {
        return User::where('email', $email)->exists();
    }
}

// Named driver
'accounts' => [
    'driver' => 'database',
    'drivers' => [
        'database' => \App\Frontdoor\DatabaseAccountDriver::class,
    ],
],

// Or FQCN
'accounts' => [
    'driver' => \App\Frontdoor\DatabaseAccountDriver::class,
],



namespace App\Frontdoor;

use App\Models\User;
use Daikazu\LaravelFrontdoor\Contracts\AccountData;
use Daikazu\LaravelFrontdoor\Contracts\CreatableAccountDriver;
use Daikazu\LaravelFrontdoor\Support\RegistrationField;
use Daikazu\LaravelFrontdoor\Support\SimpleAccountData;

class DatabaseAccountDriver implements CreatableAccountDriver
{
    public function findByEmail(string $email): ?AccountData
    {
        $user = User::where('email', $email)->first();

        if (! $user) {
            return null;
        }

        return new SimpleAccountData(
            id: (string) $user->id,
            name: $user->name,
            email: $user->email,
            phone: $user->phone,
            avatarUrl: $user->avatar_url,
            metadata: ['role' => $user->role],
        );
    }

    public function exists(string $email): bool
    {
        return User::where('email', $email)->exists();
    }

    public function registrationFields(): array
    {
        return [
            new RegistrationField(
                name: 'name',
                label: 'Full name',
                type: 'text',
                

'accounts' => [
    'driver' => 'database',
    'drivers' => [
        'database' => \App\Frontdoor\DatabaseAccountDriver::class,
    ],
],

'registration' => [
    'enabled' => true,
],

public function registrationFields(): array
{
    return [
        new RegistrationField(
            name: 'name',
            label: 'Full name',
              type: 'select',
                   'sales' => 'Sales',
            ],
        ),
        new RegistrationField(
            name: 'agree_terms',
            label: 'I agree to the terms of service',
            type: 'checkbox',
            

// In AppServiceProvider
$this->app->bind(ApiAccountDriver::class, function ($app) {
    return new ApiAccountDriver(
        apiUrl: config('services.user_api.url'),
        apiKey: config('services.user_api.key'),
    );
});

// Named driver
'driver' => 'api',
'drivers' => ['api' => \App\Frontdoor\ApiAccountDriver::class],

// Or FQCN
'driver' => \App\Frontdoor\ApiAccountDriver::class,

new SimpleAccountData(
    id: '1',
    name: 'Jane Doe',
    email: '[email protected]',
    phone: '+1-555-0100',       // optional
    avatarUrl: null,             // optional, falls back to generated gradient
    metadata: ['role' => 'admin'], // optional
);

'registration' => [
    'enabled' => false,  // Set to true to enable registration
],

'mail' => [
    // Standard login OTP
    'mailable' => \Daikazu\LaravelFrontdoor\Mail\OtpMail::class,
    'subject' => 'Your login code',

    // Email verification OTP (sent before registration form)
    'verification_mailable' => \Daikazu\LaravelFrontdoor\Mail\OtpMail::class,
    'verification_subject' => 'Verify your email address',

    // Welcome email (sent after account creation, no OTP)
    'welcome_mailable' => \Daikazu\LaravelFrontdoor\Mail\WelcomeMail::class,
    'welcome_subject' => 'Welcome to ' . env('APP_NAME', 'our app'),

    'from' => [
        'address' => env('FRONTDOOR_MAIL_FROM', env('MAIL_FROM_ADDRESS')),
        'name' => env('FRONTDOOR_MAIL_FROM_NAME', env('MAIL_FROM_NAME')),
    ],
],

use Daikazu\LaravelFrontdoor\Events\AccountRegistered;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

Event::listen(function (AccountRegistered $event) {
    Log::info("New user registered: {$event->account->getEmail()}");

    // Send to analytics, assign default roles, create onboarding tasks, etc.
});

'ui' => [
    'mode' => 'modal',  // Opens login flow in an overlay
],

'ui' => [
    'mode' => 'page',  // Redirects to full-page login form
],

Route::middleware('auth:frontdoor')->group(function () {
    Route::get('/dashboard', function () {
        $user = auth('frontdoor')->user();
        return view('dashboard', ['user' => $user]);
    });
});

$user = auth('frontdoor')->user();

$user->id;              // Unique identifier
$user->name;            // Display name
$user->email;           // Email address
$user->phone;           // Phone number (or null)
$user->avatar_url;      // Avatar URL (or null)
$user->initial;         // First letter of name
$user->metadata;        // Full metadata array

$user->role;            // 'admin'
$user->company;         // 'Acme'
$user->unknown_key;     // null (key not in metadata)

use Daikazu\LaravelFrontdoor\Facades\Frontdoor;

$code = Frontdoor::requestOtp('[email protected]');
// Email is sent with 6-digit code

$success = Frontdoor::verify('[email protected]', '123456');

if ($success) {
    // User is now authenticated
    $user = auth('frontdoor')->user();
}

Frontdoor::loginAs('[email protected]');
// User is now authenticated

$fields = Frontdoor::registrationFields();

foreach ($fields as $field) {
    echo $field->name;     // e.g. 'name'
    echo $field->label;    // e.g. 'Full name'
    echo $field->type;     // e.g. 'text'
    echo $field->

$code = Frontdoor::requestEmailVerification('[email protected]');
// Verification email sent with 6-digit code

$verified = Frontdoor::verifyEmailOnly('[email protected]', '123456');

if ($verified) {
    // Email is verified, show registration form
}

try {
    $account = Frontdoor::register('[email protected]', [
        'name' => 'New User',
    ]);
    // User is now logged in, welcome email sent
    echo $account->getName(); // 'New User'
} catch (\Illuminate\Validation\ValidationException $e) {
    // Required fields missing or invalid
} catch (\Daikazu\LaravelFrontdoor\Exceptions\RegistrationNotSupportedException $e) {
    // Registration not enabled or driver doesn't support it
}

if (Frontdoor::registrationEnabled()) {
    // Show registration UI
}

$manager = Frontdoor::accounts();

// Find an account
$account = $manager->driver()->findByEmail('[email protected]');

// Check if account exists
$exists = $manager->driver()->exists('[email protected]');

$otpManager = Frontdoor::otp();

// Generate a code
$code = $otpManager->generate('[email protected]');

// Verify a code
$valid = $otpManager->verify('[email protected]', '123456');

// Delete a code
$otpManager->delete('[email protected]');



return [
    /*
    |--------------------------------------------------------------------------
    | Authentication Guard
    |--------------------------------------------------------------------------
    |
    | The guard name used for Frontdoor authentication. This is registered
    | automatically and used for all authentication checks.
    |
    */
    'guard' => 'frontdoor',

    /*
    |--------------------------------------------------------------------------
    | Account Provider
    |--------------------------------------------------------------------------
    |
    | The driver determines where user accounts are looked up.
    |
    | Built-in:
    |   'testing' - Cache-backed driver with seed users. Supports registration.
    |               For development and trying out the package.
    |
    | Custom drivers can be registered two ways:
    |
    |   1. Named driver — add an entry to the drivers array:
    |      'driver' => 'salesforce',
    |      'drivers' => ['salesforce' => \App\Frontdoor\SalesforceProvider::class]
    |
    |   2. FQCN — set driver directly to the class name:
    |      'driver' => \App\Frontdoor\SalesforceProvider::class
    |
    | The class must implement AccountDriver (sign-in only)
    | or CreatableAccountDriver (sign-in + registration).
    |
    */
    'accounts' => [
        'driver' => env('FRONTDOOR_ACCOUNT_DRIVER', 'testing'),

        'drivers' => [
            'testing' => [
                'users' => [
                    // Seed users for the testing driver.
                    // '[email protected]' => [
                    //     'name' => 'User Name',
                    //     'phone' => '+1-555-0100',  // optional
                    //     'metadata' => ['role' => 'admin'],  // optional
                    // ],
                ],
            ],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Registration
    |--------------------------------------------------------------------------
    |
    | When enabled, users who attempt to log in without an existing account
    | will be offered the option to create one. The active account driver
    | must implement CreatableAccountDriver for this to work.
    |
    */
    'registration' => [
        'enabled' => false,
    ],

    /*
    |--------------------------------------------------------------------------
    | OTP Settings
    |--------------------------------------------------------------------------
    |
    | Configure one-time password generation and validation behavior.
    |
    */
    'otp' => [
        'length' => 6,                     // Number of digits in the code
        'ttl' => 600,                      // Time-to-live in seconds (10 minutes)
        'cache_store' => null,             // Cache store (null = default)
        'cache_prefix' => 'frontdoor:otp:',

        'rate_limit' => [
            'max_attempts' => 5,           // Max OTP requests per window
            'decay_seconds' => 300,        // Rate limit window (5 minutes)
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Mail Settings
    |--------------------------------------------------------------------------
    |
    | Configure email delivery. Separate mailables for login OTP,
    | registration verification OTP, and post-registration welcome.
    |
    */
    'mail' => [
        'mailable' => \Daikazu\LaravelFrontdoor\Mail\OtpMail::class,
        'from' => [
            'address' => env('FRONTDOOR_MAIL_FROM', env('MAIL_FROM_ADDRESS')),
            'name' => env('FRONTDOOR_MAIL_FROM_NAME', env('MAIL_FROM_NAME')),
        ],
        'subject' => 'Your login code',

        // Email verification OTP (sent before registration form)
        'verification_mailable' => \Daikazu\LaravelFrontdoor\Mail\OtpMail::class,
        'verification_subject' => 'Verify your email address',

        // Welcome email (sent after account creation, no OTP)
        'welcome_mailable' => \Daikazu\LaravelFrontdoor\Mail\WelcomeMail::class,
        'welcome_subject' => 'Welcome to ' . env('APP_NAME', 'our app'),
    ],

    /*
    |--------------------------------------------------------------------------
    | UI Settings
    |--------------------------------------------------------------------------
    |
    | Control the authentication UI behavior and appearance.
    |
    */
    'ui' => [
        'mode' => 'modal',                 // 'modal' (overlay) or 'page' (redirect)
        'prefer_livewire' => true,         // Use Livewire when available
        'login_route' => '/login',         // Fallback login route

        'nav' => [
            'login_label' => 'Login',
            'account_label' => 'Account',
            'logout_label' => 'Logout',
            'account_route' => null,       // Optional account page route
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Avatar Settings
    |--------------------------------------------------------------------------
    |
    | Configure deterministic avatar generation. Avatars are generated from
    | email hashes using HSL gradients.
    |
    */
    'avatar' => [
        'algorithm' => 'gradient',         // Avatar generation algorithm
        'saturation' => 65,                // HSL saturation percentage
        'lightness' => 55,                 // HSL lightness percentage
    ],

    /*
    |--------------------------------------------------------------------------
    | Routes
    |--------------------------------------------------------------------------
    |
    | Configure authentication routes. Set enabled to false to disable
    | automatic route registration.
    |
    */
    'routes' => [
        'enabled' => true,
        'prefix' => 'frontdoor',
        'middleware' => ['web'],
    ],
];

use Daikazu\LaravelFrontdoor\Events\LoginSucceeded;
use Daikazu\LaravelFrontdoor\Events\AccountRegistered;

protected $listen = [
    LoginSucceeded::class => [
        LogUserLogin::class,
    ],
    AccountRegistered::class => [
        SendWelcomeNotification::class,
    ],
];

use Daikazu\LaravelFrontdoor\Events\OtpRequested;
use Daikazu\LaravelFrontdoor\Events\AccountRegistered;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

Event::listen(function (OtpRequested $event) {
    Log::info("OTP requested for {$event->email}");
});

Event::listen(function (AccountRegistered $event) {
    Log::info("New account created: {$event->account->getEmail()}");

    // Send to analytics, create welcome tasks, etc.
});



namespace App\Mail;

use Daikazu\LaravelFrontdoor\Contracts\AccountData;
use Daikazu\LaravelFrontdoor\Contracts\OtpMailable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;

class BrandedOtpMail extends Mailable implements OtpMailable
{
    public string $code = '';
    public ?AccountData $account = null;
    public int $expiresInMinutes = 10;

    public function setCode(string $code): static
    {
        $this->code = $code;
        return $this;
    }

    public function setAccount(AccountData $account): static
    {
        $this->account = $account;
        return $this;
    }

    public function setExpiresInMinutes(int $minutes): static
    {
        $this->expiresInMinutes = $minutes;
        return $this;
    }

    public function envelope(): Envelope
    {
        return new Envelope(subject: 'Your Login Code');
    }

    public function content(): Content
    {
        return new Content(
            view: 'emails.branded-otp',
            with: [
                'code' => $this->code,
                'account' => $this->account,
                'expiresInMinutes' => $this->expiresInMinutes,
            ],
        );
    }
}

'mail' => [
    'mailable' => \App\Mail\BrandedOtpMail::class,
    // ...
],

public function getAvatarUrl(): ?string
{
    // Use Gravatar
    $hash = md5(strtolower(trim($this->email)));
    return "https://www.gravatar.com/avatar/{$hash}?d=mp&s=200";

    // Or use UI Avatars
    return "https://ui-avatars.com/api/?name=" . urlencode($this->name) . "&background=random";

    // Or return stored avatar path
    return $this->avatarPath ? asset($this->avatarPath) : null;
}

'avatar' => [
    'algorithm' => 'gradient',
    'saturation' => 75,  // Higher saturation = more vivid colors
    'lightness' => 50,   // Lower lightness = darker colors
],

use Daikazu\LaravelFrontdoor\Facades\Frontdoor;

it('allows authenticated users to view dashboard', function () {
    Frontdoor::loginAs('[email protected]');

    $this->get('/dashboard')
        ->assertOk()
        ->assertSee('Dashboard');
});

use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Cache;

it('sends OTP email when user requests code', function () {
    Mail::fake();

    Frontdoor::requestOtp('[email protected]');

    Mail::assertSent(OtpMail::class, function ($mail) {
        return $mail->hasTo('[email protected]');
    });
});
bash
php artisan vendor:publish --tag="laravel-frontdoor-config"
bash
php artisan vendor:publish --tag="laravel-frontdoor-views"
bash
composer analyse