A custom jwt token generator

1.0.0 2024-03-21 20:13 UTC

This package is auto-updated.

Last update: 2025-08-21 23:32:33 UTC


README

A custom jwt token generator

Installation via Composer:

composer require konstantinkotov/jwt

Settings:

Step 1:

You must start a command below:

php artisan jwt:install
php artisan migrate

This will copy the necessary migration file to your database/migrations folder.

Step 2:

Next you have to add JWTSubjectTrait to your User model:

use Konstantinkotov\jwt\Traits\JWTModelTrait;

If you need quickly access to token, you can add JWTControllerTrait to your controller files. Example:

use Konstantinkotov\jwt\Traits\JWTControllerTrait;

You'll have the access to the token inside your controller. You can obtain the token, using:

$token = $this->token();

The token will be searched in Authorization inside the headers params.

Step 3:

If you need ready resource to your checks. You can use:

return (new \Konstantinkotov\jwt\Resources\AccessAllowedResource());

or

return (new \Konstantinkotov\jwt\Resources\AccessDeniedResource());

AccessAllowedResource will return, with status code 200:

{
  "token": "<your_api_token>",
  "request_type": "bearer"
}

AccessDeniedResource will return, with status code 401:

{
  "error": "Unauthorized"
}

How to use:

$token = $user->generate();

This will create a token, save it to the api_token column in users table.

Or you can use it using JWT class. For example:

\Konstantinkotov\jwt\JWT::token()->generate(<token_size>);

By default, the size is 100.

Result example:

2sxxQfkefRw4XuUX3d2UoPfIEnJIzPZZy.wBL8KdljmfPMPHp5jUk59sQ5xs3cMtPK5.lhmLchEZCpCUkckgukz0AEhkQzJunrT5o.v