laravel-casts
Eloquent-style casts for laravel-rust models. laravel-rust has no cast hook: a cast is the field's type
(like Encrypted<T>), so get is Decode + Serialize and set is Into<Value> + Deserialize.
Port of the casts in reynotech/laravel-query-builder-custom.
| PHP | Rust |
|---|---|
DateCast::class |
DateCast |
DateTimeCast::class |
DateTimeCast |
DateCast::SETPARSED |
DateCast<Parsed> |
DateCast::SETONLYMONTHYEAR |
DateCast<MonthYear> |
config('query_builder_custom.dates.value.*') |
laravel_casts::configure(DateConfig { value: DatePatterns { date, .. }, .. }) |
Install
laravel-rust does not compile without a database driver. Enable the feature of the one the application uses:
mysql, postgres or sqlite.
= { = "0.1", = ["mysql"] } # the typed casts
= { = "0.1", = ["mysql", "dynamic"] } # and the casts chosen by name
dynamic is off by default: it adds laravel_casts::dynamic and its dependencies
(serde_json, bigdecimal).
Typed casts
Patterns, parsing and the Day.js export come from php-dates; DateConfig is its type.
Call laravel_casts::configure(DateConfig { .. }) once at boot: Decode/Serialize get no application context.
The setting is one for the whole process, and the last call wins. A call while other threads read is safe, but the
setting is read once for each value, so a response being written at that moment can carry both.
Without Parsed, a request must send the storage format (Y-m-d); with it, the configured pattern too, where numbers
may come without their leading zeros (1/2/2026), as createFromFormat reads them. A DateCast read from text is at
midnight, also when its pattern has a time.
A DateCast holds a day: two casts of the same day are equal, whatever time new was given (datetime() still answers
it). From<Date>, From<DateTime> and, for DateTimeCast, From<Timestamp> (UTC) build one, so created_at and
updated_at can be DateTimeCast. An Option<DateTimeCast> timestamp and .year() on a column are not possible yet:
laravel-rust does not let another crate provide them.
Month and day names are in English.
What to know about the column:
DateCastreads aDATEandDateTimeCasta date and time column; the other way round is a decoding error.- A
DateTimeCastmade in code can carry a fraction of a second.laravel-rustcuts it to the connection'stime_precision(microseconds by default), and aDATETIMEwithout decimals then rounds it:23:59:59.6is stored as midnight of the next day. DeclareDATETIME(6), or settime_precision(0)on the connection. - MySQL's zero date (
0000-00-00) comes out of the driver asNULL:Nonein anOptionfield, an error in any other.
A cast of your own
Implement ColumnCast for a field whose column holds something else, and call impl_column_cast! once:
/// `800x600` in a text column.
impl_column_cast!;
That gives the type Decode, Nullable and Into<Value>, so it is a model field, also as Option<Size>. SQL NULL
is the one of Repr. Serde is the type's own (derive it, or go through String with serde(try_from, into), as the
Money example in the docs does). DateCast and DateTimeCast implement ColumnCast too, which is how to test them
without a database.
A newtype stored as its one field, with nothing to check or convert, needs none of this:
#[derive(laravel::Newtype)] does it. Enums are #[derive(laravel::db::Enum)] and JSON columns db::Json.
Serde is for the response, not for storage
Serialize writes the display pattern. The default ones, d/m/y and d/m/y h:i A, lose information: 1965-05-01 is
shown as 01/05/65, which reads back as 2065, and seconds are dropped. A cast without Parsed does not even read what
it shows. Prefer Y in configure for values that a form sends back.
For data (a JSON column, a cache, a queued job) write the storage format:
A fraction of a second is written with six digits (2026-01-31 10:05:00.500000) and read back; below a microsecond is
not kept.
It also reads the display pattern, so JSON already persisted by 0.1.0 can be loaded with the configuration that wrote it.
Custom format
Declare a format once with date_format! and use it as the cast's type parameter:
date_format!; // Feb - 2026, get and set
date_format!;
due_at: ,
A pattern can print and still be impossible to read (Y-W, or h:i without A). Check yours at boot, after
configure, or in a test: DateCast::<MonthDash>::check_format()?.
Tokens are those of php-dates 0.2: every token of PHP's DateTime::format(), in English.
Casts by name: cast_array
Needs the dynamic feature.
A typed cast is fixed when the program compiles. When the schema is data (a field definition that says
"cast": "date:true"), the cast arrives as text, the way Eloquent's $casts takes it. laravel_casts::dynamic is the port
of a PHP cast_array() helper over Eloquent casts, over serde_json values:
use ;
let casts = ;
// A form is on its way to storage.
let stored = cast_array?; // {"copies": 3, "issued": "2026-01-31", "tags": "[\"a\"]"}
// A row is on its way to the screen.
let shown = cast_array?;
Fields without a cast are left as they are. To read the casts once and apply them to many rows, use CastSet::parse(casts)?
and .apply(&row, mode); for one value, Caster::parse("decimal:2")?.get(&value).
| Cast | get |
set |
|---|---|---|
integer, int |
PHP's (int): "12abc" is 12, an array is 0 or 1; exact from i64::MIN to u64::MAX, an error beyond |
as it comes (integer is tidied to an integer; one that does not fit stays as it came) |
float, double, real |
PHP's (float); an array is an error |
as it comes (float and double are tidied) |
string |
(string): true is "1", 10.0 is "10" |
as it comes |
boolean, bool |
text is true only for 1, true, on, yes |
as it comes (boolean is tidied with filter_var) |
decimal[:places] |
text with the places asked (two by default, 65 at most), rounded half away from zero | as it comes |
array, json, json:unicode, collection, object |
JSON text is decoded (nested deeper than 127 levels is an error; PHP reads 512); an array passes through | json_encoded: slashes and, but for json:unicode, non-ASCII escaped |
DateCast, DateTimeCast (and the aliases) |
the stored date in the get format | with setParsing, the typed date in the set format becomes the stored one |
hashed |
the hash, as it is | a $2y$ hash within the configured rounds is kept, any other bcrypt hash is an error; other text is hashed with laravel::hash::make |
encrypted |
laravel::crypt::decrypt_string |
laravel::crypt::encrypt_string of the value as text |
encrypted:array, :json, :collection, :object |
decrypted, then read as JSON | the json_encode text, encrypted |
Like cast_array(), an empty text is not zero: it is left alone for integer, float, double and boolean. Names are
resolved through [Aliases]: date is DateCast, date_parsed is DateCast:true, date_month_year is
DateCast:true,m/Y,m/Y, and the Eloquent date casts are our own: datetime and immutable_datetime are DateTimeCast,
immutable_date is DateCast. Arguments after an alias go on to what it stands for (date:true,
datetime:true,d/m/Y H:i,d/m/Y H:i). An alias that already has arguments (date_parsed, date_month_year) takes no
more: date_parsed:true is an error. Pass your own with CastSet::parse_with. A class may carry its namespace (ReynoTECH\QueryBuilderCustom\Casts\DateCast:true,m/Y,m/Y).
A date cast's arguments are setParsing,getFormat,setFormat; without a format it uses the one given to configure.
A date is read from the storage format, then from a timestamp (10 or 13 digits), then from 2026-01-31, 2026/01/31,
2026-01-31 10:05[:00] and the ISO form with T and a zone (the wall time as written is kept). A number in the pattern
may come without its leading zeros (1/2/2026). Where that would be a guess it is not forgiven: anything but spaces
that PHP would drop before AM/PM (the seconds of 9:05:59 pm for h:i A), a Y year under four
digits, a pattern with a day name, a 12-hour clock without A, or two numbers with nothing between them.
A decimal takes at most 1,024 digits and an exponent of ±1000. The typed casts and the dynamic ones read the set
pattern with the same rule, but only the dynamic ones also take timestamps, the ISO forms and "" as nothing.
Your own casts by name
Implement dynamic::AttributeCast (get(&value), set(&value), set_async(&value)), the equivalent of the class
named in $casts. Add it by hand with CastSet::with(field, cast), or register it with a name with
Registry::with(name, factory); then CastSet::parse_in(casts, ®istry) reads "money:USD" beside "integer" and
"date". A registered name is read before the aliases, so Registry::with("date", ..) replaces the built-in date.
See the example in the docs of the trait.
cast_array takes either in its list: cast_array([("price", Cents)], &row, Mode::Get) for objects,
[("copies", "integer")] for texts, and [("copies", Spec::from("integer")), ("price", Spec::from(Cents))] for both (a
list has one type). Names that are yours go through cast_array_in(casts, ®istry, &row, mode) (and
cast_array_in_async).
The casts! macro writes that list without the wrapper, and the result goes wherever a list does:
let casts = casts! ;
cast_array?;
hashed and encrypted
They are the framework's: laravel::hash::make and laravel::crypt::{encrypt_string, decrypt_string}. The bcrypt rounds and
APP_KEY (with APP_PREVIOUS_KEYS) are the application's, so they work inside one; outside it they answer
CastError::Failed. What encrypted writes is what Laravel in PHP writes (encryptString), and the other way round:
tests/secrets.rs reads payloads and a bcrypt hash that PHP made with the same key, and its opt-in test has Laravel's
Encrypter and password_verify open what this crate wrote (CASTS_PHP_APP=/path/to/laravel/app, only its vendor
directory is used).
Hashing runs on the blocking pool, so a hashed cast is written with the _async forms: Caster::set_async,
CastSet::apply_async or cast_array_async. The synchronous set and cast_array answer
CastError::NeedsAsync for it (a null is still null). Everything else can use either.
Not supported, and an error rather than a guess: timestamp, custom_datetime, encrypted:json:unicode and the other Eloquent
casts. A cast that cannot be read, or a value it cannot take, is a CastError.
How it was checked
tests/oracle.rs replays 2,808 cases (26 casts, 54 values, both modes) against a real PHP cast_array() on PHP 8.5:
2,669 give the same answer, including the errors. tests/fixtures/generate.php makes the table again
(APP=/path/to/laravel/app php tests/fixtures/generate.php, with an application that has that helper).
tests/form.rs puts an invented form of 19 fields through the casts, 9 times, and compares what is stored and what is
shown with what PHP answered: 8 are identical (tests/fixtures/generate_form.php makes the table again).
The 139 that differ are on purpose, all dates:
- Carbon reads text that is only a number (
"1.5"," 7","-5") andfalseas a moment in 1970 or as now. Here they arenull. createFromFormat('m/Y', '01/2026')fills what the pattern lacks with today's day, so the result changes with the calendar (2026-01-02on the 2nd). Here it is the first of the month.createFromFormatlets month 13 roll over into the next January, and99/99/9999into a date in the year 10007. Here both arenull.- Month and day names are in English (
php-dates), where Carbon translates them. - A
Yyear under four digits is not read (5/2/26is year 26 in PHP), and a day name does not move the date. These two are not in the table.
The fixtures and the tests that read them are in the repository, not in the published package.
cargo test --features mysql,dynamic (or postgres, sqlite; without dynamic its tests are left out) needs no
server. tests/sqlite.rs runs the casts on a model over SQLite in memory (--features sqlite). tests/mysql.rs is opt-in: point
CASTS_MYSQL_URL at a MySQL server, then cargo test --features mysql --test mysql -- --ignored. tests/postgres.rs is opt-in too:
set LARAVEL_CASTS_TEST_POSTGRES_URL (PostgreSQL 13 or later, a user with CREATEDB), then
cargo test --features postgres --test postgres -- --ignored. Both create a database casts_<pid> and drop it.
cargo +nightly fuzz run dynamic feeds casts and values to the parser; cargo bench --features mysql,dynamic times
the hot paths.