Laravel 9 Sanctum API Authentication
Step 1: Install Laravel 9 (Optional)
If you haven't created your Laravel app yet:
Step 2: Install Laravel Sanctum
Install Sanctum via Composer:
Publish Sanctum’s config file:
Run database migrations to create Sanctum's tables:
Step 3: Sanctum Configuration
Add Middleware
Open app/Http/Kernel.php
and update the api
middleware group:
Modify User.php
Model
Edit app/Models/User.php
to include the Sanctum trait:
Step 4: Create API Routes
Edit routes/api.php
:
Step 5: Create Controller Files
Create a folder: app/Http/Controllers/API/
and then:
BaseController.php
RegisterController.php
Step 6: Run the Laravel App
Start the Laravel development server:
Your app will be running at http://localhost:8000
.
Step 7: Test APIs Using Postman
Set Headers in Postman:
API Endpoints:
Action | Method | Endpoint |
---|---|---|
Register | POST | http://localhost:8000/api/register |
Login | POST | http://localhost:8000/api/login |
Get Users | GET | http://localhost:8000/api/users |
Note: Use the token from login response as the Bearer token for accessing protected routes.
Optional: Clone Project from GitLab