Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,16 @@ protected function castAttribute($key, $value)
return $value;
}

switch ($this->getCastType($key)) {
$castType = $this->getCastType($key);

// If the cast type has a cast mutator, we will call that then return what
// it returns as the value, which is useful for transforming values on
// retrieval from the model to a form that is more useful for usage.
if ($this->hasCastMutator($castType)) {
return $this->{'cast'.Str::studly($castType).'Value'}($value);
}

switch ($castType) {
case 'int':
case 'integer':
return (int) $value;
Expand Down Expand Up @@ -507,6 +516,17 @@ protected function getCastType($key)
return trim(strtolower($this->getCasts()[$key]));
}

/**
* Determine if a cast mutator exists for an cast type.
*
* @param string $key
* @return bool
*/
public function hasCastMutator($key)
{
return method_exists($this, 'cast'.Str::studly($key).'Value');
}

/**
* Set a given attribute on the model.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1516,6 +1516,16 @@ public function testModelDateAttributeCastingResetsTime()
$this->assertEquals('1969-07-20 00:00:00', $arr['dateAttribute']);
}

public function testModelAttributeCustomCasting()
{
$model = new EloquentModelCastingStub;
$model->customAttribute = 'test';

$arr = $model->toArray();

$this->assertEquals('test1', $arr['customAttribute']);
}

public function testModelAttributeCastingPreservesNull()
{
$model = new EloquentModelCastingStub;
Expand Down Expand Up @@ -2008,12 +2018,18 @@ class EloquentModelCastingStub extends Model
'dateAttribute' => 'date',
'datetimeAttribute' => 'datetime',
'timestampAttribute' => 'timestamp',
'customAttribute' => 'custom',
];

public function jsonAttributeValue()
{
return $this->attributes['jsonAttribute'];
}

public function castCustomValue($value)
{
return $value.'1';
}
}

class EloquentModelDynamicHiddenStub extends \Illuminate\Database\Eloquent\Model
Expand Down