Getting started

laravel-rust-phone Alpha Laravel for Rust

Add the crate to your Laravel for Rust project.

[dependencies]
laravel-rust-phone = "0.1"

To use model columns, add features = ["database-sqlite"] to the dependency. Use database-postgres or database-mysql for the corresponding Laravel driver.

Parse and format a number

use laravel_rust_phone::phone;

let number = phone("0470 12 34 56").with_countries(["BE"]);

assert!(number.is_valid());
assert_eq!(number.country().as_deref(), Some("BE"));
assert_eq!(number.format_e164()?, "+32470123456");
assert_eq!(number.raw_number(), "0470 12 34 56");

phone() remembers the submitted text. A recognized international prefix takes precedence over the hints. For a national number, the parser tries countries in order. It ignores duplicates and unknown country codes. Strict mode chooses the first region for which the number is valid. With .lenient(true), it chooses the first region for which the number has a possible length.

Formatting and validation serve different purposes. For example, +32470123 is parseable and can format as E.164, but fails strict validation. Call is_valid() before accepting a number from a user.

Use format_e164() for canonical storage and format_rfc3966() for a tel: URI. Use format_international() or format_national() for display. format_for_country(origin) uses the caller's dialing plan. format_for_mobile_dialing_in_country(origin, formatted) returns an empty string when the number cannot be dialed on mobile from that origin.

Validate a request

use laravel::validation::Validate;
use laravel_rust_phone::PhoneRule;
use serde::Deserialize;

#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct StoreContact {
    #[validate(required, PhoneRule::new())]
    phone: String,
    phone_country: String,
}

The rule looks for phone_country before using its configured countries. For an alternate field, use country_field("billing.country"). That explicit root path replaces the implicit field lookup, even when the alternate field is absent.

  • The country field contributes the first hint. A null value, empty string, or "0" supplies no hint. Arrays and objects cause a validation failure.
  • countries(["BE", "NL"]) adds parsing hints and restricts the allowed regions. default_countries(["BE"]) applies when the rule has no explicit countries.
  • international() lifts the region restriction for correctly formatted international numbers. Configured hints still parse national numbers.
  • lenient() accepts possible lengths without checking the full carrier pattern.
  • mobile() and fixed_line() both match numbers with an ambiguous fixed-line-or-mobile type. Use allow_types() or block_types() for a list. A rule with both lists populated returns a configuration error.

For a runtime rules collection, call PhoneRule::new().into_rule(). Build a base rule with your application defaults and clone it for each field. To localize the error, pass your application's validation.phone template to message(). Laravel expands placeholders such as :attribute.

parameters(["BE", "mobile"]) accepts trusted PHP-style configuration tokens. Fields named by those tokens are looked up in the submitted request. Type and mode keywords take precedence over field names, and a field name takes precedence over a country code.

For a collection of contacts, apply the rule to each member with a nested Validate type or Rules::each::<ContactInput>("members"). When migrating PHP wildcard configuration, the parameter builder can resolve matching paths and can reuse numeric list indexes across different paths. Use a typed nested rule for associative keys when the parameter path has a different structure.

Store the submitted number

use laravel::model::model;
use laravel_rust_phone::{E164PhoneNumber, RawPhoneNumber};

#[model]
struct Contact {
    id: i64,
    phone: E164PhoneNumber,
    raw_phone: RawPhoneNumber,
    phone_country: Option<String>,
}

Construct the model after request validation.

let contact = Contact::create()
    .phone(E164PhoneNumber::from_input(
        Some(&input.phone),
        [&input.phone_country],
    )?)
    .raw_phone(RawPhoneNumber::new(Some(input.phone)))
    .phone_country(Some(input.phone_country))
    .await?;

For the Belgian input above, serialization emits "+32470123456" for phone and "0470 12 34 56" for raw_phone. Choose E.164 for standardized lookup or raw text for the submitted spelling. If you store raw national input, store and select its country alongside it.

E.164 storage

Use from_input(value, hints) with text or from_number(number) with a PhoneNumber. Values are formatted before binding. Resolve a national number with explicit hints.

Reading a stored value requires a resolvable international region. Legacy +32 470 12 34 56 keeps its exact spelling in number().raw_number() and exports +32470123456 through text(). A stored local value or one with an unknown region returns CastError::InvalidStoredNumber. Validate before writes if a value must also pass the strict numbering checks.

Raw storage

Use number(hints) when the application needs a parsed value. National text without a usable hint returns CastError::MissingCountry. Use CastCountries to resolve named model attributes and literal region codes, with the <attribute>_country field last. Raw serialization preserves text without resolving it.

SQL NULL, an empty string, and "0" read as missing. E.164 writes use SQL NULL for all three. Raw writes preserve explicit strings, and None binds SQL NULL.