# Getting started (laravel-rust-phone)

> Add the crate to your Laravel for Rust project.

- Package: laravel-rust-phone (Laravel for Rust, alpha), crates: `laravel-rust-phone`, `laravel-rust-phone-core`
- Maintenance: active; Latest release: 0.1.0 (2026-12-04); Framework: laravel-rust 0.2.x; MSRV: Rust 1.99 or later; Licence: MIT
- Links: [Repository](https://github.com/bowerbird-si/laravel-rust-phone), [crates.io](https://crates.io/crates/laravel-rust-phone/0.1.0), [docs.rs](https://docs.rs/laravel-rust-phone/0.1.0), [Changelog](https://oss.bowerbird.si/phone/docs/changelog/), [Contributing](https://github.com/bowerbird-si/laravel-rust-phone/blob/c3aec2c3f7375e75853ae6a5ef0d1160cd10904d/CONTRIBUTING.md), [Security policy](https://github.com/bowerbird-si/laravel-rust-phone/blob/c3aec2c3f7375e75853ae6a5ef0d1160cd10904d/SECURITY.md)
- Based on: [Laravel-Phone](https://github.com/Propaganistas/Laravel-Phone): The package this ports: parsing, validation rules, formatting and model casts, following version 6.1.0.; [phonenumbers-rs](https://github.com/MasonLyons/phonenumbers-rs): Phone number parsing and formatting in Rust (version 0.1.2).; [Google libphonenumber](https://github.com/google/libphonenumber): The numbering-plan data (version 9.0.44).
- PHP parity: full (36 covered, 15 diverged, 0 planned of 51 abilities; 179 fixtures; follows propaganistas/laravel-phone 6.1.0; verified 2026-12-04)
- Community package, not affiliated with Laravel.
- HTML version: https://oss.bowerbird.si/phone/docs/getting-started/
- Source: https://github.com/bowerbird-si/laravel-rust-phone/blob/c3aec2c3f7375e75853ae6a5ef0d1160cd10904d/docs/getting-started.md

Add the crate to your Laravel for Rust project.

```toml
[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

```rust
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

```rust
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

```rust
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.

```rust
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.
