Skip to main content

Crate laravel_rust_format

Crate laravel_rust_format 

Source
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-format

Register 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 variableDefaultEffect
FORMATTING_CURRENCYUSDDefault currency for number_currency. The provider validates it against the ISO 4217 current currency and funds list at boot.
FORMATTING_TIMEZONEUTCDisplay timezone for Unix seconds, serialized timestamps ending in Z and php_date. The provider validates the zone at boot.
FORMATTING_MAX_OUTPUT_BYTES8388608Maximum raw bytes per call, before MiniJinja autoescaping.
FORMATTING_MAX_COLLECTION_ITEMS100000Maximum 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 functionArgumentsPHP or Laravel equivalentExample → output
number_formatdecimals=0, dec_point=".", thousands_sep=","number_format()1234.5 | number_format(2) → 1,234.50
php_roundprecision=0, mode=round() with a PHP mode name or integer3.5 | php_round | php_echo → 4
php_echoecho $number1.0e20 | php_echo → 1.0E+20
ucfirstucfirst()"apple" | ucfirst → Apple
php_lcfirstlcfirst()"Apple" | php_lcfirst → apple
php_ucwordsseparators=noneucwords()"red-apple" | php_ucwords("-") → Red-Apple
php_strtolowerstrtolower()"ÉTÉ" | php_strtolower → ÉtÉ
php_strtoupperstrtoupper()"été" | php_strtoupper → éTé
str_limitlimit=100, end="...", preserve_words=falseStr::limit()"hello" | str_limit(3) → hel...
str_wordswords=100, end="..."Str::words()"one two three" | str_words(2) → one two...
str_slugseparator="-", language="en"Str::slug()"Café Noir" | str_slug → cafe-noir
str_asciilanguage="en"Str::ascii()"café" | str_ascii → cafe
str_titleStr::title()"red apple" | str_title → Red Apple
str_headlineStr::headline()"first_name" | str_headline → First Name
str_ucfirstStr::ucfirst()"été" | str_ucfirst → Été
str_lcfirstStr::lcfirst()"Été" | str_lcfirst → été
str_upperStr::upper()"été" | str_upper → ÉTÉ
str_lowerStr::lower()"ÉTÉ" | str_lower → été
str_pluralcount=2, prepend_count=falseStr::plural()"city" | str_plural(3, true) → 3 cities
str_singularStr::singular()"cities" | str_singular → city
plural(word, count)Both requiredStr::plural() without prepending the countplural("city", 3) → cities
number_format_intlprecision=none, max_precision=none, locale=noneNumber::format()2.5 | number_format_intl(0) → 2
number_file_sizeprecision=0, max_precision=none, locale=noneNumber::fileSize()1536 | number_file_size(1) → 1.5 KB
number_percentageprecision=0, max_precision=none, locale=noneNumber::percentage()2.5 | number_percentage(1) → 2.5%
number_currencycode=config.currency, precision=none, locale=noneNumber::currency()42 | number_currency("EUR") → €42.00
number_abbreviateprecision=0, max_precision=none, locale=noneNumber::abbreviate()1500 | number_abbreviate(1) → 1.5K
number_for_humansprecision=0, max_precision=none, abbreviate=false, locale=noneNumber::forHumans()1500 | number_for_humans(1) → 1.5 thousand
number_ordinallocale=noneNumber::ordinal()21 | number_ordinal → 21st
carbon_formatformat (required, PHP date letters)Carbon::format()"2026-12-03" | carbon_format("D, M j") → Thu, Dec 3
carbon_iso8601Carbon::toIso8601String()"2026-12-03" | carbon_iso8601 → 2026-12-03T00:00:00+00:00
carbon_iso_stringCarbon::toISOString()"2026-12-03" | carbon_iso_string → 2026-12-03T00:00:00.000000Z
carbon_date_stringCarbon::toDateString()"2026-12-03T16:30:00+01:00" | carbon_date_string → 2026-12-03
diff_for_humansother=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_nl2bris_xhtml=truenl2br"<b>line</b>\nnext"|php_nl2br(is_xhtml=false) → &lt;b&gt;line&lt;&#x2f;b&gt;&lt;br&gt;\nnext
php_str_padlength, pad=" ", side=1str_pad"x"|php_str_pad(4, "-", side=2) → -x--
php_wordwrapwidth=75, line_break="\n", cut_long_words=falsewordwrap"one two"|php_wordwrap(4, " / ") → one &#x2f; two
php_strip_tagsallowed_tags=nonestrip_tags"<b>bold</b><i>italic</i>"|php_strip_tags(["b"]) → &lt;b&gt;bold&lt;&#x2f;b&gt;italic
str_aftersearchStr::after"id:42"|str_after(":") → 42
str_after_lastsearchStr::afterLast"a:b:c"|str_after_last(":") → c
str_beforesearchStr::before"id:42"|str_before(":") → id
str_before_lastsearchStr::beforeLast"a:b:c"|str_before_last(":") → a:b
str_betweenfrom, toStr::between"[a][b]"|str_between("[", "]") → a][b
str_between_firstfrom, toStr::betweenFirst"[a][b]"|str_between_first("[", "]") → a
str_camelStr::camel"user name"|str_camel → userName
str_snakedelimiter="_"Str::snake"UserName"|str_snake(delimiter=".") → user.name
str_studlynormalize=falseStr::studly"user name"|str_studly → UserName
str_kebabStr::kebab"UserName"|str_kebab → user-name
str_maskcharacter, index, length=noneStr::mask"abcdef"|str_mask("*", 1, length=3) → a***ef
str_pad_leftlength, pad=" "Str::padLeft"猫"|str_pad_left(3, "-") → --猫
str_pad_rightlength, pad=" "Str::padRight"猫"|str_pad_right(3, "-") → 猫--
str_pad_bothlength, pad=" "Str::padBoth"猫"|str_pad_both(4, "-") → -猫--
str_replacesearch, replacement, case_sensitive=trueStr::replace"Été"|str_replace("é", "x", case_sensitive=false) → xtx
str_squishStr::squish" one\t two "|str_squish → one two
str_word_wrapwidth=75, line_break="\n", cut_long_words=falseStr::wordWrap"one two"|str_word_wrap(4, " / ") → one &#x2f; two
str_apaStr::apa"notes from the road"|str_apa → Notes From the Road
str_initialscapitalize=falseStr::initials"ada lovelace"|str_initials(capitalize=true) → AL
str_matchpatternStr::match"ID-42"|str_match("/ID-([0-9]+)/") → 42
str_is_matchpatternStr::isMatch"ID-42"|str_is_match("/^ID-/") → True
str_replace_matchespattern, replacement, limit=-1Str::replaceMatches"blue blue"|str_replace_matches("/blue/", "red", limit=1) → red blue
str_markdownhtml_input="allow", allow_unsafe_links=true, soft_break="\n"Str::markdown"**hello**"|str_markdown → &lt;p&gt;&lt;strong&gt;hello&lt;&#x2f;strong&gt;&lt;&#x2f;p&gt;\n
str_inline_markdownhtml_input="allow", allow_unsafe_links=true, soft_break="\n"Str::inlineMarkdown"**hello**<br>"|str_inline_markdown(html_input="strip") → &lt;strong&gt;hello&lt;&#x2f;strong&gt;\n
number_spelllocale=none, after=none, until=noneNumber::spell100000|number_spell(locale="en_IN") → one lakh
number_spell_ordinallocale=noneNumber::spellOrdinal123|number_spell_ordinal → one hundred twenty-third
carbon_iso_formatformat, locale="en"$date->isoFormat($format)zoned|carbon_iso_format("LLLL", locale="fr") → mardi 14 juillet 2026 09:00
carbon_translated_formatformat, locale="en"$date->translatedFormat($format)zoned|carbon_translated_format("l j F", locale="fr") → mardi 14 juillet
carbon_calendarreference, locale="en"$date->calendar($reference)zoned|carbon_calendar(other, locale="fr") → Aujourd’hui à 09:00
interval_for_humansshort=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_inother, locale="en"$date->diffForHumans($other)zoned|carbon_diff_for_humans_in(other, locale="fr") → 2 heures avant
php_trim, php_ltrim, php_rtrimcharacters=none (PHP byte mask)PHP trim functions"abc!cab" | php_trim("a..c") → !
arr_joinglue, final_glue=""Arr::join()["a", "b"] | arr_join(", ", " and ") → a and b
php_implodeseparator=""implode()[12, false, "x"] | php_implode("/") → 12//x
php_explodeseparator, limit=9223372036854775807explode()"a,b,c" | php_explode(",", limit=2) → ["a", "b,c"]
php_array_filter, php_array_valuesPHP array filtering and reindexing["0", "00"] | php_array_filter | php_array_values → ["00"]
str_append and str_prependVariadic partsStringable::append() / prepend()"end" | str_prepend("first ") → first end
carbon_parsetz=noneCarbon::parse()"2024-02-29" | carbon_parse | carbon_date_string → 2024-02-29
carbon_modifymodifier, tz=none$date->modify($modifier)"2024-01-31" | carbon_modify("+1 month") | carbon_date_string → 2024-03-02
php_strtotimebase_timestamp=none, tz=nonestrtotime($text, $baseTimestamp)"+1 week" | php_strtotime(0) → 604800
carbon_create_from_formatformat, tz=noneCarbon::createFromFormat()"2024-02" | carbon_create_from_format("!Y-m") | carbon_date_string → 2024-02-01
carbon_date_time_stringprecision="second", tz=noneCarbon::toDateTimeString()zoned | carbon_date_time_string("minute") → 2026-07-14 09:00
js_fromflags=0, depth=512Js::from()[1, 2] | js_from → JSON.parse('[1,2]')
php_json_encodeflags=0, depth=512, named flag overridesjson_encode()"é" | php_json_encode(unescaped_unicode=true) → "é"
blade_jsonflags=15, depth=512Blade @json"</script>" | blade_json → "\u003C\/script\u003E"
php_edouble_encode=trueLaravel e()"&amp;<" | php_e(double_encode=false) → &amp;&lt;
php_sprintf, php_vsprintfPositional values, or one sequence/map for php_vsprintfPHP printf formatting"%04d" | php_sprintf(7) → 0007
php_str_starts_withneedlestr_starts_with()"hello" | php_str_starts_with("") → True
str_containsneedles, ignore_case=falseStr::contains()"CAFÉ" | str_contains(["", "Fé"], ignore_case=true) → True
str_starts_with, str_ends_withneedlesStr::startsWith(), Str::endsWith()"été" | str_ends_with("") → False
str_substrstart, length=noneStr::substr()"a猫b" | str_substr(-2, -1) → 猫
str_lengthStr::length()"a猫b" | str_length → 3
str_match_allpatternStr::matchAll()"3 12" | str_match_all("/([0-9]+)/") → ["3", "12"]
str_splitpattern, limit=-1, flags=0preg_split()"a,b" | str_split("/,/") → ["a", "b"]
str_scanformatStringable::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 clocknow() | carbon_format("Y", tz="Asia/Tokyo")
php_dateformat, tz=none as a function, or pass the format as filter inputPHP date() with the app clockphp_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.

KeywordDefaultEffect
syntax"auto"Override the wording with "absolute", "relative_to_now", or "relative_to_other".
short, partsfalse, 1Use abbreviated units or show more than one unit.
join, last_gluefalse, nonejoin=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, skipnone, []Limit the smallest displayed unit or skip a list of units.
a_unitfalseUse an article such as “an hour” for a single unit.
options0Carbon’s flags as a bit mask. The boolean flags below add to it.
just_now, no_zero_difffalseUse “just now” when equal to the clock or replace a zero difference with one unit.
one_day_words, two_day_wordsfalseEnable weekday-relative wording such as “yesterday” and “after tomorrow”.
sequential_parts_onlyfalseStop at the first missing unit.
round, ceil, floorfalseRound 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 PHP date() letters, toIso8601String(), toISOString(), toDateString(), and diffForHumans() with optional localization.
js
Laravel’s Illuminate\Support\Js expression 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.
FormattingConfig
Defaults used by the Laravel Number::currency() and Carbon template filters.
FormattingServiceProvider
Registers the formatting configuration and, with the default minijinja feature, the template equivalents of PHP’s formatting functions and Laravel’s Str, Number and Carbon helpers.

Enums§

ErrorKind
The kind of Error.
PhpNumber
A PHP number: an int or a float.

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.