Article

Build a Task CRUD API in Laravel Rust and Laravel PHP with PostgreSQL

Build the same PostgreSQL-backed task API in Laravel PHP and Laravel Rust. Get complete code for all five CRUD endpoints, a shared smoke test, and a side-by-side comparison of the two implementations.

20 min readLanguage: EN EnglishFree0 claps0 comments
Engineering ArticlesAPILaravelPHPPostgreSQLRust
Reading options

A short code sample can show how Laravel Rust handles a request. A complete application shows what changes when that request reaches the database and an API client has to depend on the result. Here you'll build the same task API in Laravel PHP 13 and the Laravel Rust beta, using PostgreSQL and one test script for both versions.

The SQL and public response formats are intentionally similar. That makes it easier to compare how each framework validates input, maps rows, handles missing resources, and returns HTTP responses. For ecosystem and performance figures, see Laravel Rust vs. Laravel PHP on GAUAB.

1. Agree on the contract

Each task exposes an integer id, a title of up to 120 characters, and a description of up to 500 characters. Both text fields are required for creates and replacements, and each must contain a non-whitespace character. The list returns up to 50 tasks ordered by descending ID.

Request JSON body Success response
POST /api/tasks {"title":"Draft notes","description":"Summarize the release"} 201 with the created task
GET /api/tasks — 200 with {"data":[...]}
GET /api/tasks/{id} — 200 with the task
PUT /api/tasks/{id} {"title":"Publish notes","description":"Send the final version"} 200 with the replacement
DELETE /api/tasks/{id} — 204 with an empty body

Send Accept: application/json with each request and Content-Type: application/json when sending a body. Valid requests for missing numeric IDs return 404. Missing or invalid fields return 422. Error wording comes from each framework. The contract test focuses on HTTP status codes and successful JSON payloads.

2. Apply a common PostgreSQL schema

Create two development databases, one for each implementation. Use the same schema in both so you can test each service independently. If your local default database role can create databases and owns them afterwards, run createdb task_php and createdb task_rust. Otherwise, use your normal PostgreSQL tooling to create both databases and give your local application role access.

Save the following as schema.sql.

CREATE TABLE tasks (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title varchar(120) NOT NULL CHECK (length(btrim(title)) > 0),
    description varchar(500) NOT NULL CHECK (length(btrim(description)) > 0)
);

Apply it once to each database. Replace YOUR_USER with your PostgreSQL role name and enter its password when prompted.

psql "postgres://YOUR_USER@127.0.0.1:5432/task_php" -v ON_ERROR_STOP=1 -f schema.sql
psql "postgres://YOUR_USER@127.0.0.1:5432/task_rust" -v ON_ERROR_STOP=1 -f schema.sql

For production, track the schema in migrations and give one service or pipeline responsibility for applying them. The primary key supports the two queries that look up tasks by ID and list the most recent IDs. Laravel PHP migrations · Laravel Rust migrations

3. Build the Laravel PHP version

Install the PHP version required by Laravel 13, Composer, and the pdo_pgsql extension. In your workspace, scaffold a fresh Laravel app and enable API routing.

composer create-project laravel/laravel task-php "^13.0"
cd task-php
php artisan install:api

Set the PHP app's .env as follows. If your environment defines DB_URL, point it at the same database or remove it. Then run php artisan migrate for the framework's starter tables. The shared SQL has already created tasks.

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=task_php
DB_USERNAME=YOUR_USER
DB_PASSWORD=YOUR_LOCAL_PASSWORD

Create app/Http/Controllers/TaskController.php. This controller uses Laravel's database facade so the SQL stays visible. Eloquent is an option when this resource grows relationships, casts, or scopes.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

final class TaskController extends Controller
{
    public function index(): JsonResponse
    {
        $tasks = DB::select(
            'SELECT id, title, description FROM tasks ORDER BY id DESC LIMIT 50'
        );

        return response()->json([
            'data' => array_map(self::serializeTask(...), $tasks),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $input = $this->validatedInput($request);

        $task = DB::selectOne(
            'INSERT INTO tasks (title, description) VALUES (?, ?)
             RETURNING id, title, description',
            [$input['title'], $input['description']],
            false,
        );
        abort_if($task === null, 500);

        return response()->json(self::serializeTask($task), 201);
    }

    public function show(int $id): JsonResponse
    {
        $task = DB::selectOne(
            'SELECT id, title, description FROM tasks WHERE id = ?',
            [$id],
        );
        abort_if($task === null, 404);

        return response()->json(self::serializeTask($task));
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $input = $this->validatedInput($request);

        $task = DB::selectOne(
            'UPDATE tasks SET title = ?, description = ? WHERE id = ?
             RETURNING id, title, description',
            [$input['title'], $input['description'], $id],
            false,
        );
        abort_if($task === null, 404);

        return response()->json(self::serializeTask($task));
    }

    public function destroy(int $id): Response
    {
        $deleted = DB::delete('DELETE FROM tasks WHERE id = ?', [$id]);
        abort_if($deleted === 0, 404);

        return response()->noContent();
    }

    private function validatedInput(Request $request): array
    {
        return $request->validate([
            'title' => ['required', 'string', 'max:120', 'regex:/(*UCP)\S/u'],
            'description' => ['required', 'string', 'max:500', 'regex:/(*UCP)\S/u'],
        ]);
    }

    private static function serializeTask(object $task): array
    {
        return [
            'id' => (int) $task->id,
            'title' => $task->title,
            'description' => $task->description,
        ];
    }
}

The false argument in each write-and-return call selects the write PDO connection when a read/write configuration exists. PostgreSQL returns the updated representation in the same statement that performs the write. The controller reads from the validated array and maps raw database rows into the public response. Laravel PHP database · Laravel PHP validation

Add the following routes to routes/api.php. Keep any existing routes you need. The API registration supplies the /api prefix.

<?php

use App\Http\Controllers\TaskController;
use Illuminate\Support\Facades\Route;

Route::get('/tasks', [TaskController::class, 'index']);
Route::post('/tasks', [TaskController::class, 'store']);
Route::get('/tasks/{id}', [TaskController::class, 'show'])->whereNumber('id');
Route::put('/tasks/{id}', [TaskController::class, 'update'])->whereNumber('id');
Route::delete('/tasks/{id}', [TaskController::class, 'destroy'])->whereNumber('id');

Start the PHP app with php artisan serve --host=127.0.0.1 --port=8001. The task collection is at http://127.0.0.1:8001/api/tasks. Laravel PHP routing

4. Build the Laravel Rust version

Install the Laravel CLI, Rust 1.99 or later, and the scaffold's frontend prerequisites. From the parent workspace, create the second app.

laravel new task-rust --rust
cd task-rust

Set the generated .env to the Rust database. Use URI-encoded credentials if the PostgreSQL password contains special characters.

DB_CONNECTION=postgres
DATABASE_URL=postgres://YOUR_USER:YOUR_LOCAL_PASSWORD@127.0.0.1:5432/task_rust

Run laravel migrate for the framework tables. Check that src/app.rs registers .api(routes::api::routes). If your scaffold doesn't list Serde with its derive feature, run cargo add serde --features derive. Laravel Rust installation · Laravel Rust routing

Organize the Rust code by responsibility

A single route file can be convenient for an initial spike. Once the resource has five endpoints, keep routing, HTTP handling, and persistence in separate modules. This follows Laravel Rust's convention of putting resource handlers under src/http/handlers. Laravel Rust handlers

File Responsibility
src/routes/api.rs Registers HTTP methods, paths, and their handlers
src/http/handlers/tasks.rs Validates input, calls the repository, and chooses HTTP status codes and JSON responses
src/repositories/tasks.rs Runs parameterized PostgreSQL queries and maps the returned rows

Register the new modules. Add mod repositories; to src/lib.rs, the default crate root for the generated application library. If you've customized the [lib] path in Cargo.toml, add the declaration to that crate root. Add pub(crate) mod tasks; to the existing src/http/handlers/mod.rs. Create src/repositories/mod.rs with the same pub(crate) mod tasks; declaration. Retain the scaffold's existing module declarations.

Register the five routes

In src/routes/api.rs, import the task handlers and register these routes. Merge the registrations into your existing routes function if it already contains other endpoints. Laravel Rust routing

use crate::http::handlers::tasks;
use laravel::prelude::*;

pub fn routes(route: &mut Router) {
    route.get("/tasks", tasks::index);
    route.post("/tasks", tasks::store);
    route.get("/tasks/{id}", tasks::show);
    route.put("/tasks/{id}", tasks::update);
    route.delete("/tasks/{id}", tasks::destroy);
}

Put PostgreSQL queries in the repository

Create src/repositories/tasks.rs. Each operation returns a database outcome. For example, find returns None when the task doesn't exist, and delete reports whether it removed a row. The same functions can serve a console command or background job, which may handle those outcomes differently from an HTTP endpoint. Laravel Rust database queries

use laravel::db;

#[derive(db::FromRow, serde::Serialize)]
pub(crate) struct Task {
    id: i64,
    title: String,
    description: String,
}

pub(crate) async fn list() -> laravel::Result<Vec<Task>> {
    let tasks = db::query!(
        "SELECT id, title, description FROM tasks ORDER BY id DESC LIMIT 50"
    )
    .select_as::<Task>()
    .await?;

    Ok(tasks)
}

pub(crate) async fn create(title: String, description: String) -> laravel::Result<Option<Task>> {
    let task = db::query!(
        "INSERT INTO tasks (title, description) VALUES ({title}, {description})
         RETURNING id, title, description"
    )
    .insert_returning_as::<Task>()
    .await?;

    Ok(task)
}

pub(crate) async fn find(id: i64) -> laravel::Result<Option<Task>> {
    let task = db::query!(
        "SELECT id, title, description FROM tasks WHERE id = {id}"
    )
    .select_one_as::<Task>()
    .await?;

    Ok(task)
}

pub(crate) async fn replace(
    id: i64,
    title: String,
    description: String,
) -> laravel::Result<Option<Task>> {
    let task = db::query!(
        "UPDATE tasks SET title = {title}, description = {description}
         WHERE id = {id} RETURNING id, title, description"
    )
    .update_returning_as::<Task>()
    .await?;

    Ok(task)
}

pub(crate) async fn delete(id: i64) -> laravel::Result<bool> {
    let affected = db::query!("DELETE FROM tasks WHERE id = {id}")
        .delete()
        .await?;

    Ok(affected > 0)
}

db::FromRow maps named columns onto the Task type. The SQL selects exactly the three fields exposed by the API, so this example can serialize Task directly. Introduce a separate response struct if the persisted fields and the API representation start to differ. The braces in db::query! bind values as parameters. Integration tests still need to exercise these queries against the database schema.

Translate request and repository outcomes into HTTP responses

Create src/http/handlers/tasks.rs. The handlers use Valid<TaskInput> to receive validated data and Params<i64> to receive the numeric route parameter. They turn an absent record into 404 and choose the success status for each operation. Rust input validation · Rust JSON responses

use crate::repositories::tasks::{self, Task};
use laravel::prelude::*;

#[derive(serde::Serialize)]
pub(crate) struct TaskList {
    data: Vec<Task>,
}

#[laravel::input]
#[validate(anyone)]
pub(crate) struct TaskInput {
    #[validate(required, max_length(120), regex(r"\S"))]
    title: String,
    #[validate(required, max_length(500), regex(r"\S"))]
    description: String,
}

pub(crate) async fn index() -> laravel::Result<Json<TaskList>> {
    let data = tasks::list().await?;
    Ok(Json(TaskList { data }))
}

pub(crate) async fn store(
    Valid(input): Valid<TaskInput>,
) -> laravel::Result<(StatusCode, Json<Task>)> {
    let task = tasks::create(input.title, input.description)
        .await?
        .or_abort(500)?;

    Ok((StatusCode::CREATED, Json(task)))
}

pub(crate) async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Task>> {
    let task = tasks::find(id).await?.or_abort(404)?;
    Ok(Json(task))
}

pub(crate) async fn update(
    Params(id): Params<i64>,
    Valid(input): Valid<TaskInput>,
) -> laravel::Result<Json<Task>> {
    let task = tasks::replace(id, input.title, input.description)
        .await?
        .or_abort(404)?;

    Ok(Json(task))
}

pub(crate) async fn destroy(Params(id): Params<i64>) -> laravel::Result<StatusCode> {
    let deleted = tasks::delete(id).await?;
    let status = deleted.then_some(StatusCode::NO_CONTENT).or_abort(404)?;

    Ok(status)
}

For these single-table operations, the handler can call the repository directly. A service becomes helpful when an operation coordinates multiple writes, owns a transaction across modules, or applies business rules shared by several entry points. For example, if creating a task must also write an audit record, a service can own that transaction.

Run cargo check to verify the module declarations and handler signatures in your scaffold. Then start the service with laravel dev and use http://127.0.0.1:8000. The next section uses the same smoke test for both implementations.

5. Test both implementations with one script

Save the following as smoke.sh. It requires Bash, curl, and jq. The script creates its own record, uses the ID returned by the server, and deletes the task at the end. Run it only against the two local development databases.

#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 1 ]]; then
    printf 'Usage: bash smoke.sh http://127.0.0.1:PORT\n' >&2
    exit 2
fi

base="$1"
body=$(mktemp)
trap 'rm -f "$body"' EXIT

request() {
    local expected=$1
    shift
    local status
    status=$(curl -sS -o "$body" -w '%{http_code}' \
        -H 'Accept: application/json' \
        -H 'Content-Type: application/json' "$@")

    if [[ "$status" != "$expected" ]]; then
        printf 'Expected HTTP %s but got %s\n' "$expected" "$status" >&2
        cat "$body" >&2
        exit 1
    fi
}

request 422 -X POST "$base/api/tasks" -d '{"title":"Incomplete request"}'
request 422 -X POST "$base/api/tasks" -d '{"title":"   ","description":"Blank title"}'

request 201 -X POST "$base/api/tasks" \
    -d '{"title":"Draft notes","description":"Summarize the release"}'
id=$(jq -er '.id | select(type == "number")' "$body")
jq -e '.title == "Draft notes" and .description == "Summarize the release"' "$body" >/dev/null

request 200 "$base/api/tasks/$id"
jq -e --argjson id "$id" '.id == $id' "$body" >/dev/null

request 200 "$base/api/tasks"
jq -e --argjson id "$id" 'any(.data[]; .id == $id)' "$body" >/dev/null

request 422 -X PUT "$base/api/tasks/$id" -d '{"title":"Missing description"}'
request 200 -X PUT "$base/api/tasks/$id" \
    -d '{"title":"Publish notes","description":"Send the final version"}'
jq -e '.title == "Publish notes" and .description == "Send the final version"' "$body" >/dev/null

request 204 -X DELETE "$base/api/tasks/$id"
test ! -s "$body"
request 404 "$base/api/tasks/$id"
request 404 -X DELETE "$base/api/tasks/$id"

printf 'Task API contract checks passed for %s\n' "$base"
bash smoke.sh http://127.0.0.1:8001
bash smoke.sh http://127.0.0.1:8000

A failed assertion before the delete can leave a test record in the development database. Before a production migration, extend the checks for unusual Unicode, whitespace normalization, malformed JSON, out-of-range IDs, and concurrent writes. PHP's standard request middleware can normalize input before validation. If clients depend on that behavior, define it explicitly and test it in both services.

6. Compare what you just built

Decision Laravel PHP Laravel Rust
Code organization API routes delegate to TaskController, which validates requests and runs queries in this example. API routes delegate to task handlers. The handlers use a separate PostgreSQL repository.
Input boundary Rules validate a request and return an array. The handler receives a Valid<TaskInput> containing Rust strings.
Database mapping The controller normalizes PDO-backed row objects into arrays. The repository maps columns to a typed Task, which the handler serializes.
Missing task abort_if translates a missing row or zero affected rows to 404. The repository reports absence. The handler maps it to 404.
PostgreSQL writes selectOne reads the returned row from the configured write connection. Dedicated write-and-return methods map the result into Task.
Local command php artisan serve starts the development server. laravel dev starts the development services.
Benchmark baseline Use the same PHP runtime configuration you can deploy, including Octane if relevant. Use a release build and document the connection pool and worker configuration.

In both applications, UPDATE ... RETURNING changes the row and returns it in one database statement. That saves a query and returns the representation produced by that update. Concurrent editors can still overwrite one another with stale data. For collaborative editing, add a version column and make each update conditional on the version the caller last read.

For shared use, authenticate callers, scope every query to the owning workspace, and replace the fixed limit with cursor pagination. If you compare performance, keep the SQL, dataset, request mix, and PostgreSQL connection budget comparable. Measure p95 latency, error rate, CPU, and connection wait under load. Those measurements tell you which change is worth taking to production.

Start with GAUAB's Laravel Rust API tutorial · Read the broader Laravel PHP and Laravel Rust comparison

Featured Articles

Laravel Rust vs. Laravel PHP: Code, Performance, and Migration Trade-offs
EditorialEN
17 minFree

Laravel Rust vs. Laravel PHP: Code, Performance, and Migration Trade-offs

Compare Laravel Rust and Laravel PHP through the same API endpoint, Eloquent and typed queries, queues, deployment, and Laravel’s benchmark. Learn when to use Octane, stay on PHP, or move one workload to Rust.

Engineering ArticlesLaravelPerformancePHP
0 claps
Read
Laravel Rust in Practice: Build an API, Validate Requests, and Deploy It
EditorialEN
15 minFree

Laravel Rust in Practice: Build an API, Validate Requests, and Deploy It

Build your first API with the Laravel Rust beta. Learn typed validation, PostgreSQL models, async queues and workflows, and how to measure whether a Rust pilot is worth shipping.

Engineering ArticlesAPILaravelPostgreSQL
0 claps
Read
Laravel Go and Laravel Rust: A Practical Guide for PHP Teams
EditorialEN
7 minFree

Laravel Go vs. Laravel Rust: An Engineering Guide for PHP Teams

A hands-on comparison of Laravel Go, Laravel Rust, and PHP, with route examples, benchmark analysis, and a production migration plan.

Engineering Articles
0 claps
Read

Comments

0 comments

No approved comments are visible yet. New community replies may wait for moderation.