Overview Laravel Sanctum provides a featherweight authentication system specifically designed for SPAs, mobile applications, and simple token-based APIs. While Laravel Passport offers a full OAuth2 server implementation, Sanctum focuses on first-party applications where you control both ends of the stack. It eliminates the complexity of OAuth2 while maintaining robust security for your endpoints. Prerequisites To follow this guide, you should be comfortable with the Laravel framework, specifically PHP Eloquent models, migrations, and basic routing. You will need a working Laravel installation with a database configured. Key Libraries & Tools * **Laravel Sanctum**: The core package for issuing and validating API tokens. * **HasApiTokens Trait**: A crucial trait added to the User model to enable token management methods. * **Personal Access Tokens Table**: The migration-generated table where Sanctum stores hashed token data. Code Walkthrough First, equip your User model with the necessary capabilities. Adding the trait gives you access to methods like `createToken()`. ```php use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; } ``` To generate a token, call `createToken` and specify a name. It is vital to grab the `plainTextToken` immediately, as Sanctum only stores a hashed version for security. ```php $user = User::first(); $token = $user->createToken('my-app-name')->plainTextToken; ``` When making requests, you must pass this string in the `Authorization` header as a Bearer token. Laravel's HTTP client makes this easy with the `withToken()` method: ```php $response = Http::withToken($token)->get('https://api.test/movies'); ``` Syntax Notes Sanctum uses **Abilities** to handle fine-grained permissions. By default, a token might have a `['*']` ability, granting full access. You can restrict tokens by passing an array of specific strings during creation, such as `['movies:read']`. This is checked via the `ability` or `abilities` middleware in your routes. Practical Examples Imagine a mobile app where users only need to view data but not update it. You would issue a token with a `read-only` ability. If that token is hijacked, the attacker cannot perform destructive actions like deleting records because the Sanctum middleware will block any request lacking the required scope. Tips & Gotchas * **The Plain Text Trap**: You can only access the unhashed token once at the moment of creation. If you don't show it to the user then, it's gone forever. * **Middleware Order**: Always ensure the `auth:sanctum` middleware is applied before any ability checks in your route files to ensure the user is identified first.
Laravel Passport
Products
- Dec 11, 2025
- Dec 7, 2025