Guide to building a secure Laravel 12 REST API using Laravel Sanctum for token-based authentication. Laravel Sanctum is a simple package for API token authentication and is ideal for SPAs or mobile apps.
Laravel 12 API Authentication with Sanctum
Prerequisites
Before starting, ensure you have:
-
PHP 8.1+
-
Composer
-
Laravel 12
-
MySQL or MariaDB
-
Postman (for testing)
Step 1: Create a Laravel 12 Project
Step 2: Install Laravel Sanctum
Step 3: Add HasApiTokens to User Model
In app/Models/User.php
, add:
Step 4: Configure Database
In your .env
file:
Then run:
Step 5: Create API Routes
If the a install:api
A command is available; run it in your terminal:
If the a install:api
A command is available; run it in your terminal:
This will automatically generate API controllers, routes, and configurations, and may also install any
Step 6: Define API Routes
Open routes/api.php
and add:
Step 7: Create Authentication Controller
Step 8: AuthenticationController Logic
Edit app/Http/Controllers/API/AuthenticationController.php
:
Step 9: Run the Server
Step 10: Test Routes in Postman
Action Method URL Auth Header Register POST http://localhost:8000/api/register - Login POST http://localhost:8000/api/login - Get User GET http://localhost:8000/api/get-user Bearer your_token
Logout POST http://localhost:8000/api/logout Bearer your_token
Action | Method | URL | Auth Header |
---|---|---|---|
Register | POST | http://localhost:8000/api/register | - |
Login | POST | http://localhost:8000/api/login | - |
Get User | GET | http://localhost:8000/api/get-user | Bearer your_token |
Logout | POST | http://localhost:8000/api/logout | Bearer your_token |
Step 1: Test API with Postman
Register
-
POST
http://127.0.0.1:8000/api/register
-
Body (JSON):
Login
-
POST
http://127.0.0.1:8000/api/login
-
Response will include the
token
.
Get Authenticated User
-
GET
http://127.0.0.1:8000/api/
get-user -
Header:
Logout
-
POST
http://127.0.0.1:8000/api/logout
-
Header:
Conclusion
You’ve now built a secure Laravel 12 REST API with:
-
User registration
-
Login with token generation
-
Protected routes using
auth:sanctum
-
Token-based logout