Skip to main content

One post tagged with "Laravel"

View All Tags

Building Simple Todo REST API with PHP, Laravel, and PostgreSQL

· 4 min read
Huseyin BABAL
Software Developer

Introduction

In this tutorial, we’ll walk through building a basic Todo REST API using Laravel and PostgreSQL. Whether you’re looking to enhance your understanding of Laravel, or you're interested in integrating a PostgreSQL database into your project, this guide will provide you with the necessary steps to get up and running quickly.

Prerequisites

In this article, we will be using PostgreSQL as our database. You can maintain your database in any database management system. For a convenient deployment option, consider cloud-based solutions like Rapidapp, which offers managed PostgreSQL databases, simplifying setup and maintenance.

tip

Create a free database in Rapidapp in seconds here

Step-by-Step Implementation

Setting Up Your Laravel Project

First, let's create a new Laravel project. You can do this using Composer:

composer create-project --prefer-dist laravel/laravel laravel-todo-api

Next, navigate to the project directory:

cd laravel-todo-api

Configuring PostgreSQL Database

Open the .env file in the root directory of your Laravel project and update the database configuration to use PostgreSQL:

DB_CONNECTION=pgsql
DB_HOST=<host>
DB_PORT=<port>
DB_DATABASE=<database>
DB_USERNAME=<user>
DB_PASSWORD=<password>

Creating the Task Model and Migration

Run the following command to generate a model and migration for your tasks:

php artisan make:model Task -m

This command creates a Task model and a migration file located in the database/migrations directory.

Defining the Database Schema

Open the generated migration file in database/migrations and define the schema for the tasks table:

public function up()
{
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

Implementing the Task Model

To allow mass assignment, update the Task model (app/Models/Task.php) by adding the title, description, and completed attributes to the fillable array:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
use HasFactory;

protected $fillable = [
'title',
'description',
'completed',
];
}

Setting Up the API Routes

Define the routes for your API in the routes/web.php file. Laravel provides a convenient way to create RESTful routes using Route::apiResource:

use App\Http\Controllers\TaskController;

Route::apiResource('tasks', TaskController::class);

Creating the TaskController

Generate a controller for handling API requests:

php artisan make:controller TaskController --api

In the generated TaskController (app/Http/Controllers/TaskController.php), implement the methods to handle CRUD operations:

namespace App\Http\Controllers;

use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
public function index()
{
return Task::all();
}

public function store(Request $request)
{
$task = Task::create($request->all());
return response()->json($task, 201);
}

public function show($id)
{
return Task::findOrFail($id);
}

public function update(Request $request, $id)
{
$task = Task::findOrFail($id);
$task->update($request->all());
return response()->json($task, 200);
}

public function destroy($id)
{
Task::findOrFail($id)->delete();
return response()->json(null, 204);
}
}

Running the Laravel Application

To start your Laravel application, use the built-in development server:

php artisan serve

Your API will be accessible at http://127.0.0.1:8000/api/tasks.

Disabling CSRF for API Routes

Since this is a REST API, you can disable CSRF protection for API routes. Laravel handles this by default in the api middleware group. To manually configure it, you can exclude the api/* routes from CSRF protection in bootstrap/app.php:

...
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(
except: ['api/*']
);
})
...

Testing the API

List All Tasks

curl -X GET http://127.0.0.1:8000/api/tasks

Create a New Task

curl -X POST http://127.0.0.1:8000/api/tasks \
-H "Content-Type: application/json" \
-d '{
"title": "Buy groceries",
"description": "Milk, Bread, Cheese",
"completed": false
}'

Get a Specific Task

curl -X GET http://127.0.0.1:8000/api/tasks/1

Update a Task

curl -X PUT http://127.0.0.1:8000/api/tasks/1 \
-H "Content-Type: application/json" \
-d '{
"title": "Buy groceries and snacks",
"description": "Milk, Bread, Cheese, Chips",
"completed": false
}'

Delete a Task

curl -X DELETE http://127.0.0.1:8000/api/tasks/1

Conclusion

Congratulations! You've successfully built a simple Todo List REST API using Laravel and PostgreSQL. This foundation can be expanded with additional features, authentication, and more to create a fully functional web application.

Whether you're learning Laravel or looking to integrate a PostgreSQL database with your projects, this guide serves as a practical starting point.

tip

You can find the complete source code for this project on GitHub.