# Laravel Rust Hijri documentation (v1.x)

> Canonical: https://pharaonic.dev/packages/laravel-rust/hijri/1.x  
> Version: v1.x (latest release 1.0.0, 2026-12-02)  
> Install: cargo add pharaonic-laravel-hijri  
> Requires: Rust 1.99+, Laravel Rust 0.1 – 1.x  
> Repository: https://github.com/Pharaonic/laravel-rust-hijri  
> All versions: https://pharaonic.dev/packages/laravel-rust/hijri/1.x.md

:::badges
- Laravel Rust Package {color=blue}
- v1.0.0 {color=green}
- MIT License {color=purple}
- AI Ready {color=violet}
:::

# Laravel Rust Hijri

Hijri (Islamic) dates for [Laravel Rust](https://laravel.com/rust) applications. Register one service provider, set the day adjustment, format, language and time zone with `HIJRI_*` environment variables, and print Hijri dates in your MiniJinja views with the `hijri` filter. Forms validate Hijri dates with `HijriDateRule`, models store Hijri dates with the `AsHijri` column, and handlers convert dates with the same settings. The calendar comes from the [Pharaonic Hijri](https://pharaonic.dev/packages/rust/hijri) crate, and the package is the Laravel Rust counterpart of [Laravel Hijri](https://pharaonic.dev/packages/laravel/hijri).

:::success AI Ready
Hijri ships an agent guideline for your `AGENTS.md` and a `hijri-development` skill for `.agents/skills/`, so Claude Code, Cursor, Codex or Amp write correct Hijri filters, rules, model columns and conversions. See [AI Ready](#ai-ready).
:::

:::features
### Template Filter
`{{ post.created_at|hijri }}` prints a Hijri date in any MiniJinja view.

### Validation Rule
Accept only `YYYY-MM-DD` Hijri dates that exist in the calendar.

### Environment Configuration
Adjustment, format, language and time zone, each with a default.

### Arabic and English Months
Month names in Arabic or English, per application or per date.

### AI Ready
An agent guideline and a `hijri-development` skill, bundled in the crate.

### Model Columns
`AsHijri` stores the Gregorian date and reads it back as Hijri.
:::

:::info Quick Tip
Laravel Rust works in UTC. If your users live in Riyadh or Cairo, set `HIJRI_TIMEZONE`, so a post created at 23:30 UTC shows the Hijri date of their day, not of the day in London.
:::

## Installation

Add the package with Cargo, then register its service provider.

### Requirements

- Rust 1.99 or newer (the package's `rust-version`, the same as the framework's)
- [Laravel Rust](https://laravel.com/rust) 0.1.4 or later, below 2.0
- MiniJinja views, only for the `hijri` template filter

### Cargo Installation

Applications that render MiniJinja views enable the `minijinja` feature, which adds the template filter:

```bash title="Terminal" no-line-numbers
cargo add pharaonic-laravel-hijri --features minijinja
```

Inertia applications that don't render MiniJinja views leave it out:

```bash title="Terminal" no-line-numbers
cargo add pharaonic-laravel-hijri
```

Add the `database` feature for [model columns](#models):

```bash title="Terminal" no-line-numbers
cargo add pharaonic-laravel-hijri --features minijinja,database
```

Or add the dependency to `Cargo.toml` yourself:

```toml title="Cargo.toml"
[dependencies]
pharaonic-laravel-hijri = { version = "1", features = ["minijinja", "database"] }
```

### Register the Service Provider

Laravel Rust doesn't discover packages automatically. Add the provider in `src/app.rs`:

```rust title="src/app.rs"
use laravel::Application;
use pharaonic_laravel_hijri::HijriServiceProvider;

pub fn configure() -> laravel::foundation::ApplicationBuilder {
    Application::configure()
        .with_providers(|providers| {
            providers.add(HijriServiceProvider);
        })
}
```

:::success Installation Complete
You're all set! The defaults work without any configuration: English month names, the `-1` day adjustment, and UTC. See [Configuration](#configuration) to change them.
:::

## Configuration

The package reads four environment variables into its `HijriConfig` section. Each has a default, so you only set the ones you want to change.

| Variable | Field | Default | Description |
| --- | --- | --- | --- |
| `HIJRI_ADJUSTMENT` | `adjustment` | `-1` | Days added to every conversion from a Gregorian date, to follow local moon sighting |
| `HIJRI_FORMAT` | `format` | `%-d %B %Y` | The default format of the `hijri` filter |
| `HIJRI_LANGUAGE` | `language` | `en` | Month names: `ar` or `en` (also `arabic` or `english`, in any case) |
| `HIJRI_TIMEZONE` | `timezone` | `UTC` | The time zone a timestamp is read in before it becomes a date |

For an Arabic site in Saudi Arabia, your `.env` might read:

```dotenv title=".env"
HIJRI_ADJUSTMENT=0
HIJRI_LANGUAGE=ar
HIJRI_TIMEZONE=Asia/Riyadh
```

### The Day Adjustment

The calendar is tabular: it computes months instead of following moon sighting, so it can be a day or two off your local calendar. `HIJRI_ADJUSTMENT` shifts every conversion from a Gregorian date by whole days. The default `-1` matches the Laravel (PHP) package and Pharaonic Hijri; `0` uses the tabular calendar as it is.

### Formats

`HIJRI_FORMAT` uses the `strftime` directives of Pharaonic Hijri:

| Directive | Output |
| --- | --- |
| `%Y` | year, at least four digits: `1445` |
| `%y` | last two digits of the year: `45` |
| `%m` / `%-m` | month: `09` / `9` |
| `%d` / `%-d` / `%e` | day: `05` / `5` / ` 5` |
| `%j` | day of the year, three digits: `247` |
| `%B` | month name in the language: `Ramadan` |
| `%%` | a literal `%` |

Weekday directives such as `%A` aren't supported, because the weekday belongs to the Gregorian date.

### Changing Settings in Code

Package settings load before your application's, so you may change any field in `src/app.rs`:

```rust title="src/app.rs"
use laravel::Application;
use pharaonic_laravel_hijri::{HijriConfig, HijriServiceProvider, Language};

pub fn configure() -> laravel::foundation::ApplicationBuilder {
    Application::configure()
        .with_providers(|providers| {
            providers.add(HijriServiceProvider);
        })
        .with_config(|config, _| {
            config.section_mut::<HijriConfig>().language = Language::Arabic;
        })
}
```

:::warning Checked at Startup
An unknown `HIJRI_LANGUAGE` stops the application when it's created. An unsupported directive in `HIJRI_FORMAT` or an unknown `HIJRI_TIMEZONE` stops it at boot, with a message that names the variable, before it serves a request.
:::

## Basic Usage

With the provider registered and the `minijinja` feature on, print a Hijri date in any view with the `hijri` filter:

```html title="resources/views/posts/show.html"
<time datetime="{{ post.created_at }}">{{ post.created_at|hijri }}</time>
```

A post created on 11 March 2024 shows `1 Ramadan 1445`, or `1 رَمضان 1445` with `HIJRI_LANGUAGE=ar`.

Validate a Hijri date in a form with `HijriDateRule`:

```rust title="src/http/requests.rs"
use pharaonic_laravel_hijri::HijriDateRule;

#[laravel::input]
#[validate(anyone)]
pub struct StoreEvent {
    #[validate(required, HijriDateRule)]
    pub starts_on: String,
}
```

And convert dates in a handler with the configured adjustment:

```rust title="src/http/controllers/events.rs"
use laravel::config::Section;
use laravel::time::civil::date;
use pharaonic_laravel_hijri::HijriConfig;

pub async fn ramadan(hijri: Section<HijriConfig>) -> laravel::Result<String> {
    let date = hijri.converter().to_hijri(date(2024, 3, 11))?;

    assert_eq!(date.to_string(), "1445-09-01");

    Ok(date.strftime(&hijri.format, hijri.language)?)
}
```

The next sections cover each part in detail.

## Template Filter

The `minijinja` feature registers a `hijri` filter for your MiniJinja views. It takes a Gregorian date and prints its Hijri date with your configuration.

```html title="resources/views/posts/show.html"
{{ post.created_at|hijri }}
```

### What It Accepts

The filter reads the text that Laravel Rust's date and time types serialize to:

| Value | Example | Date used |
| --- | --- | --- |
| A date (`civil::Date`) | `2024-03-11` | that date |
| A date and time (`civil::DateTime`) | `2024-03-11T09:30:00` | its date |
| A timestamp (`Timestamp`) | `2024-03-10T23:30:00Z` | its date in `HIJRI_TIMEZONE` |
| A zoned date-time (`ZonedDateTime`) | `2024-03-10T20:00:00-05:00[America/Chicago]` | its date in its own time zone |
| `none` or an undefined variable | | prints nothing |

Anything else, such as `11/03/2024` or a number, is a template error, so a mistake shows up in development instead of printing a wrong date. A Hijri date string such as `1445-09-01` is read as a Gregorian date, so pass Gregorian values to the filter.

### Options

Pass a format as the first argument, and `language` or `adjustment` by name. Each one overrides the configuration for that date only:

```html title="resources/views/events/show.html"
{{ event.starts_at|hijri("%Y/%m/%d") }}             {# 1445/09/01 #}
{{ event.starts_at|hijri(language="ar") }}          {# 1 رَمضان 1445 #}
{{ event.starts_at|hijri("%-d %B", adjustment=0) }} {# 2 Ramadan #}
```

`language` takes the same values as `HIJRI_LANGUAGE`. An unknown option name is a template error.

### Machine-Readable Dates

Wrap the Hijri date in a `<time>` element so browsers, search engines and screen readers get the Gregorian date too:

```html title="resources/views/posts/show.html"
<time datetime="{{ post.published_on }}">{{ post.published_on|hijri }}</time>
```

:::info Without the Feature
Without `minijinja`, the provider registers no filter, and a view that uses `|hijri` fails to render. Enable the feature in `Cargo.toml` if your application renders MiniJinja views.
:::

## Validation

`HijriDateRule` accepts a Hijri date in the `YYYY-MM-DD` format that exists in the calendar, such as `1445-09-01` or `1445-9-1`. Put it on a `String` field of a validated struct:

```rust title="src/http/requests.rs"
use pharaonic_laravel_hijri::HijriDateRule;

#[laravel::input]
#[validate(anyone)]
pub struct StoreEvent {
    #[validate(required, HijriDateRule)]
    pub starts_on: String,
    #[validate(HijriDateRule)]
    pub ends_on: Option<String>,
}
```

It rejects `1445-02-30` (Safar 1445 has 29 days), `1445-13-01` and `01/09/1445`. Like most rules, it skips a missing or blank field, so add `required` when the date must be there.

### Reading the Date

The handler receives the validated text. Parse it into a `HijriDate`; the rule already checked it, so parsing succeeds:

```rust title="src/http/controllers/events.rs"
use laravel::prelude::*;
use pharaonic_laravel_hijri::{HijriDate, HijriDateRule};

#[laravel::input]
#[validate(anyone)]
pub struct StoreEvent {
    #[validate(required, HijriDateRule)]
    pub starts_on: String,
}

pub async fn store(Valid(event): Valid<StoreEvent>) -> laravel::Result<String> {
    let starts_on: HijriDate = event.starts_on.parse()?;
    let gregorian = starts_on.to_gregorian()?;

    Ok(format!("The event starts on {gregorian}"))
}
```

### The Message

A failed check reads "The starts on field must be a valid Hijri date." Replace it for one field with `.message(...)`, which may use the `:attribute` placeholder:

```rust title="src/http/requests.rs"
use pharaonic_laravel_hijri::HijriDateRule;

#[laravel::input]
#[validate(anyone)]
pub struct StoreEvent {
    #[validate(required, HijriDateRule.message("Enter the :attribute as YYYY-MM-DD, such as 1445-09-01."))]
    pub starts_on: String,
}
```

:::info Arabic Messages
Laravel Rust has no translation files yet, so the built-in message is English. Use `.message(...)` to show it in Arabic.
:::

## Models

With the `database` feature, `AsHijri` is a model column that holds a Hijri date, the counterpart of Laravel Hijri's `AsHijri` cast. The database keeps the Gregorian date in a `date` column, so other applications and reports still read a normal date, and your model reads it back as a Hijri date.

```toml title="Cargo.toml"
[dependencies]
pharaonic-laravel-hijri = { version = "1", features = ["database"] }
```

### Declaring the Column

Create a `date` column in the migration:

```rust title="database/migrations/2026_12_02_000000_create_events_table.rs"
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("events", |table| {
            table.id();
            table.string("name");
            table.date("starts_on");
            table.date("ends_on").nullable();
        })
        .await
}
```

Then declare the field as `AsHijri`, or `Option<AsHijri>` for a nullable column:

```rust title="src/models/event.rs"
use laravel::model::model;
use pharaonic_laravel_hijri::AsHijri;

#[model]
pub struct Event {
    pub id: i64,
    pub name: String,
    pub starts_on: AsHijri,
    pub ends_on: Option<AsHijri>,
}
```

### Creating Rows

Build the value from a Hijri date with `AsHijri::new`, or from a Gregorian date with `AsHijri::from_gregorian`. Both take a converter; pass the configured one so the stored date follows `HIJRI_ADJUSTMENT`:

```rust title="src/http/controllers/events.rs"
use laravel::config::Section;
use laravel::model::{create, model};
use pharaonic_laravel_hijri::{AsHijri, HijriConfig, HijriDate};

#[model]
pub struct Event {
    pub id: i64,
    pub name: String,
    pub starts_on: AsHijri,
    pub ends_on: Option<AsHijri>,
}

pub async fn store(hijri: Section<HijriConfig>) -> laravel::Result<String> {
    let starts_on = AsHijri::new(HijriDate::new(1445, 9, 1)?, hijri.converter())?;

    let event = create!(Event {
        name: "Ramadan".to_owned(),
        starts_on,
        ends_on: None,
    })
    .await?;

    Ok(format!("Stored {}", event.starts_on.gregorian())) // "Stored 2024-03-11"
}
```

### Reading Rows

Reading a row converts the stored Gregorian date with the configured `HIJRI_ADJUSTMENT`. `hijri()` returns the `HijriDate` and `gregorian()` the stored date:

```rust title="src/http/controllers/events.rs"
use laravel::model::model;
use pharaonic_laravel_hijri::{AsHijri, Language};

#[model]
pub struct Event {
    pub id: i64,
    pub name: String,
    pub starts_on: AsHijri,
    pub ends_on: Option<AsHijri>,
}

pub async fn show(id: i64) -> laravel::Result<String> {
    let event = Event::find_or_fail(id).await?;

    assert_eq!(event.starts_on.to_string(), "1445-09-01");

    Ok(event.starts_on.hijri().strftime("%-d %B %Y", Language::English)?) // "1 Ramadan 1445"
}
```

Changing `HIJRI_ADJUSTMENT` later changes how stored rows read, never the stored dates, as with the Laravel (PHP) package.

### Filtering

Compare the column with an `AsHijri` value; the query compares the Gregorian dates:

```rust title="src/http/controllers/events.rs"
use laravel::model::model;
use pharaonic_laravel_hijri::{AsHijri, Converter, HijriDate};

#[model]
pub struct Event {
    pub id: i64,
    pub name: String,
    pub starts_on: AsHijri,
    pub ends_on: Option<AsHijri>,
}

pub async fn first_of_ramadan() -> laravel::Result<Vec<Event>> {
    let day = AsHijri::new(HijriDate::new(1445, 9, 1)?, Converter::default())?;

    Ok(Event::query().filter(Event::starts_on.eq(day)).get().await?)
}
```

### JSON and Inertia

In JSON and Inertia responses, the column is its Hijri date as `YYYY-MM-DD`, such as `"starts_on": "1445-09-01"`, the same as the `AsHijri` cast. A `None` column is `null`.

:::info Forms
Validated input fields can't be `AsHijri`. Validate the field as a `String` with [`HijriDateRule`](#validation), parse it into a `HijriDate`, then build the column with `AsHijri::new`.
:::

:::warning Inside the Application
Reading an `AsHijri` column needs the application's configuration, which every query inside a handler, job or command has. Reading one elsewhere, such as in a task started with `tokio::spawn`, returns an error. Use `laravel::task::spawn` instead.
:::

## Dates in Your Code

The package re-exports the Pharaonic Hijri types, `HijriDate`, `Converter`, `Language` and `Error`, so you don't need a second dependency to work with Hijri dates in handlers, jobs and commands.

### Reading the Configuration

Take the configuration as a `Section<HijriConfig>` argument in a handler, or read it with `laravel::config().section::<HijriConfig>()` anywhere else, such as in a job or a command. `converter()` returns a `Converter` with the configured adjustment:

```rust title="src/support/calendar.rs"
use laravel::time::civil::Date;
use pharaonic_laravel_hijri::{Error, HijriConfig};

pub fn hijri_label(date: Date) -> Result<String, Error> {
    let config = laravel::config();
    let hijri = config.section::<HijriConfig>();
    let hijri_date = hijri.converter().to_hijri(date)?;

    hijri_date.strftime(&hijri.format, hijri.language)
}
```

`HijriDate::from_gregorian()` always uses the default adjustment of `-1`. Use the configured converter when `HIJRI_ADJUSTMENT` matters.

### Timestamps

A `Timestamp`, such as a model's `created_at`, is an instant without a date. Read it in your time zone first, then convert the date:

```rust title="src/http/controllers/posts.rs"
use laravel::time::Timestamp;
use laravel::time::tz::TimeZone;
use pharaonic_laravel_hijri::{HijriConfig, HijriDate};

pub fn published_on(config: &HijriConfig, created_at: Timestamp) -> laravel::Result<HijriDate> {
    let time_zone = TimeZone::get(&config.timezone)?;
    let date = created_at.to_zoned_datetime(time_zone).date();

    Ok(config.converter().to_hijri(date)?)
}
```

### Errors

The Pharaonic Hijri `Error` converts into `laravel::Error`, so `?` works in handlers. Its variants are `InvalidDate`, `OutOfRange`, `Parse`, `UnknownDirective` and `UnknownLanguage`; see the [Pharaonic Hijri docs](https://pharaonic.dev/packages/rust/hijri) for when each happens, and for Hijri date math and formatting.

## Cargo Features

| Feature | Default | Enables |
| --- | --- | --- |
| `database` | off | The [`AsHijri`](#models) model column, and the framework's `database` feature |
| `minijinja` | off | The `hijri` template filter, and the framework's `minijinja` feature |

Without features, the package still registers its configuration, checks it at startup, and provides `HijriDateRule` and the re-exported types. Turn on the features your application uses:

```toml title="Cargo.toml"
[dependencies]
pharaonic-laravel-hijri = { version = "1", features = ["database", "minijinja"] }
```

The package itself depends on Laravel Rust with its default features off, so it never adds Inertia or MiniJinja to your application unless you ask for them. `database` doesn't pick a database either: your application's `database-postgres`, `database-mysql` or `database-sqlite` feature does.

## AI Ready

Hijri is AI ready. The crate ships an agent guideline and an [Agent Skill](https://agentskills.io) in the same format as the `AGENTS.md` and `.agents/skills/` of every new Laravel Rust application, so the coding agent working on your application (Claude Code, Cursor, Codex, Amp, Copilot…) knows how to use the package.

### Install

Laravel Rust doesn't discover package resources, so copy them once from the installed crate. Run this from your application's root (it needs `jq`):

```bash title="Terminal" no-line-numbers
hijri="$(cargo metadata --format-version 1 --locked | jq -r '.packages[] | select(.name == "pharaonic-laravel-hijri") | .manifest_path | rtrimstr("/Cargo.toml")')/resources/agents"
mkdir -p .agents/skills
cp -R "$hijri/skills/hijri-development" .agents/skills/
cat "$hijri/guidelines.md" >> AGENTS.md
```

The skill lands next to the framework's skills in `.agents/skills/hijri-development/`, and the guideline becomes a `## Hijri dates` section at the end of `AGENTS.md`, which the application's `CLAUDE.md` already imports. Commit both, so every agent session and every teammate gets them.

### What the Agent Learns

| Resource | Loaded | Covers |
| --- | --- | --- |
| Guideline (`resources/agents/guidelines.md`) | In every session, as part of `AGENTS.md` | The provider, the `HIJRI_*` settings, `config.converter()`, the `hijri` filter, `HijriDateRule` and `AsHijri`, with one example |
| Skill `hijri-development` | When the agent shows, validates, stores or converts Hijri dates | Setup and features, every setting, converting dates, the filter options, the rule, model columns, pitfalls and testing |

### After an Update

When you update the crate, run the `cp -R` line again to refresh the skill. Compare the `## Hijri dates` section of your `AGENTS.md` with the new `guidelines.md` and replace it if it changed, instead of appending it twice.

:::tip Edit Your Copy
The copies belong to your application. Add your own conventions to them, such as which models use `AsHijri` or the format your designers chose, the way the framework suggests for its own skills.
:::

## API Reference

Everything below is exported from the crate root, `pharaonic_laravel_hijri`. The full reference is on [docs.rs](https://docs.rs/pharaonic-laravel-hijri).

### HijriServiceProvider

| Item | Description |
| --- | --- |
| `HijriServiceProvider` | Unit struct implementing `laravel::foundation::ServiceProvider`. Register it with `providers.add(HijriServiceProvider)` |
| `config()` | Loads `HijriConfig` from the environment |
| `register()` | With `minijinja`, registers the `hijri` filter |
| `boot()` | Fails startup when `HIJRI_FORMAT` or `HIJRI_TIMEZONE` is invalid |

### HijriConfig

A `#[non_exhaustive]` configuration section (`Debug`, `Clone`, `Default`). Read it with `Section<HijriConfig>` or `config().section::<HijriConfig>()`, and change it with `section_mut::<HijriConfig>()`.

| Field / Method | Type | Description |
| --- | --- | --- |
| `adjustment` | `i32` | `HIJRI_ADJUSTMENT`, default `-1` |
| `format` | `String` | `HIJRI_FORMAT`, default `%-d %B %Y` |
| `language` | `Language` | `HIJRI_LANGUAGE`, default `Language::English` |
| `timezone` | `String` | `HIJRI_TIMEZONE`, default `UTC` |
| `converter(&self)` | `Converter` | A converter with the configured adjustment |

### HijriDateRule

| Item | Description |
| --- | --- |
| `HijriDateRule` | Unit struct implementing `laravel::validation::ValidationRule`. Accepts `YYYY-MM-DD` Hijri dates that exist; message "The :attribute field must be a valid Hijri date." |

### hijri Filter

| Usage | Description |
| --- | --- |
| `value\|hijri` | Formats with `HIJRI_FORMAT`, `HIJRI_LANGUAGE` and `HIJRI_ADJUSTMENT` |
| `value\|hijri("%Y/%m/%d")` | Another format |
| `value\|hijri(language="ar")` | Another language: `ar`, `en`, `arabic`, `english` |
| `value\|hijri(adjustment=0)` | Another adjustment |

### AsHijri

With the `database` feature. A `Copy` value (`Debug`, `Clone`, `PartialEq`, `Eq`, `Hash`, `Display`, `Serialize`) for a `date` column.

| Method | Description | Returns |
| --- | --- | --- |
| `AsHijri::new(hijri, converter)` | From a Hijri date; finds the Gregorian date with the converter | `Result<AsHijri, Error>` |
| `AsHijri::from_gregorian(date, converter)` | From a Gregorian date (`impl Into<civil::Date>`) | `Result<AsHijri, Error>` |
| `hijri(self)` | The Hijri date | `HijriDate` |
| `gregorian(self)` | The stored Gregorian date | `civil::Date` |
| `to_string()` | The Hijri date as `YYYY-MM-DD` | `String` |

`AsHijri` converts into `HijriDate` and `civil::Date` with `From`. Rows decode with the configured `HIJRI_ADJUSTMENT`, and JSON serializes the Hijri `YYYY-MM-DD`.

### Re-exports from Pharaonic Hijri

| Type | Description |
| --- | --- |
| `HijriDate` | A Hijri date: conversion, date math, `strftime`, parsing |
| `Converter` | Converts between calendars with an adjustment |
| `Language` | `Arabic` or `English`; parses from `ar`/`en` |
| `Error` | `InvalidDate`, `OutOfRange`, `Parse`, `UnknownDirective`, `UnknownLanguage` |

Their methods are documented in the [Pharaonic Hijri API reference](https://pharaonic.dev/packages/rust/hijri).

## Coming from Laravel Hijri

The package follows the Laravel (PHP) package where the framework allows it. The differences:

| Laravel Hijri (PHP) | Laravel Rust Hijri |
| --- | --- |
| `HIJRI_ADJUSTMENT`, default `-1` | The same variable and default |
| `config('pharaonic.hijri.format')` with ISO tokens, `D MMMM YYYY` | `HIJRI_FORMAT` with `strftime` directives, `%-d %B %Y` |
| The application locale picks the language | `HIJRI_LANGUAGE`, because Laravel Rust has no application locale |
| `@hijri($post->created_at)` Blade directive | `{{ post.created_at\|hijri }}` MiniJinja filter |
| `<x-hijri-date :date="$date" />` component | `<time datetime="{{ date }}">{{ date\|hijri }}</time>` |
| `new HijriDateRule` | `#[validate(HijriDateRule)]` |
| English and Arabic validation messages | An English message, replaceable with `.message(...)` |
| A global adjustment set at boot | No global state: `HijriConfig::converter()` carries the adjustment |
| `'starts_on' => AsHijri::class` cast | `starts_on: AsHijri` model field, with the `database` feature |
| Carbon mixin | The methods of `HijriDate` |

A `YYYY-MM-DD` date gives the same Hijri date in both packages with the same adjustment.

## Examples

### 1. Hijri Dates on Blog Posts

Show when each post was published, in the reader's calendar:

- ===Handler

  ```rust title="src/http/controllers/posts.rs"
  use laravel::prelude::*;
  use laravel::time::Timestamp;
  use serde::Serialize;

  #[derive(Serialize)]
  pub struct Post {
      pub title: String,
      pub created_at: Timestamp,
  }

  pub async fn index() -> laravel::Result<Response> {
      let posts = vec![Post {
          title: "Ramadan Kareem".to_owned(),
          created_at: "2024-03-10T23:30:00Z".parse()?,
      }];

      Ok(view("posts.index", data! { posts }).into_response())
  }
  ```

- ===View

  ```html title="resources/views/posts/index.html"
  {% for post in posts %}
      <article>
          <h2>{{ post.title }}</h2>
          <time datetime="{{ post.created_at }}">{{ post.created_at|hijri }}</time>
      </article>
  {% endfor %}
  ```

- ===.env

  ```dotenv title=".env"
  HIJRI_LANGUAGE=ar
  HIJRI_TIMEZONE=Asia/Riyadh
  ```

With these settings, the post shows `1 رَمضان 1445`: 23:30 UTC on 10 March is already 11 March in Riyadh.

### 2. Booking a Date in the Hijri Calendar

Let users book by Hijri date and store the Gregorian date:

```rust title="src/http/controllers/bookings.rs"
use laravel::prelude::*;
use pharaonic_laravel_hijri::{HijriDate, HijriDateRule};

#[laravel::input]
#[validate(anyone)]
pub struct StoreBooking {
    #[validate(required, HijriDateRule)]
    pub day: String,
}

pub async fn store(Valid(booking): Valid<StoreBooking>) -> laravel::Result<String> {
    let day: HijriDate = booking.day.parse()?;
    let gregorian = day.to_gregorian()?;

    Ok(format!("Booked for {gregorian}"))
}
```

### 3. Both Calendars Side by Side

Show the Hijri date in Arabic next to the Gregorian date:

```html title="resources/views/events/show.html"
<p>
    {{ event.starts_on }}
    ({{ event.starts_on|hijri("%-d %B %Y هـ", language="ar") }})
</p>
```

For `2024-04-10`, this prints `2024-04-10 (1 شوّال 1445 هـ)`.

### 4. A Ramadan Countdown

Count the days to the next Ramadan in a handler, with the configured adjustment:

```rust title="src/http/controllers/ramadan.rs"
use laravel::config::Section;
use pharaonic_laravel_hijri::{HijriConfig, HijriDate};

pub async fn countdown(hijri: Section<HijriConfig>) -> laravel::Result<String> {
    let converter = hijri.converter();
    let today = converter.to_hijri(laravel::time::today())?;

    let year = if today.month() < 9 { today.year() } else { today.year() + 1 };
    let ramadan = HijriDate::new(year, 9, 1)?;

    Ok(format!("{} days until Ramadan {year}", today.days_until(ramadan)))
}
```

## Troubleshooting

### A view fails because the hijri filter is unknown

The filter is behind the `minijinja` feature. Enable it in `Cargo.toml` (`features = ["minijinja"]`) and make sure `HijriServiceProvider` is registered in `src/app.rs`.

### The application doesn't start: "HIJRI_FORMAT ... is invalid"

The format has a directive Pharaonic Hijri doesn't support, often a weekday (`%A`, `%a`) or a time (`%H`). See [Formats](#configuration) for the supported directives, and format the weekday from the Gregorian date instead.

### The application doesn't start: "HIJRI_TIMEZONE ... is invalid"

Use an IANA time zone name, such as `Asia/Riyadh`, `Africa/Cairo` or `UTC`. Abbreviations such as `AST` aren't time zone names.

### The application doesn't start because of HIJRI_LANGUAGE

`HIJRI_LANGUAGE` accepts `ar`, `en`, `arabic` or `english`, in any case. Locale tags such as `ar-SA` aren't accepted.

### Dates are one day off

Either the adjustment doesn't match your local calendar, or a timestamp is read in UTC. Set `HIJRI_ADJUSTMENT` (`0` for the tabular calendar, `-1` by default) and `HIJRI_TIMEZONE` to your users' time zone.

### "hijri expects a date, a date-time or a timestamp"

The filter received text that isn't one of the shapes in [Template Filter](#template-filter), such as `11/03/2024`, or an empty string. Pass the model's date or timestamp field itself, or use `none` for a missing date.

### A number fails with "must be a string"

Validated fields check their type before their rules. Declare the Hijri date field as `String`, and send it as text.

### "AsHijri needs pharaonic_laravel_hijri::HijriServiceProvider to be registered"

Reading an `AsHijri` column uses the package's configuration. Register `HijriServiceProvider` in `src/app.rs`.

### "AsHijri can only be read inside the application"

The query ran outside the application, such as in a task started with `tokio::spawn`. Start the task with `laravel::task::spawn`, which keeps the application's context.

### The database build fails with "non-exhaustive patterns" errors

Laravel Rust's `database` feature needs a database backend. Enable `database-postgres`, `database-mysql` or `database-sqlite` on `laravel-rust` in your application's `Cargo.toml`.

## Upgrade Guide

### 1.x

1.0.0 is the first release of the package. There are no upgrade steps yet.

Coming from the Laravel (PHP) package? See [Coming from Laravel Hijri](#coming-from-laravel) for the mapping and the differences.
