LaravelのORMのEloquentを単体で使う方法を解説する。
illuminate/database
をインストールする:
composer require illuminate/database
Eloquent単体での使い方:
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Schema\Blueprint;
$db = new DB();
$connectionName = 'default';
// DBの接続設定
$db->addConnection(
[
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'development',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_ja_0900_as_cs_ks',
],
$connectionName
);
// DBへのコネクションを取得する
$connection = $db->getConnection($connectionName);
// テーブルがなければ作る
$connection->getSchemaBuilder()->hasTable('user')
|| $connection->getSchemaBuilder()->create(
'user',
function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestamps();
}
);
// テーブルを空っぽにする
$connection->table('user')->truncate();
$now = new DateTimeImmutable();
// 1レコードinsertする
$connection->table('user')->insert(
[
'name' => 'alice',
'email' => 'alice@example.com',
'created_at' => $now,
'updated_at' => $now,
]
);
// insertしたレコードを取得する
$alice = $connection->table('user')->find(1);
// 期待したとおりのレコードが取れているか?
assert(
$alice == (object) [
'id' => 1,
'name' => 'alice',
'email' => 'alice@example.com',
'created_at' => $now->format('Y-m-d H:i:s'),
'updated_at' => $now->format('Y-m-d H:i:s'),
]
);