<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\ConnectionResolver;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Grammars\MySqlGrammar;
// Eloquent Model class for existing table "test"
class Test extends Model
{
protected $table = 'test';
protected $connection = 'default';
public $timestamps = false;
}
/* ### Configure Test model ### */
$pdo = new PDO('mysql:dbname=eloquent;host=127.0.0.1');
$connection = new Connection($pdo);
$connection->enableQueryLog();
$connection->setQueryGrammar(new MySqlGrammar());
$resolver = new ConnectionResolver([
'default' => $connection,
]);
Test::setConnectionResolver($resolver);
/* ### Work with Test model ### */
// Get all DB rows as Test instances and access columns
// with magic properties and ArrayAccess
$tests = Test::all();
foreach ($tests as $test) {
echo $test->id . ' - ' . $test->name . ' || ';
echo $test['id'] . ' - ' . $test['name'] . PHP_EOL;
}
// find one Test by id
$test = Test::find(2);
// A few methods of Eloquent models
dump(
$test->getAttribute('id'),
$test->isDirty('name'),
$test->toJson(),
json_encode($test),
$test->toArray(), // Including relations, but Test has none
$test->attributesToArray() // Without relations
);
$test->setAttribute('name', 'newname');
dump(
$test->getAttribute('name'),
$test->isDirty('name')
);
echo $test;
^ 2
^ false
^ "{"id":2,"name":"test","creation_date":"2014-07-20 10:40:22"}"
^ "{"id":2,"name":"test","creation_date":"2014-07-20 10:40:22"}"
^ array:3 [
"id" => 2
"name" => "test"
"creation_date" => "2014-07-20 10:40:22"
]
^ array:3 [
"id" => 2
"name" => "test"
"creation_date" => "2014-07-20 10:40:22"
]
^ "newname"
^ true