Laravel 12 API Authentication with Sanctum and CRUD
In this comprehensive step-by-step guide, you'll learn how to build a secure Laravel 12 RESTful API using Laravel Sanctum for token-based authentication. We'll also implement full CRUD operations for a Post
model, including creating, reading, updating, and deleting posts. This guide is ideal for developers who want to build modern APIs for single-page applications (SPAs), mobile apps, or other frontend clients.
Prerequisites
Make sure you have the following installed:
-
PHP 8.1+
-
Composer
-
Laravel 12
-
MySQL or MariaDB
-
Postman (for API testing)
Step 1: Create a New Laravel Project
Step 2: Install Sanctum
Step 3: Update User Model
In app/Models/User.php
:
Step 4: Configure Database
In your .env
file:
Then run:
Run this command in your terminal:
This command (if supported in your Laravel version) will automatically:
-
Create API route files (in
routes/api.php
)
Step 5: Define API Routes
In routes/api.php
:
Step 6: Create Authentication Controller
In app/Http/Controllers/API/AuthenticationController.php
Step 7: Create Post Model, Migration, and Controller
Update database/migrations/xxxx_xx_xx_create_posts_table.php
Run the migration
Step 8: Implement PostController Logic
Edit app/Http/Controllers/PostController.php
Step 9: Add Relationship to User Model
In app/Models/User.php
:
In app/Models/Post.php
:
Step 10: Run the Laravel Development Server
Step 11: Test API with Postman
Auth Endpoints
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/user | Bearer YOUR_TOKEN |
Logout | POST | http://localhost:8000/api/logout | Bearer YOUR_TOKEN |
Register Example:
Login Example:
Use the returned token as:
Post CRUD Endpoints
Action | Method | URL | Auth Header |
---|---|---|---|
Get All Posts | GET | http://localhost:8000/api/posts | Bearer YOUR_TOKEN |
Create Post | POST | http://localhost:8000/api/posts | Bearer YOUR_TOKEN |
View Post | GET | http://localhost:8000/api/posts/{id} | Bearer YOUR_TOKEN |
Update Post | PUT | http://localhost:8000/api/posts/{id} | Bearer YOUR_TOKEN |
Delete Post | DELETE | http://localhost:8000/api/posts/{id} | Bearer YOUR_TOKEN |
Create Post Example:
Update Post Example:
Summary
You now have a fully functional Laravel 12 REST API that supports:
-
Secure user registration and login
-
Token-based API access via Sanctum
-
Authenticated user information and logout
-
Full CRUD operations for posts
-
Authorization for all sensitive actions