In this article, we are going to generate a slug from a title in filament admin panel. If you are working on filament, in some cases you must need a slug generation process from title. So, lets discuss this in this article.
Create a title and slug field.
Lets first add title and slug field in our forms() method.
TextInput::make('title')
->translateLabel(),
TextInput::make('slug')
->maxLength(255)
->rules(['alpha_dash'])
->unique(ignoreRecord: true)
So, here we have added two fields title and slug. And in the slug field i have added alpha_dash and unique validation.
Learning Filament, check out the official docs. Also check out the tips and tricks for filament.
Modify Title field.
Now, we will modify the title field, whenever user will type in the title field, lets update our slug. So, for that we will chain afterStateUpdated() method.
TextInput::make('title')
->afterStateUpdated(function (Set $set, $state) {
$set('slug', Str::slug($state));
})
->translateLabel()
So, now you can see after the title state is updated, we are generating the slug from Str::slug(“string”) method and inserting that on that slug.
If you test this, then you will obviously feel slow , so to control that we will chain onLive(blur:true) method on title field so that it will update the slug when user focus out from the title field.
TextInput::make('title')
->live(onBlur: true)
->afterStateUpdated(function (Set $set, $state) {
$set('slug', Str::slug($state));
})
->translateLabel()
Conclusion:
So, in this way we can generate slug from a title in filament. If you have any confusion , you can comment down below.