REST APIs are the backbone of modern applications such as mobile apps, SPAs, and third-party integrations. Laravel makes API development clean, secure, and scalable.
In this tutorial, you’ll learn how to create a REST API in Laravel from scratch, including:
REST (Representational State Transfer) is an architectural style that uses HTTP methods:
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create data |
| PUT | Update data |
| DELETE | Remove data |
Create a new Laravel project:
composer create-project laravel/laravel laravel-apiMove into the project directory:
cd laravel-apiStart the server:
php artisan serveEdit your .env file:
DB_DATABASE=laravel_api
DB_USERNAME=root
DB_PASSWORD=Run migrations:
php artisan migrateWe’ll create a Post API example.
php artisan make:model Post -mEdit migration file:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});Run migration:
php artisan migratephp artisan make:controller API/PostControllerOpen routes/api.php:
use App\Http\Controllers\API\PostController;
Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store']);
Route::get('/posts/{id}', [PostController::class, 'show']);
Route::put('/posts/{id}', [PostController::class, 'update']);
Route::delete('/posts/{id}', [PostController::class, 'destroy']);All routes under api.php are prefixed with /api
Open PostController.php:
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return response()->json(Post::all(), 200);
}
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required',
'description' => 'required',
]);
$post = Post::create($validated);
return response()->json($post, 201);
}
public function show($id)
{
return response()->json(Post::findOrFail($id), 200);
}
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return response()->json($post, 200);
}
public function destroy($id)
{
Post::destroy($id);
return response()->json(['message' => 'Post deleted'], 200);
}
}Edit Post.php model:
protected $fillable = ['title', 'description'];POST /api/posts
{
"title": "Laravel REST API",
"description": "Step-by-step tutorial"
}GET /api/posts
PUT /api/posts/1
DELETE /api/posts/1
Open terminal and run:
git clone https://github.com/Yash000p/REST-API-in-Laravel.git
I'm a dedicated full-stack developer with expertise in building and managing dynamic web applications across both frontend and backend.