PHP code example of tahajaiti / jwt

1. Go to this page and download the library: Download tahajaiti/jwt 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/ */

    

tahajaiti / jwt example snippets


use Kyojin\JWT\Traits\HasJWT;

class User extends Authenticatable
{
    use HasJWT;

    // Optional: Customize payload
    public function payload(): array
    {
        return [
            'role' => $this->role
        ];
    }
}

$user = User::find(1);
$token = $user->createToken(); // New token

use Kyojin\JWT\Facades\JWT;

$payload = ['sub' => 1, 'role' => 'admin'];
$token = JWT::encode($payload);

// In routes/api.php
Route::middleware('jwt')->group(function () {
    Route::get('/test', function () {
        return response()->json(['message' => 'Authenticated']);
    });
});

use Kyojin\JWT\Facades\JWT;

$isValid = JWT::validate($token); // Returns boolean
$payload = JWT::decode($token);   // Returns array or throws exception
$user = Auth::user();            // Returns the user based on the validated token 
$user = JWT::user();            // (Optional method for retrieving the user)

use Kyojin\JWT\Exceptions\InvalidTokenException;
use Kyojin\JWT\Exceptions\TokenNotFoundException;

public function render($request, Throwable $exception)
{
    if ($exception instanceof TokenNotFoundException || $exception instanceof InvalidTokenException) {
        return response()->json(['error' => $exception->getMessage()], 401);
    }
}
 bash
php artisan jwt:setup
 php
return [
    'secret' => env('JWT_SECRET', 'fallback-secret'),
    'algo' => env('JWT_ALGO', 'HS256'),
    'ttl' => env('JWT_TTL', 3600),
];
 php
'providers' => [
    // ...
    Kyojin\JWT\Providers\JWTServiceProvider::class,
],