Laravel 12 API Authentication with Passport + Post CRUD
Tutorial for building a Laravel 12 RESTful API with Passport authentication and CRUD functionality for a Post
model. This guide is ideal for APIs that will be consumed by SPAs, mobile apps, or third-party clients using OAuth2 tokens.
Prerequisites
Make sure the following are installed:
-
PHP 8.1+
-
Composer
-
Laravel 12
-
MySQL or MariaDB
-
Postman (for API testing)
Step 1: Create a New Laravel Project
Step 2: Configure Database
Update .env
:
Step 3: Install Laravel Passport
Install Passport:
Step 4: Configure Passport
config/auth.php
Change the API guard driver to passport
:
Step 5: Update User Model
In app/Models/User.php
:
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 6: Define API Routes
In Update routes/api.php
:
Step 7: Create Authentication Controller
In app/Http/Controllers/API/AuthenticationController.php
:
Step 8: Create Post Model, Migration, and Controller
Update migration in database/migrations/xxxx_create_posts_table.php
:
Run migration:
Step 9: PostController Logic
In app/Http/Controllers/PostController.php
:
Step 10: Define Relationships
app/Models/User.php
app/Models/Post.php
Step 11: Personal
To create a personal access client in Laravel, you can use the following Artisan command:
To create a personal access client in Laravel, you can use the following Artisan command:
Step 12: Start Server
Step 13: API Testing in Postman
Auth Endpoints
Action | Method | URL | Auth Header |
---|---|---|---|
Register | POST | http://localhost:8000/api/register | – |
Login | POST | http://localhost:8000/api/login | – |
Get User Info | GET | http://localhost:8000/api/user | Bearer YOUR_TOKEN |
Logout | POST | http://localhost:8000/api/logout | Bearer YOUR_TOKEN |
Example Request (Register)
Example Request (Login)
After login, you'll get a response like:
Use that token in the Authorization tab in Postman:
-
Type: Bearer Token
-
Token:
paste_your_token_here
Post CRUD Endpoints
Action | Method | URL | Auth Header |
---|---|---|---|
Get All | GET | http://localhost:8000/api/posts | Bearer YOUR_TOKEN |
Create | POST | http://localhost:8000/api/posts | Bearer YOUR_TOKEN |
View One | GET | http://localhost:8000/api/posts/{id} | Bearer YOUR_TOKEN |
Update | PUT | http://localhost:8000/api/posts/{id} | Bearer YOUR_TOKEN |
Delete | DELETE | http://localhost:8000/api/posts/{id} | Bearer YOUR_TOKEN |
Example Create Post Request
Example Update Post Request
Summary
You now have a fully functional Laravel 12 API with:
-
✅ User Registration & Login
-
✅ Passport Token Authentication
-
✅ Protected API Endpoints
-
✅ Full CRUD for Posts
-
✅ Ready for Postman/API Client