Sanctum tokens

Contents
Issue tokens
Use Bearer
Revoke
Abilities note

Issue tokens

Phones and scripts cannot keep a login cookie, so they use tokens instead. CreateToken mints one token tied to the user and returns the plain value a single time.

Show it to the user now, since only a hash stays in the database after that.

$token = $user->createToken("phone")->plainTextToken; echo $token;

Use Bearer

Clients prove identity by sending the token on every API call. The value travels in the Authorization header after the Bearer word.

Sanctum reads that header and loads the matching user for the request.

Authorization: Bearer PASTE_TOKEN_HERE

Revoke

Tokens must die when devices are lost or users log out everywhere. Deleting the user tokens ends every session tied to them at once.

The plain values stop working right away, with no config change needed.

$user->tokens()->delete();

Abilities note

Abilities limit what one token may do, like read-only access to orders. Pass the list at creation and check it with tokenCan before risky work.

Small scopes keep a leaked token from doing wide damage.

$token = $user->createToken("phone", ["orders:read"])->plainTextToken; if ($request->user()->tokenCan("orders:read")) { echo "allowed"; }

Next: API resources

Article author: Arthur Isaev

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: