Skip to content

Instantly share code, notes, and snippets.

@isometriq
Last active February 21, 2022 12:44
Show Gist options
  • Save isometriq/b947e940913ecdc984e767ad4ba3d06a to your computer and use it in GitHub Desktop.
Save isometriq/b947e940913ecdc984e767ad4ba3d06a to your computer and use it in GitHub Desktop.
Eloquent Model Automatic Cast
namespace App\Models;
use DB;
use Illuminate\Database\Eloquent\Model as BaseModel;
abstract class Model extends BaseModel
{
static $automaticCasts = [];
public function __construct(array $attributes = [])
{
$this->casts = array_merge($this->getAutomaticCasts(), $this->casts);
parent::__construct($attributes);
}
public function getAutomaticCasts()
{
$table = $this->getTable();
if (!isset($this::$automaticCasts[$table]))
{
$columns = DB::getDoctrineSchemaManager()->listTableColumns($table);
$this::$automaticCasts[$table] = [];
foreach ($columns as $column)
{
$type = $column->getType()->getName();
// exclude string conversion to speed up, as the database returns data already in string format
if ($type != 'string') {
$this::$automaticCasts[$table][$column->getName()] = $column->getType()->getName();
}
}
}
return $this::$automaticCasts[$table];
}
}
namespace App\Models;
class User extends Model
{
var $casts = [
// Nothing to cast! ..except if you want to override automatic default
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment