Skip to content

Instantly share code, notes, and snippets.

@Quiss
Created July 27, 2022 15:24
Show Gist options
  • Save Quiss/9bd87b9c53cf77dd284486140d4ee078 to your computer and use it in GitHub Desktop.
Save Quiss/9bd87b9c53cf77dd284486140d4ee078 to your computer and use it in GitHub Desktop.
<?php
namespace Illuminate\Tests\Integration\Database\EloquentModelDateCastingTest;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
class EloquentModelDateCastingTest extends DatabaseTestCase
{
protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
{
Schema::create('test_model1', function (Blueprint $table) {
$table->increments('id');
$table->date('date_field')->nullable();
});
}
public function testDirtyWithNewInstance()
{
$model = new TestModel1;
$this->assertFalse($model->wasChanged('date_field')); // ok
$this->assertFalse($model->isDirty('date_field')); // ok
$this->assertTrue($model->isClean('date_field')); // ok
$some = $model->date_field;
$this->assertFalse($model->wasChanged('date_field')); // ok
$this->assertFalse($model->isDirty('date_field')); // failed
$this->assertTrue($model->isClean('date_field')); // failed
}
public function testDirtyAfterFind()
{
TestModel1::create([
'date_field' => '2019-10-01',
]);
$model = TestModel1::first();
$some = $model->date_field;
$this->assertArrayNotHasKey('date_field', $model->getDirty());
}
}
class TestModel1 extends Model
{
public $table = 'test_model1';
public $timestamps = false;
protected $guarded = [];
public $casts = [
'date_field' => DateObjectCaster::class,
];
}
class DateObjectCaster implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return \Illuminate\Support\Carbon::createFromDate($value);
}
public function set($model, $key, $value, $attributes)
{
return $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment