Basic Usage
Issuing Tokens
Section titled “Issuing Tokens”Issue a single secret key (server-side only):
use App\Models\User;use Cline\Bearer\Facades\Bearer;
$user = User::find(1);$token = Bearer::for($user)->issue( type: 'sk', name: 'Production API Key',);
// The plain text token is only available at creation timeecho $token->plainTextToken; // sk_test_abc123...
// Access the token model$token->accessToken->type; // 'sk'$token->accessToken->environment; // 'test'$token->accessToken->name; // 'Production API Key'Issuing Token Groups
Section titled “Issuing Token Groups”Issue a group of related tokens (sk, pk, rk linked together):
$group = Bearer::for($user)->issueGroup( types: ['sk', 'pk', 'rk'], name: 'Payment Integration Keys',);
// Access individual tokens in the group$secretKey = $group->secretKey(); // sk_test_...$publishableKey = $group->publishableKey(); // pk_test_...$restrictedKey = $group->restrictedKey(); // rk_test_...
// Find sibling tokens$pkFromSk = $secretKey->sibling('pk'); // Get publishable key from secret key's groupConfiguring Tokens
Section titled “Configuring Tokens”Issue with custom configuration using the fluent API:
$token = Bearer::for($user) ->environment('live') // Set environment ->abilities(['users:read', 'orders:write']) // Custom abilities ->allowedIps(['192.168.1.0/24', '10.0.0.1']) // IP restrictions ->allowedDomains(['*.example.com']) // Domain restrictions ->rateLimit(100) // 100 requests per minute ->expiresIn(60 * 24 * 30) // Expires in 30 days ->issue('pk', 'Frontend Widget Key');Finding Tokens
Section titled “Finding Tokens”// Find by plain text token$token = Bearer::findToken('sk_test_abc123...');
// Find by prefix (partial match)$token = Bearer::findByPrefix('sk_test_abc');Using the HasApiTokens Trait
Section titled “Using the HasApiTokens Trait”Add the trait to your User model:
use Cline\Bearer\Concerns\HasApiTokens;
class User extends Authenticatable{ use HasApiTokens;}Then use the convenience methods:
// Create token via user model$token = $user->createToken('sk', 'My Token');
// Create token group via user model$group = $user->createTokenGroup(['sk', 'pk'], 'My Keys');
// Check current token abilitiesif ($user->tokenCan('users:write')) { // User has write access}
// Check token typeif ($user->tokenIs('sk')) { // Using a secret key}
// Get current token environment$env = $user->tokenEnvironment(); // 'test' or 'live'Next Steps
Section titled “Next Steps”- Authentication - Protecting routes and checking permissions
- Custom Token Types - Creating your own token types
- Token Metadata - Attaching custom data to tokens