Expand description
PHP and Laravel formatting for Laravel for Rust applications. The Rust functions
are re-exported from core, and the service provider makes them available in MiniJinja
templates. English is the default for numbers and dates. Locale arguments select other outputs.
§Install
cargo add laravel-rust-formatRegister the provider in your application builder:
use laravel::Application;
use laravel_rust_format::FormattingServiceProvider;
let _builder = Application::configure().with_providers(|providers| {
providers.add(FormattingServiceProvider);
});This enables the filters when your application renders HTML with the framework’s MiniJinja
engine. For a standalone environment, call the register_filters function with a
FormattingConfig. Disable default features to use the provider and Rust API without
enabling MiniJinja, Markdown or random helpers. To register filters without Markdown,
enable just the minijinja feature.
§Configuration
| Environment variable | Default | Effect |
|---|---|---|
FORMATTING_CURRENCY | USD | Default currency for number_currency. The provider validates it against the ISO 4217 current currency and funds list at boot. |
FORMATTING_TIMEZONE | UTC | Display timezone for Unix seconds, serialized timestamps ending in Z and php_date. The provider validates the zone at boot. |
FORMATTING_MAX_OUTPUT_BYTES | 8388608 | Maximum raw bytes per call, before MiniJinja autoescaping. |
FORMATTING_MAX_COLLECTION_ITEMS | 100000 | Maximum collection entries per call, including nested entries. |
§Filter reference
Pass optional arguments positionally in the order shown, or by name. none denotes an
omitted argument unless otherwise specified.
| Filter or function | Arguments | PHP or Laravel equivalent | Example → output |
|---|---|---|---|
number_format | decimals=0, dec_point=".", thousands_sep="," | number_format() | 1234.5 | number_format(2) → 1,234.50 |
php_round | precision=0, mode= | round() with a PHP mode name or integer | 3.5 | php_round | php_echo → 4 |
php_echo | echo $number | 1.0e20 | php_echo → 1.0E+20 | |
ucfirst | ucfirst() | "apple" | ucfirst → Apple | |
php_lcfirst | lcfirst() | "Apple" | php_lcfirst → apple | |
php_ucwords | separators=none | ucwords() | "red-apple" | php_ucwords("-") → Red-Apple |
php_strtolower | strtolower() | "ÉTÉ" | php_strtolower → ÉtÉ | |
php_strtoupper | strtoupper() | "été" | php_strtoupper → éTé | |
str_limit | limit=100, end="...", preserve_words=false | Str::limit() | "hello" | str_limit(3) → hel... |
str_words | words=100, end="..." | Str::words() | "one two three" | str_words(2) → one two... |
str_slug | separator="-", language="en" | Str::slug() | "Café Noir" | str_slug → cafe-noir |
str_ascii | language="en" | Str::ascii() | "café" | str_ascii → cafe |
str_title | Str::title() | "red apple" | str_title → Red Apple | |
str_headline | Str::headline() | "first_name" | str_headline → First Name | |
str_ucfirst | Str::ucfirst() | "été" | str_ucfirst → Été | |
str_lcfirst | Str::lcfirst() | "Été" | str_lcfirst → été | |
str_upper | Str::upper() | "été" | str_upper → ÉTÉ | |
str_lower | Str::lower() | "ÉTÉ" | str_lower → été | |
str_plural | count=2, prepend_count=false | Str::plural() | "city" | str_plural(3, true) → 3 cities |
str_singular | Str::singular() | "cities" | str_singular → city | |
plural(word, count) | Both required | Str::plural() without prepending the count | plural("city", 3) → cities |
number_format_intl | precision=none, max_precision=none, locale=none | Number::format() | 2.5 | number_format_intl(0) → 2 |
number_file_size | precision=0, max_precision=none, locale=none | Number::fileSize() | 1536 | number_file_size(1) → 1.5 KB |
number_percentage | precision=0, max_precision=none, locale=none | Number::percentage() | 2.5 | number_percentage(1) → 2.5% |
number_currency | code=config.currency, precision=none, locale=none | Number::currency() | 42 | number_currency("EUR") → €42.00 |
number_abbreviate | precision=0, max_precision=none, locale=none | Number::abbreviate() | 1500 | number_abbreviate(1) → 1.5K |
number_for_humans | precision=0, max_precision=none, abbreviate=false, locale=none | Number::forHumans() | 1500 | number_for_humans(1) → 1.5 thousand |
number_ordinal | locale=none | Number::ordinal() | 21 | number_ordinal → 21st |
carbon_format | format (required, PHP date letters) | Carbon::format() | "2026-12-03" | carbon_format("D, M j") → Thu, Dec 3 |
carbon_iso8601 | Carbon::toIso8601String() | "2026-12-03" | carbon_iso8601 → 2026-12-03T00:00:00+00:00 | |
carbon_iso_string | Carbon::toISOString() | "2026-12-03" | carbon_iso_string → 2026-12-03T00:00:00.000000Z | |
carbon_date_string | Carbon::toDateString() | "2026-12-03T16:30:00+01:00" | carbon_date_string → 2026-12-03 | |
diff_for_humans | other=none, short=false, parts=1, join=false, just_now=false. See below for keyword options. | Carbon::diffForHumans() | "2026-12-02" | diff_for_humans("2026-12-03") → 1 day before |
php_nl2br | is_xhtml=true | nl2br | "<b>line</b>\nnext"|php_nl2br(is_xhtml=false) → <b>line</b><br>\nnext |
php_str_pad | length, pad=" ", side=1 | str_pad | "x"|php_str_pad(4, "-", side=2) → -x-- |
php_wordwrap | width=75, line_break="\n", cut_long_words=false | wordwrap | "one two"|php_wordwrap(4, " / ") → one / two |
php_strip_tags | allowed_tags=none | strip_tags | "<b>bold</b><i>italic</i>"|php_strip_tags(["b"]) → <b>bold</b>italic |
str_after | search | Str::after | "id:42"|str_after(":") → 42 |
str_after_last | search | Str::afterLast | "a:b:c"|str_after_last(":") → c |
str_before | search | Str::before | "id:42"|str_before(":") → id |
str_before_last | search | Str::beforeLast | "a:b:c"|str_before_last(":") → a:b |
str_between | from, to | Str::between | "[a][b]"|str_between("[", "]") → a][b |
str_between_first | from, to | Str::betweenFirst | "[a][b]"|str_between_first("[", "]") → a |
str_camel | Str::camel | "user name"|str_camel → userName | |
str_snake | delimiter="_" | Str::snake | "UserName"|str_snake(delimiter=".") → user.name |
str_studly | normalize=false | Str::studly | "user name"|str_studly → UserName |
str_kebab | Str::kebab | "UserName"|str_kebab → user-name | |
str_mask | character, index, length=none | Str::mask | "abcdef"|str_mask("*", 1, length=3) → a***ef |
str_pad_left | length, pad=" " | Str::padLeft | "猫"|str_pad_left(3, "-") → --猫 |
str_pad_right | length, pad=" " | Str::padRight | "猫"|str_pad_right(3, "-") → 猫-- |
str_pad_both | length, pad=" " | Str::padBoth | "猫"|str_pad_both(4, "-") → -猫-- |
str_replace | search, replacement, case_sensitive=true | Str::replace | "Été"|str_replace("é", "x", case_sensitive=false) → xtx |
str_squish | Str::squish | " one\t two "|str_squish → one two | |
str_word_wrap | width=75, line_break="\n", cut_long_words=false | Str::wordWrap | "one two"|str_word_wrap(4, " / ") → one / two |
str_apa | Str::apa | "notes from the road"|str_apa → Notes From the Road | |
str_initials | capitalize=false | Str::initials | "ada lovelace"|str_initials(capitalize=true) → AL |
str_match | pattern | Str::match | "ID-42"|str_match("/ID-([0-9]+)/") → 42 |
str_is_match | pattern | Str::isMatch | "ID-42"|str_is_match("/^ID-/") → True |
str_replace_matches | pattern, replacement, limit=-1 | Str::replaceMatches | "blue blue"|str_replace_matches("/blue/", "red", limit=1) → red blue |
str_markdown | html_input="allow", allow_unsafe_links=true, soft_break="\n" | Str::markdown | "**hello**"|str_markdown → <p><strong>hello</strong></p>\n |
str_inline_markdown | html_input="allow", allow_unsafe_links=true, soft_break="\n" | Str::inlineMarkdown | "**hello**<br>"|str_inline_markdown(html_input="strip") → <strong>hello</strong>\n |
number_spell | locale=none, after=none, until=none | Number::spell | 100000|number_spell(locale="en_IN") → one lakh |
number_spell_ordinal | locale=none | Number::spellOrdinal | 123|number_spell_ordinal → one hundred twenty-third |
carbon_iso_format | format, locale="en" | $date->isoFormat($format) | zoned|carbon_iso_format("LLLL", locale="fr") → mardi 14 juillet 2026 09:00 |
carbon_translated_format | format, locale="en" | $date->translatedFormat($format) | zoned|carbon_translated_format("l j F", locale="fr") → mardi 14 juillet |
carbon_calendar | reference, locale="en" | $date->calendar($reference) | zoned|carbon_calendar(other, locale="fr") → Aujourd’hui à 09:00 |
interval_for_humans | short=false, parts=-1, join=false, locale="en", cascade=false | $interval->forHumans($options) | 5400|interval_for_humans(join=true, cascade=true) → 1 hour and 30 minutes |
carbon_diff_for_humans_in | other, locale="en" | $date->diffForHumans($other) | zoned|carbon_diff_for_humans_in(other, locale="fr") → 2 heures avant |
php_trim, php_ltrim, php_rtrim | characters=none (PHP byte mask) | PHP trim functions | "abc!cab" | php_trim("a..c") → ! |
arr_join | glue, final_glue="" | Arr::join() | ["a", "b"] | arr_join(", ", " and ") → a and b |
php_implode | separator="" | implode() | [12, false, "x"] | php_implode("/") → 12//x |
php_explode | separator, limit=9223372036854775807 | explode() | "a,b,c" | php_explode(",", limit=2) → ["a", "b,c"] |
php_array_filter, php_array_values | PHP array filtering and reindexing | ["0", "00"] | php_array_filter | php_array_values → ["00"] | |
str_append and str_prepend | Variadic parts | Stringable::append() / prepend() | "end" | str_prepend("first ") → first end |
carbon_parse | tz=none | Carbon::parse() | "2024-02-29" | carbon_parse | carbon_date_string → 2024-02-29 |
carbon_modify | modifier, tz=none | $date->modify($modifier) | "2024-01-31" | carbon_modify("+1 month") | carbon_date_string → 2024-03-02 |
php_strtotime | base_timestamp=none, tz=none | strtotime($text, $baseTimestamp) | "+1 week" | php_strtotime(0) → 604800 |
carbon_create_from_format | format, tz=none | Carbon::createFromFormat() | "2024-02" | carbon_create_from_format("!Y-m") | carbon_date_string → 2024-02-01 |
carbon_date_time_string | precision="second", tz=none | Carbon::toDateTimeString() | zoned | carbon_date_time_string("minute") → 2026-07-14 09:00 |
js_from | flags=0, depth=512 | Js::from() | [1, 2] | js_from → JSON.parse('[1,2]') |
php_json_encode | flags=0, depth=512, named flag overrides | json_encode() | "é" | php_json_encode(unescaped_unicode=true) → "é" |
blade_json | flags=15, depth=512 | Blade @json | "</script>" | blade_json → "\u003C\/script\u003E" |
php_e | double_encode=true | Laravel e() | "&<" | php_e(double_encode=false) → &< |
php_sprintf, php_vsprintf | Positional values, or one sequence/map for php_vsprintf | PHP printf formatting | "%04d" | php_sprintf(7) → 0007 |
php_str_starts_with | needle | str_starts_with() | "hello" | php_str_starts_with("") → True |
str_contains | needles, ignore_case=false | Str::contains() | "CAFÉ" | str_contains(["", "Fé"], ignore_case=true) → True |
str_starts_with, str_ends_with | needles | Str::startsWith(), Str::endsWith() | "été" | str_ends_with("") → False |
str_substr | start, length=none | Str::substr() | "a猫b" | str_substr(-2, -1) → 猫 |
str_length | Str::length() | "a猫b" | str_length → 3 | |
str_match_all | pattern | Str::matchAll() | "3 12" | str_match_all("/([0-9]+)/") → ["3", "12"] |
str_split | pattern, limit=-1, flags=0 | preg_split() | "a,b" | str_split("/,/") → ["a", "b"] |
str_scan | format | Stringable::scan() | "42 apples" | str_scan("%d %s") → [42, "apples"] |
str_to_boolean | — | Stringable::toBoolean() | " YES " | str_to_boolean → true |
now(), time() | Current ISO timestamp or Unix seconds from the app clock | now() | carbon_format("Y", tz="Asia/Tokyo") | |
php_date | format, tz=none as a function, or pass the format as filter input | PHP date() with the app clock | php_date("Y") or "Y" | php_date |
str_replace and str_replace_matches accept a string or sequence for search and
replacement. Searches run in order, and missing parallel replacements mean the empty string.
The regular expression limit applies to each pattern.
When both precisions are supplied, max_precision wins and removes trailing zeros.
For str_slug, explicitly passing language=none disables transliteration.
php_round returns a float. Use php_echo to print it with PHP’s number-to-string rules.
§Relative dates
Pass other for “before” and “after” wording. Omitting it uses laravel::now() for
“ago” and “from now”, including the test clock set by travel or freeze_time.
A standalone environment needs an explicit other.
| Keyword | Default | Effect |
|---|---|---|
syntax | "auto" | Override the wording with "absolute", "relative_to_now", or "relative_to_other". |
short, parts | false, 1 | Use abbreviated units or show more than one unit. |
join, last_glue | false, none | join=true uses the selected locale’s conjunctions. Pass a string for custom glue and optionally a second string in last_glue for the final pair. |
locale | "en" | Carbon translations for the full options builder. |
minimum_unit, skip | none, [] | Limit the smallest displayed unit or skip a list of units. |
a_unit | false | Use an article such as “an hour” for a single unit. |
options | 0 | Carbon’s flags as a bit mask. The boolean flags below add to it. |
just_now, no_zero_diff | false | Use “just now” when equal to the clock or replace a zero difference with one unit. |
one_day_words, two_day_words | false | Enable weekday-relative wording such as “yesterday” and “after tomorrow”. |
sequential_parts_only | false | Stop at the first missing unit. |
round, ceil, floor | false | Round excess parts, in that order of precedence. |
§Values, errors and escaping
Null and undefined input generally render as an empty string. The JSON and JavaScript encoders render them
as null. Number filters accept MiniJinja integers and floats, PHP numeric strings, and booleans
coerced to 1 or 0. Integers outside PHP’s signed 64-bit range are treated as floats.
Every Carbon filter accepts an IANA timezone override as tz=. The date filters accept
integer or fractional Unix seconds, ISO dates and the framework’s serialized Jiff dates and date-times.
An explicit zone converts timestamps and zoned inputs to that zone and interprets civil dates
and times there. By default, timestamps use FORMATTING_TIMEZONE, explicit offsets and named
zones are preserved, and civil inputs use UTC. The constructor filters interpret civil
inputs in the configured time zone and use the Laravel clock for clock words and omitted
fields. carbon_iso_string renders in UTC by default, accepts keep_offset=true,
and returns an empty string for Carbon’s null conversion (local year zero).
now(), time() and php_date require an application context and follow test travel and
freeze. Register the adapter after the optional minijinja-contrib helpers to use its now().
Malformed values produce template errors named for their filter. Most outputs follow
MiniJinja autoescaping. php_e returns the exact Laravel-escaped HTML as a safe value.
blade_json uses Blade’s HEX flags by default. Keep those flags for raw JSON in script
expressions or single-quoted data attributes. js_from uses Laravel’s required flags
for JavaScript expressions in script elements. Use autoescaped php_json_encode in
HTML attributes. All three take flags and depth (default 512). Named JSON options
such as pretty_print and numeric_check override the corresponding mask bits.
Re-exports§
pub use laravel_rust_format_core as core;
Modules§
- arr
- Laravel array and collection joining, using PHP string conversion.
- carbon
- Carbon’s parsing and formatting on Jiff types (
Zoned,Timestamp,civil::Date):format()with PHPdate()letters,toIso8601String(),toISOString(),toDateString(), anddiffForHumans()with optional localization. - js
- Laravel’s
Illuminate\Support\Jsexpression encoder. - number
- English
Illuminate\Support\Number. - php
- PHP core formatting at PHP 8.4 and 8.5 defaults.
- prelude
- Everything a template or view model needs, in one import:
- str
Illuminate\Support\Str: the functions whose output Laravel apps print.
Structs§
- Error
- An error from a formatting function.
- Formatting
Config - Defaults used by the Laravel
Number::currency()and Carbon template filters. - Formatting
Service Provider - Registers the formatting configuration and, with the default
minijinjafeature, the template equivalents of PHP’s formatting functions and Laravel’s Str, Number and Carbon helpers.
Enums§
Functions§
- register_
filters - Adds PHP, Laravel Str and Number, and Carbon filters and globals to an existing MiniJinja environment.
Type Aliases§
- Result
- The result type of fallible functions in this crate.