PHPackages                             lahaxearnaud/laravel-token - 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. [Mail &amp; Notifications](/categories/mail)
4. /
5. lahaxearnaud/laravel-token

AbandonedArchivedLibrary[Mail &amp; Notifications](/categories/mail)

lahaxearnaud/laravel-token
==========================

Laravel 4 token management

v0.5.1(11y ago)103951[1 issues](https://github.com/lahaxearnaud/laravel-token/issues)MITPHPPHP &gt;=5.4.0

Since Dec 22Pushed 11y ago3 watchersCompare

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

READMEChangelogDependencies (5)Versions (8)Used By (0)

Laravel token
=============

[](#laravel-token)

[![Build Status](https://camo.githubusercontent.com/c022ca689c4e66eab25f9c58d632cada8385f32266d8587ce7355edc2606c072/68747470733a2f2f7472617669732d63692e6f72672f6c616861786561726e6175642f6c61726176656c2d746f6b656e2e7376673f6272616e63683d646576656c6f70)](https://travis-ci.org/lahaxearnaud/laravel-token)[![SensioLabsInsight](https://camo.githubusercontent.com/f98d89033d112fae951ab695fefa6dce40b43ce47ad6c0007ebe36fa496ab3ba/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f32663961626431632d343261362d346138302d383866342d6531363837623164333631612f6d696e692e706e67)](https://insight.sensiolabs.com/projects/2f9abd1c-42a6-4a80-88f4-e1687b1d361a)[![CodeClimat](https://camo.githubusercontent.com/69869151afa14ab49a856da205076635724415570d46edae4913d5f4f7c5d379/68747470733a2f2f643373366d75743368696b6775772e636c6f756466726f6e742e6e65742f6769746875622f6c616861786561726e6175642f6c61726176656c2d746f6b656e2f6261646765732f6770612e737667)](https://codeclimate.com/github/lahaxearnaud/laravel-token)[![Test Coverage](https://camo.githubusercontent.com/095dd346405914d321e3317a2b1cee4d4b49da6c67f878e70b584d8b82a9c371/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6c616861786561726e6175642f6c61726176656c2d746f6b656e2f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/lahaxearnaud/laravel-token)[![License](https://camo.githubusercontent.com/3864c0d39439273179ec036bb3fce33aeb169cd758eaa224a261c8490cc1c374/68747470733a2f2f706f7365722e707567782e6f72672f6c656170686c792f636172742d62756e646c652f6c6963656e73652e737667)](https://github.com/lahaxearnaud/laravel-token)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/7ec1b5c5e9720e8b95731e39bd13274460743fd77641f790c7f8384f4b3aecdb/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c616861786561726e6175642f6c61726176656c2d746f6b656e2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/lahaxearnaud/laravel-token/?branch=master)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
    - [Database](#database)
    - [Provider](#provider)
    - [Facade](#facade)
- [Usage](#usage)
    - [Create token](#create-token)
    - [Crypt token](#crypt-token)
    - [Validate token](#validate-token)
    - [Route filter](#route-filter)
    - [Exceptions](#exceptions)
    - [Events](#events)
- [Commands](#commands)
    - [Delete expired tokens](#delete-expired-tokens)
    - [Truncate the table](#truncate-the-table)
- [API](#api)
    - [Security](#security)
    - [Creation](#creation)
    - [Deletion](#deletion)
    - [Validation](#validation)
    - [Find](#find)

Installation
------------

[](#installation)

```
{
    "require": {
        "lahaxearnaud/laravel-token": "~0.5"
    }
}
```

### Database

[](#database)

```
    $ php artisan migrate --package="lahaxearnaud/laravel-token"
```

### Provider

[](#provider)

```
	'providers' => array(
        // ...
		'Lahaxearnaud\LaravelToken\LaravelTokenServiceProvider',
	),
```

### Facade

[](#facade)

```
	'aliases' => array(
        // ...
		'Token' => 'Lahaxearnaud\LaravelToken\LaravelTokenFacade',
	),
```

Usage
-----

[](#usage)

### Create token

[](#create-token)

```
    $token = Token::create($userID, $allowLogin);
```

If `$allowLogin` is set to true the token can be use to authentification via route filter.

### Crypt token

[](#crypt-token)

```
    $token = Token::create($userID, $allowLogin);
    $cryptToken = Token::cryptToken($token->token);
```

If `$allowLogin` is set to true the token can be use to authentification via route filter.

### Validate token

[](#validate-token)

If you crypt your token

```
    $tokenStr = Token::getTokenValueFromRequest();

    $cryptToken = Token::isValidCryptToken($token->token, $userId);
```

If you don't crypt your token:

```
    $tokenStr = Token::getTokenValueFromRequest();

    $cryptToken = Token::isValidToken($token->token, $userId);
```

If you use those functions the token is not burn. It can be use many times.

For one shot usage token:

```
    $tokenStr = Token::getTokenValueFromRequest();

    /**
      * if the token is crypt do :
      * $tokenStr = Token::uncryptToken($tokenStr);
    **/

    $tokenValid = true;
    try {
        // find the token
        $token = $token->findByToken($tokenStr, $userId);

        // test the token validity
        if (Token::isValidToken($token)) {

            // do what you need to do

            // delete the token
            Token::burn($token);
        } else {
            $tokenValid = false;
        }
    } catch (TokenNotFoundException $e) {
        $tokenValid = false;
    }

    if($tokenValid) {
        // manage errors
    }
```

### Route filter

[](#route-filter)

Simple token protection:

```
    Route::get('/token-protected', array('before' => 'token', function () {
        echo "I am token protected";
    }));
```

Authentification by token:

The token used for an authentification must be a login token, pleaserefer to the token creation section

```
    Route::get('/login-by-token', array('before' => 'token.auth', function () {
        echo Auth::user()->username;
    }));
```

In order to use the authentification by token your class User need to implements `Lahaxearnaud\LaravelToken\Models\UserTokenInterface`

```
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Lahaxearnaud\LaravelToken\Models\UserTokenInterface;

class User extends Eloquent implements UserInterface, RemindableInterface, UserTokenInterface {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');

    public function loggableByToken()
    {
        return true;
    }
}
```

The method `loggableByToken` is called when a user try to authentificate with a token.

If an error occur on token validation a TokenExeption is throw, please go to [Exceptions](#exceptions) section.

By default you can send your token in parameter or header. The default name of the field is `token` but you can change it by publishing and change the configuration:

```
    $ php artisan config:publish lahaxearnaud/laravel-token
```

Then change the tokenFieldName `config/packages/lahaxearnaud/laravel-token/config.php`.

You can get the token instance via:

```
    Token::getCurrentToken();
```

### Exceptions

[](#exceptions)

If you use route filter you need to handle some Exceptions. Add the following error handler in you `filter.php` to catch them. This is basic example, change the behavior to fit your needs (redirect, log...).

```
    App::error(function(\Lahaxearnaud\LaravelToken\exeptions\TokenException $exception)
    {
        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\TokenNotFoundException) {
            return \Response::make('Unauthorized (Not found)', 401);
        }

        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\TokenNotValidException) {
            return \Response::make('Unauthorized (Not valid token)', 401);
        }

        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\UserNotLoggableByTokenException) {
            return \Response::make('Unauthorized (Not loggable by token)', 401);
        }

        if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\NotLoginTokenException) {
            return \Response::make('Unauthorized (Not login token)', 401);
        }
    });
```

### Events

[](#events)

You can listen events:

- Token not found
    - name: `token.notFound`
    - parameters:
        - the token string
- Token not valid
    - name: `token.notValid`
    - parameters:
        - the token object
- Token doesn't allow to be used for login
    - name: `token.notLoginToken`
    - parameters:
        - the token object
- The user can't logged with a token
    - name: `token.notLoggableUser`
    - parameters:
        - the token object
        - the user object
- Token burn
    - name: `token.burned`
    - parameters:
        - the token object
- Token created
    - name: `token.created`
    - parameters:
        - the token object
- Token saved
    - name: `token.saved`
    - parameters:
        - the token object

Commands
--------

[](#commands)

```
A new artisan command is added to your project in order to help you to clean your token table

### Delete expired tokens
    Without any option the command delete all expired tokens.
    ```bash
        $ php artisan token:clean
    ```
### Truncate the table
    If you specified ``--all`` all token will be deleted
    ```bash
        $ php artisan token:clean -all
    ```

```

API
---

[](#api)

### Security

[](#security)

Crypt a string token in order to get a public token

```
    Token::cryptToken ($uncrypt)
```

Uncrypt a public token in order to get the private token

```
    Token::uncryptToken ($crypt)
```

### Creation

[](#creation)

Create a Token instance (directly saved in database)

```
    Token::create ($userId, $allowLogin = false, $lifetime = 3600, $length = 100)
```

If `$allowLogin` is set to true the token can be use to authentification via route filter.

### Deletion

[](#deletion)

Delete the token

```
    Token::burn (Token $token)
```

### Validation

[](#validation)

Fetch the token, check id the token has the good user ID and if it is not expired

```
    Token::isValidToken ($token, $userId)
```

Same as isValidToken but uncrypt the token before trying to find him

```
    Token::isValidCryptToken ($token, $userId)
```

Only validate if the token is expired

```
    Token::isValid (Token $token)
```

### Find

[](#find)

Find the token by ID

```
    Token::find ($id)
```

Find the token by token string

```
    Token::findByToken ($token, $userId)
```

Find all token for an user

```
    Token::findByUser ($idUser)
```

Todo
----

[](#todo)

- config to allow only one token by user and type

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.4% 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 ~3 days

Total

6

Last Release

4145d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bab37acc38e46b09f3452e2b81711dced89874ffa35a188687905242c4248011?d=identicon)[alahaxe](/maintainers/alahaxe)

---

Top Contributors

[![lahaxearnaud](https://avatars.githubusercontent.com/u/1364221?v=4)](https://github.com/lahaxearnaud "lahaxearnaud (54 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (2 commits)")

---

Tags

laravelroute-filtertokenizerlaraveltokennotification

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lahaxearnaud-laravel-token/health.svg)

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

###  Alternatives

[laravel-notification-channels/telegram

Telegram Notifications Channel for Laravel

1.1k3.4M35](/packages/laravel-notification-channels-telegram)[mckenziearts/laravel-notify

Flexible flash notifications for Laravel

1.7k1.1M5](/packages/mckenziearts-laravel-notify)[laravel-notification-channels/twilio

Provides Twilio notification channel for Laravel

2587.7M12](/packages/laravel-notification-channels-twilio)[laravel-notification-channels/discord

Laravel notification driver for Discord.

2371.3M11](/packages/laravel-notification-channels-discord)[brian2694/laravel-toastr

toastr.js for Laravel

136649.4k5](/packages/brian2694-laravel-toastr)[gr8shivam/laravel-sms-api

A modern, flexible Laravel package for integrating any SMS gateway with REST API support

10138.4k](/packages/gr8shivam-laravel-sms-api)

PHPackages © 2026

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