PHPackages                             pijler/personal-tokens - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. pijler/personal-tokens

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

pijler/personal-tokens
======================

This package provides support for generating and validating personal tokens.

v0.5.0(1mo ago)0233↓50%MITPHPPHP ^8.3CI passing

Since Oct 20Pushed 2mo agoCompare

[ Source](https://github.com/Pijler/personal-tokens)[ Packagist](https://packagist.org/packages/pijler/personal-tokens)[ RSS](/packages/pijler-personal-tokens/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (10)Versions (8)Used By (0)

📌 Laravel Personal Tokens
=========================

[](#-laravel-personal-tokens)

This package provides support for generating and validating personal tokens in Laravel. Personal tokens are useful for temporary authentication, one-time access links, email confirmations, password resets, and other use cases that require secure and temporary access.

### 🧩 Features

[](#-features)

- ✅ **Secure token generation**: Encrypted tokens with secure hashing
- ✅ **Automatic expiration**: Control over token lifetime
- ✅ **One-time use**: Tokens can be marked as used
- ✅ **Token types**: Support for different token types
- ✅ **Custom payload**: Storage of additional data
- ✅ **Integrated middleware**: Easy route protection
- ✅ **Model trait**: Simple Eloquent integration
- ✅ **Flexible configuration**: Complete behavior customization

### 📦 Installation

[](#-installation)

You can install the package via Composer:

```
composer require pijler/personal-tokens
```

### 🗄️ Publishing Migrations

[](#️-publishing-migrations)

Publish the package migrations:

```
php artisan vendor:publish --tag=personal-tokens-migrations
```

Run the migrations:

```
php artisan migrate
```

### ⚙️ Configuration

[](#️-configuration)

#### Basic Configuration

[](#basic-configuration)

The package works out-of-the-box, but you can customize the behavior:

```
use PersonalTokens\TokenCreator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Set default expiration time (in minutes)
        TokenCreator::expiresAt(60);

        // Use custom model
        TokenCreator::usePersonalTokenModel(CustomPersonalToken::class);

        // Customize token generation
        TokenCreator::plainTextTokenUsing(fn () => 'prefix-' . Str::random(32));
    }
}
```

### 🧠 Usage

[](#-usage)

#### 1. Using the HasTokens Trait

[](#1-using-the-hastokens-trait)

Add the `HasTokens` trait to your model:

```
use PersonalTokens\Traits\HasTokens;

class User extends Model
{
    use HasTokens;
}
```

#### 2. Creating Tokens

[](#2-creating-tokens)

```
use Illuminate\Support\Carbon;

$user = User::find(1);

// Basic token
$token = $user->createPersonalToken('email-verification');

// Token with custom payload
$token = $user->createPersonalToken(
    type: 'password-reset',
    payload: [
        'ip' => request()->ip(),
        'email' => $user->email,
    ],
);

// Token with custom expiration
$token = $user->createPersonalToken(
    type: 'temporary-access',
    expiresAt: Carbon::now()->addDays(7),
);

// Token with custom value
$token = $user->createPersonalToken(
    type: 'custom-token',
    plainTextToken: 'my-custom-token',
);
```

#### 3. Validating Tokens

[](#3-validating-tokens)

```
use PersonalTokens\TokenCreator;

// Find token
$personalToken = TokenCreator::findToken($tokenString);

if ($personalToken && !$personalToken->isUsed() && !$personalToken->isExpired()) {
    // Valid token
    $owner = $personalToken->owner;
    $payload = $personalToken->payload;

    // Mark as used (optional)
    $personalToken->markAsUsed();
}
```

#### 4. Using the Middleware

[](#4-using-the-middleware)

The package includes middleware to automatically protect routes:

```
// routes/web.php
use Illuminate\Support\Facades\Route;

// Route protected with any token
Route::post('/protected', function () {
    return response()->json(['message' => 'Access granted']);
})->middleware('personal-token');

// Route protected with specific token type
Route::post('/email-verify', function () {
    return response()->json(['message' => 'Email verified']);
})->middleware('personal-token:email-verification');
```

The middleware expects the token in the `token` parameter of the request:

```
// Example usage with JavaScript
fetch("/protected", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    token: "your-token-here",
  }),
});
```

#### 5. Working with the PersonalToken Model

[](#5-working-with-the-personaltoken-model)

```
use PersonalTokens\Models\PersonalToken;

// Create token directly
$token = PersonalToken::createToken(
    model: $user,
    type: 'email-verification',
    plainTextToken: 'custom-token',
    expiresAt: Carbon::now()->addHour(),
    payload: ['action' => 'verify-email'],
);

// Check token status
$personalToken = PersonalToken::find(1);

if ($personalToken->isUsed()) {
    // Token already used
}

if ($personalToken->isExpired()) {
    // Token expired
}

// Check if belongs to owner
if ($personalToken->belongsToOwner($user)) {
    // Token belongs to user
}
```

### 🧩 API Reference

[](#-api-reference)

#### TokenCreator

[](#tokencreator)

```
// Configuration
TokenCreator::expiresAt(int $minutes): void
TokenCreator::usePersonalTokenModel(string $model): void
TokenCreator::plainTextTokenUsing(Closure $callback): void

// Methods
TokenCreator::findToken(string $token): ?PersonalToken
TokenCreator::createPlainTextToken(): string
TokenCreator::createToken(
    mixed $type,
    ?Model $model = null,
    ?array $payload = null,
    ?Carbon $expiresAt = null,
    ?string $plainTextToken = null,
): string
```

#### PersonalToken Model

[](#personaltoken-model)

```
// Relationships
$token->owner(): MorphTo

// Verification methods
$token->isUsed(): bool
$token->isExpired(): bool
$token->belongsToOwner(Model $owner): bool

// Actions
$token->markAsUsed(): int

// Static methods
PersonalToken::createToken(...): string
PersonalToken::findToken(string $token): ?self
```

#### HasTokens Trait

[](#hastokens-trait)

```
// Methods available on model
$model->personalTokens(): MorphMany
$model->currentPersonalToken(): ?PersonalToken
$model->withPersonalToken(?PersonalToken $token): self
$model->createPersonalToken(
    mixed $type,
    ?array $payload = null,
    ?Carbon $expiresAt = null,
    ?string $plainTextToken = null,
): string
```

### 📝 License

[](#-license)

Open-source under the [MIT license](LICENSE).

🚀 Thanks!
---------

[](#-thanks)

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance86

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~38 days

Total

5

Last Release

49d ago

PHP version history (2 changes)v0.1.0PHP ^8.2

v0.5.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/5256615ef2ba165b92bdf89908082480fb12be597c607637262e9fe61b5b2b22?d=identicon)[joaopalopes24@gmail.com](/maintainers/joaopalopes24@gmail.com)

---

Top Contributors

[![joaopalopes24](https://avatars.githubusercontent.com/u/45684782?v=4)](https://github.com/joaopalopes24 "joaopalopes24 (29 commits)")

---

Tags

laraveltokenspackagepersonal-tokens

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/pijler-personal-tokens/health.svg)

```
[![Health](https://phpackages.com/badges/pijler-personal-tokens/health.svg)](https://phpackages.com/packages/pijler-personal-tokens)
```

###  Alternatives

[lab404/laravel-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

2.3k16.4M48](/packages/lab404-laravel-impersonate)[lab404/laravel-auth-checker

Laravel Auth Checker allows you to log users authentication, devices authenticated from and lock intrusions.

223164.9k2](/packages/lab404-laravel-auth-checker)[rickycezar/laravel-jwt-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

24117.6k](/packages/rickycezar-laravel-jwt-impersonate)[hapidjus/laravel-impersonate-ui

UI for 404labfr/laravel-impersonate

371.5k](/packages/hapidjus-laravel-impersonate-ui)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
