Introduction
In today’s web development world, RESTful APIs play a major role in connecting frontend applications, mobile apps, and third-party services with backend systems. APIs allow different applications to communicate with each other efficiently.
Among PHP frameworks, Laravel is one of the most popular choices for building REST APIs. Its powerful Eloquent ORM, routing system, and built-in tools like Sanctum and Passport make it easier to develop secure and scalable APIs.
In this guide, we’ll walk through the process of creating a RESTful API in Laravel step by step. By the end, you’ll have a fully functional API that can handle CRUD (Create, Read, Update, Delete) operations and authentication.
Step 1: Setting Up a Laravel Project
First, make sure you have Composer installed. Then create a new Laravel project:
Your project will be available at:
👉 http://127.0.0.1:8000
Step 2: Configure Database
Open the .env
file and configure your database:
Then create the database in MySQL:
Step 3: Create Migration and Model
Let’s create a Post model for our blog API:
This will create:
- Model:
app/Models/Post.php
- Migration:
database/migrations/xxxx_xx_xx_create_posts_table.php
Update the migration file:
Run migration:
Step 4: Create Controller
Generate a controller for handling API requests:
This creates PostController
with REST methods.
Step 5: Define API Routes
Open routes/api.php
and add:
This automatically creates routes:
GET /api/posts
→ List all postsPOST /api/posts
→ Create a new postGET /api/posts/{id}
→ Show a single postPUT /api/posts/{id}
→ Update a postDELETE /api/posts/{id}
→ Delete a post
Step 6: Implement Controller Logic
In app/Http/Controllers/Api/PostController.php
:
Also, update Post.php
model:
Step 7: Format Responses with API Resources
Laravel provides API Resources for clean JSON responses.
Create resource:
In app/Http/Resources/PostResource.php
:
Use it in PostController
:
Step 8: Authentication with Laravel Sanctum
Install Sanctum for token-based authentication:
Add HasApiTokens
to User
model:
Update config/auth.php
:
Create auth routes in api.php
:
Step 9: Error Handling & Validation
Laravel automatically handles validation errors with JSON response:
For custom errors, use:
Step 10: Test with Postman
POST /api/register
→ Create userPOST /api/login
→ Get token- Use token in Authorization → Bearer Token
- Test CRUD endpoints for
posts