Introduction
Laravel 12 is the latest version of the popular PHP framework, known for its elegance and simplicity. In this guide, we'll walk through building a REST API to manage a simple "Task" resource. We'll cover setup, routing, controllers, models, and testing the API using Postman.
Prerequisites
- PHP 8.2 or higher
- Composer installed
- Laravel 12 installed
- A database (e.g., MySQL, SQLite)
- Postman or a similar API testing tool
Step 1: Set Up Your Laravel Project
Start by creating a new Laravel project using Composer:
composer create-project laravel/laravel task-api
Navigate to the project directory and start the development server:
cd task-api
php artisan serve
Configure your .env
file to connect to your database:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=task_api
DB_USERNAME=root
DB_PASSWORD=
Step 2: Create the Task Model and Migration
Generate a model with a migration file for the Task resource:
php artisan make:model Task -m
Edit the migration file in database/migrations/
to define the tasks table:
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description')->nullable();
$table->boolean('completed')->default(false);
$table->timestamps();
});
Run the migration to create the table:
php artisan migrate
Update the Task
model in app/Models/Task.php
to define fillable fields:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $fillable = ['title', 'description', 'completed'];
}
Step 3: Create the API Controller
Generate a resourceful controller for the Task API:
php artisan make:controller API/TaskController --api --model=Task
Edit app/Http/Controllers/API/TaskController.php
to handle CRUD operations:
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\Task;
use Illuminate\Http\Request;
class TaskController extends Controller
{
public function index()
{
return Task::all();
}
public function store(Request $request)
{
$request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string',
'completed' => 'boolean',
]);
$task = Task::create($request->all());
return response()->json($task, 201);
}
public function show(Task $task)
{
return $task;
}
public function update(Request $request, Task $task)
{
$request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string',
'completed' => 'boolean',
]);
$task->update($request->all());
return response()->json($task);
}
public function destroy(Task $task)
{
$task->delete();
return response()->json(null, 204);
}
}
Step 4: Define API Routes
In routes/api.php
, define the resourceful routes for the Task API:
use App\Http\Controllers\API\TaskController;
Route::apiResource('tasks', TaskController::class);
This sets up the following endpoints:
GET /api/tasks
- List all tasksPOST /api/tasks
- Create a new taskGET /api/tasks/{id}
- Show a taskPUT/PATCH /api/tasks/{id}
- Update a taskDELETE /api/tasks/{id}
- Delete a task
Step 5: Test the API with Postman
Use Postman to test your API endpoints:
- Create a Task: Send a POST request to
http://localhost:8000/api/tasks
with JSON body:{ "title": "Sample Task", "description": "This is a test task", "completed": false }
- List Tasks: Send a GET request to
http://localhost:8000/api/tasks
- Update a Task: Send a PUT request to
http://localhost:8000/api/tasks/1
with updated JSON data - Delete a Task: Send a DELETE request to
http://localhost:8000/api/tasks/1
Step 6: Secure Your API (Optional)
To secure your API, consider using Laravel Sanctum or Passport for authentication. For Sanctum, install it:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Add middleware to your API routes in routes/api.php
:
Route::middleware('auth:sanctum')->apiResource('tasks', TaskController::class);
Conclusion
You've now built a fully functional REST API with Laravel 12! You can extend this API by adding authentication, validation, or additional resources. Laravel's ecosystem makes it easy to scale and maintain your API.
Explore more Laravel features like middleware, request validation, and Eloquent relationships to enhance your API further.