LoginSignup
7
3

More than 5 years have passed since last update.

EloquentをLaravelなしに使う

Posted at

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'),
    ]
);
7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3