Last active
February 21, 2022 12:44
-
-
Save isometriq/b947e940913ecdc984e767ad4ba3d06a to your computer and use it in GitHub Desktop.
Eloquent Model Automatic Cast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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