Skip to content

PHP: Laravel (Eloquent)

Uses Laravel’s schema builder and Eloquent outside a full application. In a Laravel application the same change is the DB_HOST line in .env; config/database.php stays as it is. The code is the same against the original database and against MachSQL; only the address changes.

DB_HOST=old-postgres
DB_HOST=machsql-host

Nothing else changes: not the code, not the driver, not its version, not the SQL.

  • PHP 8.5 with pdo_pgsql
  • illuminate/database 13.39 (the database layer of Laravel 13)
Terminal window
composer install
export DB_HOST=machsql-host DB_PASSWORD=...
php main.php

Expected output: inserted todo <id>, <n> open.

The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.

main.php
<?php
// Laravel's database layer (illuminate/database: query builder, schema builder, Eloquent).
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use App\Todo;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'pgsql',
'host' => getenv('DB_HOST'), // the only value that changes
'port' => getenv('DB_PORT') ?: '5432',
'database' => getenv('DB_DATABASE') ?: 'app',
'username' => getenv('DB_USERNAME') ?: 'app',
'password' => getenv('DB_PASSWORD'),
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = Capsule::schema();
if (!$schema->hasTable('eloquent_todo')) {
$schema->create('eloquent_todo', function (Blueprint $table): void {
$table->id();
$table->string('title');
$table->boolean('done')->default(false);
});
}
$todo = Todo::create(['title' => 'write the examples']);
$open = Todo::where('done', false)->count();
printf("inserted todo %d, %d open\n", $todo->id, $open);
composer.json
{
"name": "machsql/example-php-laravel",
"description": "Laravel's database layer (Eloquent) against MachSQL",
"type": "project",
"require": {
"php": "^8.5",
"illuminate/database": "^13.39"
},
"autoload": { "psr-4": { "App\\": "src/" } }
}
src/Todo.php
<?php
declare(strict_types=1);
namespace App;
use Illuminate\Database\Eloquent\Model;
final class Todo extends Model
{
protected $table = 'eloquent_todo';
public $timestamps = false;
protected $fillable = ['title', 'done'];
protected $attributes = ['done' => false];
}