Custom models | laravel-tags-rust | Spatie       

 SPATIE  

laravel-tags-rust
=================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-tags-rust](https://spatie.be/docs/laravel-tags-rust/v1)  Custom models

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-tags-rust/v1) 

  Custom models    
- [ Introduction ](https://spatie.be/docs/laravel-tags-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-tags-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-tags-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-tags-rust/v1/usage)
- [ Custom models ](https://spatie.be/docs/laravel-tags-rust/v1/custom-models)
- [ Database contracts ](https://spatie.be/docs/laravel-tags-rust/v1/database)
- [ Changelog ](https://spatie.be/docs/laravel-tags-rust/v1/changelog)
- [ Testing ](https://spatie.be/docs/laravel-tags-rust/v1/testing)

 Custom models
=============

###  On this page 

1. [ Select a native tag model ](#content-select-a-native-tag-model)
2. [ Native join rows and creation with tags ](#content-native-join-rows-and-creation-with-tags)

Select a native tag model
-----------------------------------------------------------------------------------------------------------------------------------

- Implement `TagModel` on your own `#[model(hooks)]`.
- Select it through `HasTags::Tag` on each owner and `Tags::for_model::<YourTag>(locale)` for lookups.
- The package uses that model for creation, assignment validation, queries, order and translations. Native model hooks remain active.
- The four typed columns identify the name map, slug map, namespace and order. Additional columns belong to your model.
- Override `create_tag` to set required extra fields.
- Delegate native hooks to the package's slug/order hooks, then add your own behavior as needed.

```
use laravel::db::{Builder, Json};
use laravel::model::{Changes, Column, Draft, Hooks, model};
use serde_json::{Value, json};
use spatie_tags::{HasTags, TagModel, Tags};
use spatie_tags::spatie_translatable::{self, HasTranslations};

#[model(table = "labels", hooks)]
struct Label {
    #[key]
    pub code: i64,
    pub name: Json<Value>,
    pub slug: Json<Value>,
    pub r#type: Option<String>,
    pub order_column: Option<i32>,
    pub description: Json<Value>,
}

impl TagModel for Label {
    const NAME: Column<Self, Json<Value>> = Self::name;
    const SLUG: Column<Self, Json<Value>> = Self::slug;
    const TYPE: Column<Self, Option<String>> = Self::r#type;
    const ORDER: Column<Self, Option<i32>> = Self::order_column;

    fn query() -> Builder<Self> { Self::query() }

    async fn create_tag(names: Value, tag_type: Option<&str>) -> laravel::Result<Self> {
        Self::create().name(Json(names)).slug(Json(json!({})))
            .r#type(tag_type.map(str::to_owned)).order_column(None::<i32>)
            .description(Json(json!({}))).await
    }
}

impl Hooks for Label {
    async fn creating(draft: &mut Draft<Self>) -> laravel::Result<()> {
        spatie_tags::model::creating(draft).await
    }

    async fn updating(&mut self, changes: &Changes<Self>) -> laravel::Result<()> {
        spatie_tags::model::updating(self, changes).await
    }
}

impl HasTranslations for Label {
    const TRANSLATABLE: &'static [&'static str] = &["name", "slug", "description"];

    fn translation_attribute(&self, column: &str) -> Option<&Value> {
        match column {
            "name" => Some(&self.name.0),
            "slug" => Some(&self.slug.0),
            "description" => Some(&self.description.0),
            _ => None,
        }
    }

    fn translation_attribute_mut(&mut self, column: &str) -> spatie_translatable::Result<&mut Value> {
        match column {
            "name" => Ok(&mut self.name.0),
            "slug" => Ok(&mut self.slug.0),
            "description" => Ok(&mut self.description.0),
            _ => Err(spatie_translatable::Error::UnknownColumn(column.into())),
        }
    }
}

#[model]
struct Article {
    pub id: i64,
    pub title: String,
}

impl HasTags for Article { type Tag = Label; }

let tags = Tags::for_model::<Label>("en")?;
assert_eq!(tags.locale(), "en");
```

- Create the `labels` table in an application migration, including `description`, then call `spatie_tags::migrate_assignments::<Label>(tx)`.
- The assignment foreign key references the custom model's table and primary key.
- Configure its pivot layout with the [typed config section](installation-and-setup#configuration).
- Use `#[model(connection = "tags")]` on both the tag and owner to select a named connection. Migrate that connection with your application's migration runner.
- A model loaded with a per-query connection override is not a substitute for a consistently configured relation. Select the connection on the model types.

Native join rows and creation with tags
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

- For extra assignment attributes, declare a native `#[join_row]` and a `MorphToMany<YourTag, YourJoinRow>` relation on the owner.
- Name its morph field in `#[morph_to_many]`.
- Use `related_join_key = "tag_id"` when the custom tag model's inferred foreign key differs.
- Its table and morph-field name must match the typed Tags configuration.
- Set extra fields with native `joined!` values through the relation's `attach` or `sync` methods.
- Read them through native eager loading or the relation's `joined()` query.
- Filter them with the join row's typed column constants.
- Create an owner and its tags in one transaction with native `create!` and nested relation values.
- Continue using `owner.taggable()` for names, namespace-aware sync and query helpers on the same rows.

The package's ID/name assignment helpers insert only identity columns. For required extra pivot values, write through the native relation instead. Existing extra values survive a sync that keeps their assignments. No custom pivot registry or alternate relation implementation is needed.

See the executed scenarios in `tests/custom_models.rs` for a custom translated model, nonstandard key, named connection, native nested creation and a typed join row with a `pinned` field.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
