Skip to content

Commit

Permalink
Merge branch 'pr/26882' of https://github.com/themsaid/framework into…
Browse files Browse the repository at this point in the history
… themsaid-pr/26882
  • Loading branch information
taylorotwell committed Feb 2, 2018
2 parents b8b26c0 + f8abc3f commit 1e4bca5
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
($value === 'date' || $value === 'datetime')) {
$attributes[$key] = $this->serializeDate($attributes[$key]);
}

if ($attributes[$key] && Str::startsWith($value, ['date:', 'datetime:'])) {
$attributes[$key] = $attributes[$key]->format(explode(':', $value, 2)[1]);
}
}

return $attributes;
Expand Down Expand Up @@ -488,6 +492,7 @@ protected function castAttribute($key, $value)
case 'date':
return $this->asDate($value);
case 'datetime':
case 'custom_datetime':
return $this->asDateTime($value);
case 'timestamp':
return $this->asTimestamp($value);
Expand All @@ -504,6 +509,10 @@ protected function castAttribute($key, $value)
*/
protected function getCastType($key)
{
if (Str::startsWith($this->getCasts()[$key], ['date:', 'datetime:'])) {
return 'custom_datetime';
}

return trim(strtolower($this->getCasts()[$key]));
}

Expand Down
51 changes: 51 additions & 0 deletions tests/Integration/Database/EloquentModelDateCastingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Illuminate\Tests\Integration\Database\EloquentModelDateCastingTest;

use Carbon\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;

/**
* @group integration
*/
class EloquentModelDateCastingTest extends DatabaseTestCase
{
public function setUp()
{
parent::setUp();

Schema::create('test_model1', function ($table) {
$table->increments('id');
$table->date('date_field')->nullable();
$table->datetime('datetime_field')->nullable();
});
}

public function test_user_can_update_nullable_date()
{
$user = TestModel1::create([
'date_field' => '2019-10-01',
'datetime_field' => '2019-10-01 10:15:20',
]);

$this->assertEquals('2019-10', $user->toArray()['date_field']);
$this->assertEquals('2019-10 10:15', $user->toArray()['datetime_field']);
$this->assertInstanceOf(Carbon::class, $user->date_field);
$this->assertInstanceOf(Carbon::class, $user->datetime_field);
}
}

class TestModel1 extends Model
{
public $table = 'test_model1';
public $timestamps = false;
protected $guarded = ['id'];
protected $dates = ['date_field', 'datetime_field'];

public $casts = [
'date_field' => 'date:Y-m',
'datetime_field' => 'datetime:Y-m H:i',
];
}

0 comments on commit 1e4bca5

Please sign in to comment.