PHP code example of spykapps / passwordless-login

1. Go to this page and download the library: Download spykapps/passwordless-login 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/ */

    

spykapps / passwordless-login example snippets


use SpykApp\PasswordlessLogin\Traits\HasMagicLogin;

class User extends Authenticatable
{
    use HasMagicLogin;
}

use SpykApp\PasswordlessLogin\Facades\PasswordlessLogin;

// Simple — generates link and sends email automatically
$user = User::where('email', $request->email)->first();

$result = PasswordlessLogin::forUser($user)->generate($request);
// $result['url']   → the magic link URL
// $result['token'] → the MagicLoginToken model

// Or use the trait
$result = $user->sendMagicLink($request);

use SpykApp\PasswordlessLogin\Facades\PasswordlessLogin;

// In a controller
public function sendLink(Request $request)
{
    $request->validate(['email' => 'n back()->with('status', __('passwordless-login::messages.link_sent_if_exists'));
    }

    try {
        PasswordlessLogin::forUser($user)->generate($request);
    } catch (\SpykApp\PasswordlessLogin\Exceptions\ThrottleException $e) {
        return back()->with('error', $e->getMessage());
    }

    return back()->with('status', __('passwordless-login::messages.link_sent'));
}

$result = PasswordlessLogin::forUser($user)
    ->guard('admin')                              // Custom guard
    ->redirectTo('/admin/dashboard')              // Custom redirect
    ->expiresIn(60)                               // 60 minutes expiry
    ->maxUses(3)                                  // Usable 3 times
    ->remember()                                  // Remember the session
    ->tokenLength(64)                             // 128-char hex token
    ->withMetadata(['source' => 'api', 'ip' => $request->ip()])
    ->withoutNotification()                       // Don't send email (handle yourself)
    ->generate($request);

// Send the link your own way
Mail::to($user)->send(new MyCustomMail($result['url']));

$user->sendMagicLink($request, [
    'guard' => 'admin',
    'redirect_url' => '/admin',
    'expiry_minutes' => 30,
    'max_uses' => 1,
    'remember' => true,
    'metadata' => ['reason' => 'password_reset'],
]);

$result = PasswordlessLogin::forUser($user)
    ->withoutNotification()
    ->generate($request);

$magicUrl = $result['url'];
// Use in SMS, WhatsApp, API response, etc.

// 1. Generate + auto-send email (most common)
$result = PasswordlessLogin::forUser($user)->generate($request);

// 2. Same thing via trait (identical to above)
$result = $user->sendMagicLink($request);

// 3. Generate only — NO email sent
$result = PasswordlessLogin::forUser($user)
    ->withoutNotification()
    ->generate($request);

// 4. Same via trait — NO email sent
$result = $user->generateMagicLink($request, [
    'send_notification' => false,
]);

// 5. Generate without email, send your own way
$result = PasswordlessLogin::forUser($user)
    ->withoutNotification()
    ->generate($request);

Mail::to($user)->send(new YourCustomMail($result['url']));
// or SMS, WhatsApp, etc.

// 6. Generate + send with custom notification class
$result = PasswordlessLogin::forUser($user)
    ->useNotification(\App\Notifications\MyMagicLink::class)
    ->generate($request);

// 7. Generate + send with custom mailable class
$result = PasswordlessLogin::forUser($user)
    ->useMailable(\App\Mail\MyMagicLinkMail::class)
    ->generate($request);

// 8. Full fluent example — no email
$result = PasswordlessLogin::forUser($user)
    ->guard('admin')
    ->redirectTo('/admin/dashboard')
    ->expiresIn(60)
    ->maxUses(3)
    ->remember()
    ->tokenLength(64)
    ->withMetadata(['source' => 'api'])
    ->withoutNotification()
    ->generate($request);

$magicUrl = $result['url'];
$tokenModel = $result['token'];

// config/passwordless-login.php
'bot_detection' => [
    'enabled' => true,
    'strategy' => 'both', // Options: 'confirmation_page', 'javascript', 'both'
],

// config/passwordless-login.php
'conditions' => [
    // Closures
    fn($user) => $user->is_active,
    fn($user) => !$user->is_banned,
    fn($user) => $user->email_verified_at !== null,

    // Classes implementing LoginCondition
    \App\Auth\CheckSubscription::class,
],

use SpykApp\PasswordlessLogin\Contracts\LoginCondition;
use Illuminate\Contracts\Auth\Authenticatable;

class CheckSubscription implements LoginCondition
{
    public function check(Authenticatable $user): bool
    {
        return $user->hasActiveSubscription();
    }

    public function message(): string
    {
        return 'Your subscription has expired.';
    }
}

// config/passwordless-login.php
'after_login_action' => \App\Actions\UpdateLastLogin::class,

use SpykApp\PasswordlessLogin\Contracts\AfterLoginAction;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Request;

class UpdateLastLogin implements AfterLoginAction
{
    public function execute(Authenticatable $user, Request $request): void
    {
        $user->update([
            'last_login_at' => now(),
            'last_login_ip' => $request->ip(),
        ]);
    }
}

// EventServiceProvider or listener
use SpykApp\PasswordlessLogin\Events\MagicLinkAuthenticated;
use SpykApp\PasswordlessLogin\Events\MagicLinkFailed;

Event::listen(MagicLinkAuthenticated::class, function ($event) {
    Log::info("User {$event->user->email} logged in via magic link");
});

Event::listen(MagicLinkFailed::class, function ($event) {
    Log::warning("Magic link failed: {$event->reason} from {$event->ipAddress}");
});

// lang/vendor/passwordless-login/es/messages.php
return [
    'email_subject' => 'Tu enlace de inicio de sesión',
    'email_greeting' => '¡Hola!',
    'email_intro' => 'Recibimos una solicitud de inicio de sesión para tu cuenta.',
    'email_action' => 'Iniciar Sesión',
    'email_expiry_notice' => 'Este enlace expirará en :minutes minutos.',
    'email_outro' => 'Si no solicitaste este enlace, no es necesario realizar ninguna acción.',
    // ... etc
];

// config/passwordless-login.php
'notification' => [
    'class' => \App\Notifications\CustomMagicLink::class,
],

// config/passwordless-login.php
'notification' => [
    'mailable' => \App\Mail\CustomMagicLinkMail::class,
],
bash
php artisan vendor:publish --tag=passwordless-login-config
bash
php artisan vendor:publish --tag=passwordless-login-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=passwordless-login
bash
php artisan passwordless-login:upgrade
bash
php artisan vendor:publish --tag=passwordless-login-lang
bash
php artisan vendor:publish --tag=passwordless-login-views