PHP code example of mydaniel / laravel-temporary-tokens

1. Go to this page and download the library: Download mydaniel/laravel-temporary-tokens 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/ */

    

mydaniel / laravel-temporary-tokens example snippets


namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use MyDaniel\TemporaryTokens\Traits\HasTemporaryTokens;

class User extends Authenticatable
{
    use HasTemporaryTokens;

    // ...
}

$user = User::find(1);

// The `temporaryTokenBuilder` method comes from the HasTemporaryTokens trait
$temporaryToken = $user->temporaryTokenBuilder()->create();

echo $temporaryToken->token; // e.g., "123456"

$user = User::find(1);

$temporaryToken = $user->temporaryTokenBuilder()
    ->setType('email-verification')       // Set a token type
    ->setTokenLength(5)                   // Generate a 5-digit token
    ->setUsageLimit(1)                    // Allow the token to be used only once
    ->setExpireDate(now()->addMinutes(15)) // Set a 15-minute expiration
    ->setMetadata(['source' => 'registration']) // Attach custom data
    ->create();

use MyDaniel\TemporaryTokens\Models\TemporaryToken;

$userToken = '123456';
$tokenType = 'email-verification';

// Find a token that is not expired and has not exceeded its usage limit
$token = TemporaryToken::findValid($userToken, $tokenType);

if ($token) {
    // The token is valid
    echo "Token is valid!";

    // You can also check if the token belongs to the correct user
    if ($token->tokenable_id === $user->id) {
        // ...
    }
}

if ($token && $token->isValid()) {
    // ...
}

// Mark the token as "used"
$token->use();

// If the token reaches its usage limit, `hasExceededMaxUsage()` will return true
if ($token->hasExceededMaxUsage()) {
    echo "This token cannot be used anymore.";
}

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('temporary-tokens:prune-expired')->daily();
}
bash
php artisan vendor:publish --provider="MyDaniel\TemporaryTokens\TemporaryTokensServiceProvider"
bash
php artisan migrate
bash
php artisan temporary-tokens:prune-expired