# Data for Laravel Rust
`laravel-data` is a port of [spatie/laravel-data](https://github.com/spatie/laravel-data) to [Laravel Rust](https://crates.io/crates/laravel-rust). Data objects describe your data once and serve as API resources: lazy properties that are only included when asked for, partial includes from the query string, additional properties, wrapping and collections.
> [!NOTE]
> This is a community port maintained by [Rivervo](https://github.com/rivervo). It is not an official Spatie package. It follows spatie/laravel-data **4.23.1**: the same `include`, `exclude`, `only` and `except` partials and their syntax (`songs.{name, artist}`, `songs.*`), `Lazy` (`create`, `when`, `defaultIncluded`), `Optional`, `with` and `additional`, wrapping, request partials and response statuses, with Rust naming. In Rust, serde and Laravel Rust's validation already do what PHP's casts, mappers and validation attributes do, so this port focuses on data objects as resources. All credit for the design goes to [Spatie](https://spatie.be) and the package's contributors.
- [Installation](#installation)
- [Creating data objects](#creating-data-objects)
- [Lazy properties](#lazy-properties)
- [Only and except](#only-and-except)
- [Optional properties](#optional-properties)
- [Mapping property names](#mapping-property-names)
- [Appending properties](#appending-properties)
- [Responses and wrapping](#responses-and-wrapping)
- [Collections](#collections)
- [Testing](#testing)
- [Differences from PHP](#differences-from-php)
- [Not yet ported (planned for a later release)](#not-yet-ported-planned-for-a-later-release)
- [License](#license)
## Installation
```shell
cargo add laravel-data
```
Register the service provider in `src/app.rs` to configure the global wrap key:
```rust
Application::configure()
.with_providers(|providers| {
providers.add(laravel_data::DataServiceProvider);
})
```
## Creating data objects
```rust
use laravel_data::Data;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct SongData {
pub title: String,
pub artist: String,
}
impl Data for SongData {}
let song = SongData::from_value(json!({ "title": "Never Gonna Give You Up", "artist": "Rick Astley" }))?;
let song = SongData::from_source(&song_model)?; // from anything serializable, such as a model
let songs = SongData::collect(&song_models)?;
song.to_array();
song.to_json();
```
For request input, use Laravel Rust's `Valid<T>` with validation rules on the struct.
## Lazy properties
```rust
#[derive(Serialize)]
pub struct AlbumData {
pub title: String,
pub songs: Lazy<Vec<SongData>>,
}
impl Data for AlbumData {}
let album = AlbumData {
title: album.title.clone(),
songs: Lazy::create(move || songs.clone()),
};
album.to_array(); // {"title": "..."}: the closure doesn't run
album.include(["songs"]).to_array(); // with the songs
album.include(["songs.{title, artist}"]); // nested lazy properties
album.include(["songs.*"]); // every lazy property of the songs
```
- `Lazy::when(|| user.is_admin, || ...)` is only included when the condition holds, and can't be included otherwise.
- `Lazy::create(|| ...).default_included()` is included unless excluded with `exclude(["songs"])`.
- A data object can always include or exclude properties by overriding `include_properties` and `exclude_properties`.
## Only and except
`only` and `except` work on every property, lazy or not:
```rust
song.only(["title"]);
album.include(["songs.*"]).except(["songs.artist"]);
```
## Optional properties
`Optional<T>` is left out of the output when it's missing. Give the field `#[serde(default)]` so missing input deserializes as `Optional::Missing`:
```rust
#[derive(Serialize, Deserialize)]
pub struct UserData {
pub name: String,
#[serde(default)]
pub nickname: Optional<String>,
}
```
## Mapping property names
Use serde's attributes, PHP's `MapName`, `MapInputName` and `MapOutputName`:
```rust
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserData {
pub first_name: String,
}
```
## Appending properties
```rust
impl Data for UserData {
fn with(&self) -> Map<String, Value> {
let mut with = Map::new();
with.insert("endpoint".to_owned(), json!(format!("/users/{}", self.id)));
with
}
}
user.additional(json!({ "role": "admin" }));
```
## Responses and wrapping
`to_response(&request)` sends the data as JSON with `201` for a `POST` and `200` otherwise, as PHP does, and applies the `?include=`, `?exclude=`, `?only=` and `?except=` partials the data object allows:
```rust
impl Data for AlbumData {
fn allowed_request_includes() -> Option<Vec<&'static str>> {
Some(vec!["songs"]) // None allows every include; the default allows none
}
}
pub async fn show(request: Request) -> laravel::http::Response {
album.to_response(&request)
}
```
A transformation (what `include`, `only`, `additional` and the others return) is a response too. Responses are wrapped in the `DataConfig::wrap` key (`None` by default), a data object's `default_wrap`, or `.wrap("data")`; `.without_wrapping()` turns it off.
## Collections
A `Vec` of data objects is a collection, with the same partials for every item:
```rust
use laravel_data::DataCollection;
albums.include(["songs.title"]).to_value();
albums.to_response(&request);
```
## Testing
```shell
cargo test --all-features
```
## Differences from PHP
- `include`, `exclude`, `only`, `except`, `additional` and `wrap` return a `Transformation` instead of changing the object.
- Creating data objects uses serde (`from_value`, `from_source`, `collect`); validation is Laravel Rust's `Valid<T>`.
- A request partial must be listed in `allowed_request_*` exactly as requested (or `*`). PHP also checks a nested partial against the nested data class's own allowed list.
- Outside `to_array`, `to_value` and responses (plain `serde_json::to_string`), a lazy property that isn't included by default serializes as `null`.
## Not yet ported (planned for a later release)
- Paginated collections with `links` and `meta`, and `CursorPaginatedDataCollection`.
- `Lazy::whenLoaded` (relations), `Lazy::inertia` and `Lazy::closure`, and auto lazy.
- Computed properties, casts, transformers, rule inferring, validation attributes and `validateAndCreate`, magic `from*` methods, injected property values, data factories, TypeScript generation and the `make:data` command.
## License
MIT. See [LICENSE.md](LICENSE.md).