PHPackages                             shetabit/token-builder - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. shetabit/token-builder

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

shetabit/token-builder
======================

Laravel Token Builder

v3.0.0(11mo ago)236.7k—0%12[1 issues](https://github.com/shetabit/token-builder/issues)MITPHPPHP &gt;=7.2

Since Dec 4Pushed 11mo ago2 watchersCompare

[ Source](https://github.com/shetabit/token-builder)[ Packagist](https://packagist.org/packages/shetabit/token-builder)[ Docs](https://github.com/shetabit/token-builder)[ RSS](/packages/shetabit-token-builder/feed)WikiDiscussions master Synced 1mo ago

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

[![](resources/images/laravel-token-builder-package.png?raw=true)](resources/images/laravel-token-builder-package.png?raw=true)

Laravel Token Builder
=====================

[](#laravel-token-builder)

This package can generate **random tokens** which **can expires**.

Generated token can be used for creating **one-time links**, or **authentication with sms pin** and etc.

we have 2 things that can **expire** genereted tokens:

- **time limit** : for example a token can be expired after 2022/05/12
- **usage limit** : for example a token can be expired after using it more than 3 times.

[Donate me](https://yekpay.me/mahdikhanzadi) if you like this package 😎 ![:bowtie:](https://github.githubassets.com/images/icons/emoji/bowtie.png ":bowtie:")

List of contents
================

[](#list-of-contents)

- [Available drivers](#list-of-available-drivers)
- [Install](#install)
- [Configure](#configure)
- [How to use](#how-to-use)
    - [Generating tokens](#generating-tokens)
    - [Adding expiration date](#adding-expiration-date)
    - [Adding usage limit](#adding-usage-limit)
    - [Validation](#validation)
    - [Add relations](#useful-methods)
    - [Attach custom data](#useful-methods)
    - [Retrieve tokens](#retrieve-tokens)
    - [TokenBuilder reference](#tokenbuilder-reference)
        - [setUniqueId](#setUniqueId)
        - [getUniqueId](#getUniqueId)
        - [setData](#setData)
        - [getData](#getData)
        - [setExpireDate](#setExpireDate)
        - [getExpireDate](#getExpireDate)
        - [setUsageLimit](#setUsageLimit)
        - [getUsageLimit](#getUsageLimit)
        - [setType](#setType)
        - [getType](#getType)
        - [setRelatedItem](#setRelatedItem)
        - [getRelatedItem](#getRelatedItem)
        - [build](#build)
        - [findToken](#findToken)
        - [findValidToken](#findValidToken)
    - [Token (Eloquent) reference](#token-reference)
        - [use](#use)
        - [hasUsed](#hasUsed)
        - [hasMaxUsageLimit](#hasMaxUsageLimit)
        - [hasExpired](#hasExpired)
        - [markAsExpired](#markAsExpired)
        - [isValid](#isValid)
        - [tokenable](#tokenable)
- [Change log](#change-log)
- [Contributing](#contributing)
- [Security](#security)
- [Credits](#credits)
- [License](#license)

Install
-------

[](#install)

Via Composer

```
$ composer require shetabit/token-builder
```

Configure
---------

[](#configure)

If you are using `Laravel 5.5` or higher then you don't need to add the provider and alias.

In your `config/app.php` file add these two lines.

```
# In your providers array.
'providers' => [
    ...
    Shetabit\TokenBuilder\Provider\TokenBuilderServiceProvider::class,
],

# In your aliases array.
'aliases' => [
    ...
    'TokenBuilder' => Shetabit\TokenBuilder\Facade\TokenBuilder::class,
],
```

then, run the below commands to **publish migrations** and **create tables**

```
php artisan vendor:publish

php artisan migrate
```

How to use
----------

[](#how-to-use)

you can use `TokenBuilder` facade or `Builder` class to build tokens.

#### Generating tokens

[](#generating-tokens)

In your code, use **facade** like the below :

```
use Shetabit\TokenBuilder\Facade\TokenBuilder;

// ...

$tokenObject = $token = TokenBuilder::build();
```

you can also use `Builder` :

```
use Shetabit\TokenBuilder\Builder;

// ...

$builder = new Builder;

$tokenObject = $builder->build();
```

each **tokenObject** has a **unique value** that can be used to recognize it from others and we call it `token`. you can access to tokenObject unique token using `token`, see below example:

```
use Shetabit\TokenBuilder\Facade\TokenBuilder;

// ...

// generate and store token in database
$tokenObject = $token = TokenBuilder::build();

// show token unique value
echo $tokenObject->token;
```

you can retrieve token and send it to users via email or sms or using it in URLs. it can be used to **sms verifications** or **one-time login pins** , etc.

#### Adding expiration date

[](#adding-expiration-date)

you can build a token with auto expiration date. this kind of token will be expired after the specified date.

```
    use Shetabit\TokenBuilder\Facade\TokenBuilder;

    // ...

    // will be expired after 5 minutes
    $date = Carbon::now()->addMinutes(5);
    $tokenObject = TokenBuilder::setExpireDate($date)->build();

    echo $tokenObject->token; // show unique token
    echo $tokenObject->expired_at; // show expiration datetime

    if ($tokenObject->hasExpired()) {
        echo 'token has expired';
    }
```

#### Adding usage limit

[](#adding-usage-limit)

you can add usage limit into your tokens. a token will be invalid after the usage has exceeded the limit.

```
    use Shetabit\TokenBuilder\Facade\TokenBuilder;

    // ...

    // will be expired after 1 usage.
    $tokenObject = TokenBuilder::setUsageLimit(1)->build();

    // use token --> increment the usage counter
    $tokenObject->use();

    echo $tokenObject->token; // show unique token
    echo $tokenObject->usage_count; // show total usages count
    echo $tokenObject->max_usage_limit; // show max usage limit

    // determine if user has used
    if ($tokenObject->hasUsed()) {
        echo 'token has used';
    }

    // determin if token has exceed max usage
    if ($tokenObject->hasExceedMaxUsage()) {
        echo 'token used has exceeded the specified limit';
    }
```

#### Validation

[](#validation)

you can validate a token using `isValid` method. a token is valid if has not exceeded the specified limit and has not expired yet.

```
use Shetabit\TokenBuilder\Facade\TokenBuilder;

// ...

$date = Carbon::now()->addMinutes(5); // will be expired after 5 minutes
$usageLimit = 1; // max usages
$token = TokenBuilder::setExpireDate($date)->setUsageLimit($usageLimit)->build();

if ($token->isValid()) {
    echo 'token is valid';

    $token->use(); // use token (increament usage counter)
} else {
    echo 'token is not valid any more!';
}
```

you can use a token by running `use` method. you can expire a token by running `markAsExpired` method. (this method will update expiration date to current date).

#### Add relations

[](#add-relations)

you can add a relation to tokens. this can be done in 2 different ways:

```
use Shetabit\TokenBuilder\Facade\TokenBuilder;
use App\User;

$user = User::first();

/**
 * first example: using TokenBuilder
 **/

$tokenObject = TokenBuilder::setRelatedItem($user)->build();

/**
 * second example: using a main model
 **/

$tokenObject = $user->temporaryTokenBuilder()->build();

// you can access to token's relation using the tokenable
dd($tokenObject->tokenable);

if ($tokenObject->tokenable) {
    echo $tokenObject->tokenable->email;
}
```

#### Attach custom data

[](#attach-custom-data)

you can attach custom data into your token. this data will be stored in json format.

```
use Shetabit\TokenBuilder\Facade\TokenBuilder;

/**
 * first example: using TokenBuilder
 **/

$data = [
    'mobile' => '9373620353',
    'name' => 'John Doe',
];

$tokenObject = TokenBuilder::setData($data)->build();

echo $tokenObject->data['mobile'];
```

#### Retrieve tokens

[](#retrieve-tokens)

you can retrieve `tokenObject` using token's unique string

```
$token = 22325651; // your unique token

// retrieve token object
$tokenObject = TokenBuilder::setUniqueId($token)->findToken();

// retrieve token object if it is valid
$tokenObject = TokenBuilder::setUniqueId($token)->findValidToken();

// retrieve token object using its relation
$tokenObject = $user->temporaryTokenBuilder()->setUniqueId($token)->findToken();

// retrieve token object if it is valid using its relation
$tokenObject = $user->temporaryTokenBuilder()->setUniqueId($token)->findValidToken();
```

#### TokenBuilder reference

[](#tokenbuilder-reference)

This is a reference for TokenBuilder methods. `TokenBuilder` creates a tokenObject (instance of eloquent `Token` model) if you run build method and searches into data base using `findToken` and `findValidToken`.

- ###### setUniqueId

    [](#setuniqueid)
- you can build tokens with your custom algoritm and use it as unique id.

    ```
      $token = 'jgaZ1z9';
      $tokenObject = TokenBuilder::setUniqueId($token)->build();
      echo $tokenObject->token; // jgaZ1z9
    ```
- ###### getUniqueId

    [](#getuniqueid)
- returns your custom unique id (if not exists, returns `null`).
- ###### setData

    [](#setdata)
- you can attach some data into tokens and retrieve them later.
- ###### getData

    [](#getdata)

    returns attached data.
- ###### setExpireDate

    [](#setexpiredate)

    sets an expiration date.
- ###### getExpireDate

    [](#getexpiredate)

    retrieves expiration date.
- ###### setUsageLimit

    [](#setusagelimit)

    sets usage limit.
- ###### getUsageLimit

    [](#getusagelimit)

    retrieves usage limit.
- ###### setType

    [](#settype)

    sets token type. you can set type for your tokens. its like a scope for your tokens.
- ###### getType

    [](#gettype)

    retrieves token type.
- ###### setRelatedItem

    [](#setrelateditem)

    add a relation to token.
- ###### getRelatedItem

    [](#getrelateditem)

    retrieve current relation.
- ###### build

    [](#build)

    generate a token.
- ###### findToken

    [](#findtoken)

    find token (being valid or not valid is not important) and return `null` if not exists.
- ###### findValidToken

    [](#findvalidtoken)

    find token if it is valid and return `null` if not exists.

#### Token Reference

[](#token-reference)

- ###### use

    [](#use)

    add 1 to usage counter. (usageCounter = usageCounter + 1)
- ###### hasUsed

    [](#hasused)

    determine is current token has used and returns a boolean result.
- ###### hasMaxUsageLimit

    [](#hasmaxusagelimit)

    determine if current token max usage is limited and returns a boolean result.
- ###### hasExpired

    [](#hasexpired)

    determine if current token has expired or not.
- ###### markAsExpired

    [](#markasexpired)

    mark current token as expired.

    **notice:** this method updates `expired_at` field to current time (now).
- ###### isValid

    [](#isvalid)

    determines if current token is valid (must not be expired and must not be exceeded max usage limit).
- ###### tokenable

    [](#tokenable)

    returns the token relation if there is any relation, and returns null if no relation exists.

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Mahdi khanzadi](https://github.com/khanzadimahdi)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance50

Moderate activity, may be stable

Popularity35

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 76.7% 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 ~333 days

Recently: every ~477 days

Total

7

Last Release

357d ago

Major Versions

v1.2 → v2.0.02023-02-27

v2.1.0 → v3.0.02025-05-27

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d73b855df70ba50a46d879126a3f32fb173d12ca3e778e0a72b7398cbef8a26?d=identicon)[shetabit](/maintainers/shetabit)

---

Top Contributors

[![khanzadimahdi](https://avatars.githubusercontent.com/u/6291970?v=4)](https://github.com/khanzadimahdi "khanzadimahdi (33 commits)")[![paulo-hortelan](https://avatars.githubusercontent.com/u/135706260?v=4)](https://github.com/paulo-hortelan "paulo-hortelan (3 commits)")[![roshedgostarandev1](https://avatars.githubusercontent.com/u/52368299?v=4)](https://github.com/roshedgostarandev1 "roshedgostarandev1 (3 commits)")[![amirsadeghi1](https://avatars.githubusercontent.com/u/26359326?v=4)](https://github.com/amirsadeghi1 "amirsadeghi1 (1 commits)")[![xembill](https://avatars.githubusercontent.com/u/8319808?v=4)](https://github.com/xembill "xembill (1 commits)")[![sifex](https://avatars.githubusercontent.com/u/2058557?v=4)](https://github.com/sifex "sifex (1 commits)")[![ezalorpro](https://avatars.githubusercontent.com/u/37134637?v=4)](https://github.com/ezalorpro "ezalorpro (1 commits)")

---

Tags

laraveltokenlaravel tokenonetime tokenexpiring tokensone usage tokenexpire token generatorpin generatorone time usage pinpin numberlaravel pin numberlaravel token builderlaravel pin builderlaravel pin generatortoken builder

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/shetabit-token-builder/health.svg)

```
[![Health](https://phpackages.com/badges/shetabit-token-builder/health.svg)](https://phpackages.com/packages/shetabit-token-builder)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[dirape/token

Unique Token Generator For Laravel

28277.4k2](/packages/dirape-token)[interaction-design-foundation/laravel-geoip

Support for multiple Geographical Location services.

17221.0k3](/packages/interaction-design-foundation-laravel-geoip)[nedwors/navigator

A Laravel package to ease defining navigation menus

433.1k](/packages/nedwors-navigator)[dcblogdev/laravel-junie

Install pre-configured guides for Jetbrains Junie

392.5k](/packages/dcblogdev-laravel-junie)[kevinsimard/laravel-cookieless-session

Laravel middleware to start a cookieless session

1417.0k](/packages/kevinsimard-laravel-cookieless-session)

PHPackages © 2026

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