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.
The only change
Section titled “The only change”DB_HOST=old-postgresDB_HOST=machsql-hostNothing else changes: not the code, not the driver, not its version, not the SQL.
Versions
Section titled “Versions”- PHP 8.5 with
pdo_pgsql - illuminate/database 13.39 (the database layer of Laravel 13)
composer installexport DB_HOST=machsql-host DB_PASSWORD=...php main.phpExpected output: inserted todo <id>, <n> open.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.
<?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);{ "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/" } }}<?phpdeclare(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];}