Using the HasSlug trait | laravel-sluggable-go | Spatie       

 SPATIE  

  Laravel Sluggable Go 
=======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-sluggable-go](https://spatie.be/docs/laravel-sluggable-go/v1)  Basic-usage  Using the HasSlug trait

 Version   v1      

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

  Using the HasSlug trait    
- [ Introduction ](https://spatie.be/docs/laravel-sluggable-go/v1/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-sluggable-go/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-sluggable-go/v1/installation-setup)
- [ Translatable slugs ](https://spatie.be/docs/laravel-sluggable-go/v1/translatable-slugs)
- [ Laravel Boost skill ](https://spatie.be/docs/laravel-sluggable-go/v1/laravel-boost-skill)
- [ Changelog ](https://spatie.be/docs/laravel-sluggable-go/v1/changelog)
- [ Questions and issues ](https://spatie.be/docs/laravel-sluggable-go/v1/questions-issues)
- [ Support us ](https://spatie.be/docs/laravel-sluggable-go/v1/support-us)
- [ Upgrading ](https://spatie.be/docs/laravel-sluggable-go/v1/upgrading)
- [ Testing ](https://spatie.be/docs/laravel-sluggable-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-sluggable-go/v1/releasing)

Basic usage
-----------

- [ Generating your first slug ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/getting-started)
- [ Using the Sluggable attribute ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/using-the-attribute)
- [ Using the HasSlug trait ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/using-the-has-slug-trait)
- [ Finding models by slug ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/finding-models-by-slug)
- [ Self-healing URLs ](https://spatie.be/docs/laravel-sluggable-go/v1/basic-usage/self-healing-urls)

Advanced usage
--------------

- [ Combining multiple source columns ](https://spatie.be/docs/laravel-sluggable-go/v1/advanced-usage/source-fields)
- [ Tuning the uniqueness suffix ](https://spatie.be/docs/laravel-sluggable-go/v1/advanced-usage/uniqueness)
- [ Overriding the underlying actions ](https://spatie.be/docs/laravel-sluggable-go/v1/advanced-usage/overriding-actions)

 Using the HasSlug trait
=======================

###  On this page 

1. [ A closure as the source field ](#content-a-closure-as-the-source-field)
2. [ Skip slug generation conditionally ](#content-skip-slug-generation-conditionally)
3. [ Scope uniqueness to a subset of rows ](#content-scope-uniqueness-to-a-subset-of-rows)
4. [ A custom suffix generator ](#content-a-custom-suffix-generator)
5. [ Find a model by its slug ](#content-find-a-model-by-its-slug)
6. [ Regenerate a slug on demand ](#content-regenerate-a-slug-on-demand)
7. [ Translatable slugs ](#content-translatable-slugs)
8. [ Self-healing URLs ](#content-self-healing-urls)
9. [ Pending updates ](#content-pending-updates)

Go models use explicit methods instead of PHP traits. Implement `SlugOptions() sluggable.Options[Post]`, delegate `Creating` and `Updating` to the package, and return the options your model needs. The [getting started](getting-started) page has a complete model.

Keep your own model, table name, key type, validation and additional fields. A `TableName()` method and `db` tags work through the native model API. Options and callbacks are typed to your model, so replacements participate in persistence, lookups and returned results rather than sitting in an unused configuration field.

A closure as the source field
-----------------------------------------------------------------------------------------------------------------------------------------------

Compute the slug from arbitrary model state, including explicitly loaded related models, with `Source`.

```
options := sluggable.DefaultOptions[Post]("title")
options.Source = func(post *Post, locale string) (string, error) {
    return fmt.Sprintf("%d %s", post.TenantID, post.Title), nil
}
```

Callbacks receive the pending model, including incoming `model.Update` values, and return errors normally. A locale is provided for translated slugs. Relationships are never lazy-loaded. Use a callback for nested source values rather than a dotted PHP attribute path.

Skip slug generation conditionally
--------------------------------------------------------------------------------------------------------------------------------------------------------------

`SkipWhen` runs on every model create or update. Returning `true` leaves the slug column untouched for that write.

```
options.SkipWhen = func(post *Post) bool {
    return post.Title == "Draft"
}
```

Scope uniqueness to a subset of rows
--------------------------------------------------------------------------------------------------------------------------------------------------------------------

`Scope` narrows the uniqueness check, so two records can share a slug as long as they differ on the scope columns.

```
options.Scope = func(query *model.Builder[Post], post *Post) *model.Builder[Post] {
    return query.Where("tenant_id", "=", post.TenantID)
}
```

Uniqueness queries include all rows by default, including soft-deleted records. Lookup queries retain the constraints you supply. Laravel Go does not install PHP global scopes automatically.

A custom suffix generator
-----------------------------------------------------------------------------------------------------------------------------------

Replace the default collision suffix with your own. The callback receives the base slug and the zero-based collision iteration.

```
options.Suffix = func(slug string, iteration int) string {
    return fmt.Sprintf("revision-%d", iteration + 1)
}
```

Choose a generator that can produce free values. Returning the same taken value forever will keep checking until the context is cancelled.

Find a model by its slug
--------------------------------------------------------------------------------------------------------------------------------

Bind operations to a model and call `FindBySlug` with a native query. See [Finding models by slug](finding-models-by-slug).

Regenerate a slug on demand
-----------------------------------------------------------------------------------------------------------------------------------------

The one-call shortcut generates outside the normal save lifecycle. Call `model.Save` afterwards to persist the new value.

```
if err := sluggable.Generate(ctx, &post); err != nil {
    return err
}
return model.Save(ctx, &post)
```

This bypasses lifecycle skip and overwrite controls. Explicitly changed manual slugs remain authoritative and still pass through uniqueness checks. Existing translated custom slugs are preserved, matching PHP's locale-aware behavior.

For several operations, use `slugs, err := sluggable.For(ctx, &post)` and check the error once. You may also pass an explicit `Options[Post]` to `For`, `Generate`, `Creating` or `Updating` instead of implementing `SlugOptions`.

Translatable slugs
--------------------------------------------------------------------------------------------------------------

Generate one slug per locale with JSON columns. See [Translatable slugs](../translatable-slugs).

Self-healing URLs
-----------------------------------------------------------------------------------------------------------

Enable `SelfHealing` in the options and resolve keys explicitly in your route handler. See [Self-healing URLs](self-healing-urls).

Pending updates
-----------------------------------------------------------------------------------------------------

Use typed values in `db.Values`, matching the model fields, including `db.JSON` fields. Nullable pointer fields also accept their underlying value, so a `*string` slug accepts either a string or a pointer. The hook loads the persisted original to distinguish a manual slug from a generated one, then generates against a detached pending model. The slug joins the same transaction as the model write.

Update whole JSON columns rather than `column->locale` paths. SQL expressions cannot be evaluated in memory by slug callbacks. For SQL-expression updates, use a native bulk query that bypasses hooks and regenerate affected models explicitly afterwards.

 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)
