Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Type cast for Laravel Eloquent ORM. Tested on Laravel 4.2 Requires PHP 5.4
class SampleModel extends \Eloquent
{
use TypeCast;
protected $table = 'manufacturer';
protected $fillable = [];
protected $guarded = [
'id',
'created_at',
'updated_at'
];
// TypeCast usage:
protected $castedAttributes = [
'id' => 'int',
'status' => 'bool',
'created_at' => 'DateTime',
'updated_at' => 'DateTime',
];
}
<?php
/**
* Created by IntelliJ IDEA.
* User: janez
* Date: 2014.08.01.
* Time: 20:39
* Author: Janos Meszaros <m.janee@gmail.com>
*/
/**
* Usage: add in model
protected $castedAttributes = [
'id' => 'int',
'created_at' => 'DateTime',
'updated_at' => 'DateTime',
];
*/
use Carbon\Carbon;
trait TypeCast
{
// ---- Overrided Methods --------------------------------------------------
// Illuminate\Database\Eloquent\Model
/**
* Get an attribute from the $attributes array.
*
* @param string $key
* @return mixed
*/
protected function getAttributeFromArray($key)
{
if (array_key_exists($key, $this->attributes))
{
if ($this->isCastableAttribute($key))
return $this->castAttribute($key, $this->attributes[$key]);
return $this->attributes[$key];
}
}
/**
* @return mixed
*/
protected function getArrayableAttributes()
{
$attributes = $this->getArrayableItems($this->attributes);
foreach ($attributes AS $key=>$value)
if ($this->isCastableAttribute($key))
$attributes[$key] = $this->castAttribute($key, $value);
return $attributes;
}
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
* @return \Carbon\Carbon
*/
protected function asDateTime($value)
{
// If this value is an integer, we will assume it is a UNIX timestamp's value
// and format a Carbon object from this timestamp. This allows flexibility
// when defining your date fields as they might be UNIX timestamps here.
if (is_numeric($value))
{
return Carbon::createFromTimestamp($value);
}
// If the value is in simply year, month, day format, we will instantiate the
// Carbon instances from that format. Again, this provides for simple date
// fields on the database, while still supporting Carbonized conversion.
elseif (is_string($value) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value))
{
return Carbon::createFromFormat('Y-m-d', $value)->startOfDay();
}
// Finally, we will just assume this date is in the format used by default on
// the database connection and use that format to create the Carbon object
// that is returned back out to the developers after we convert it here.
elseif ( ! $value instanceof DateTime)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value);
}
return Carbon::instance($value);
}
// ---- TypeCast Methods ---------------------------------------------------
/**
* @param $key
* @param $value
* @return mixed
*/
public function setAttribute($key, $value)
{
if ($this->isCastableAttribute($key))
{
$value = $this->castAttribute($key, $value);
}
return parent::setAttribute($key, $value);
}
/**
* @return array
*/
function getCastedAttributes()
{
return is_array($this->castedAttributes) ? $this->castedAttributes : [];
}
/**
* @param $key
* @return bool
*/
function isCastableAttribute($key)
{
return is_array($this->castedAttributes) && array_key_exists($key, $this->castedAttributes);
}
/**
* @param $key
* @param $value
* @return array|bool|float|int|object|string
*/
protected function castAttribute($key, $value)
{
switch($this->castedAttributes[$key]):
case 'int':
case 'integer':
return intval($value);
case 'str':
case 'string':
return strval($value);
case 'float':
case 'double':
case 'real':
return floatval($value);
case 'bool':
case 'boolean':
return boolval($value);
case 'array':
return (array) $value;
case 'object':
return (object) $value;
default:
$type = $this->castedAttributes[$key];
return new $type($value);
endswitch;
}
}

TypeCast usage

class Something extends \Eloquent
{
  ..
    use TypeCast;
  ..
  
    protected $castedAttributes = [
        'id'            => 'int',
        'status'        => 'bool',
        'created_at'    => 'DateTime',
        'updated_at'    => 'DateTime',
    ];
  

Available Types:

  • int | integer
  • str | string
  • bool | boolean
  • float | double | real
  • array
  • object | objectName | DateTime | SomeClassName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment