What is BaseEntity casting in CodeIgniter 4?

Answer

CI4's Entity casting system automatically converts data types when getting or setting Entity properties. Built-in cast types: integer, float, string, boolean, json (encodes/decodes JSON automatically), array, csv (comma-separated values), datetime (returns a Time object), timestamp, uri. Define casts: protected $casts = ["is_admin" => "boolean", "metadata" => "json", "tags" => "csv", "created_at" => "datetime"]. Custom cast types: implement CastInterface and register in the model. Nullable casts: "age" => "?integer". Casting in entities greatly reduces data transformation boilerplate — setting $entity->tags = ["php", "ci4"] automatically serializes to CSV, and getting $entity->tags returns an array. This brings CI4 models closer to Eloquent's casting functionality.