The Filament documentation offers a nice copy-and-paste solution for generating slugs from a title.
This example sets the title field to be a Livewire Live field, and then, as you enter characters, it generates a slug and sets it to another form field.
use Filament\Forms\Components\TextInput;
use Filament\Forms\Set;
use Illuminate\Support\Str;
TextInput::make('title')
->live()
->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state)))
TextInput::make('slug')
This works great for most situations, but I wanted to take this a step further and only dynamically change the slug if it’s either a new entry or if it’s not been published yet. Otherwise, if a slug gets changed, it’ll cause a 404 since the old one doesn’t exist.
To solve this, here is an updated version that only updates if it’s a new record or hasn’t been published:
TextInput::make('title')
->live()
->afterStateUpdated(function (Get $get, Set $set, ?string $operation, ?string $old, ?string $state, ?Model $record) {
if ($operation == 'edit' && $record->isPublished()) {
return;
}
if (($get('slug') ?? '') !== Str::slug($old)) {
return;
}
$set('slug', Str::slug($state));
})
To explain the code, the afterStateUpdated
in Filament allows you to inject both the operation (create or edit) and the model, which you can then use to determine if the slug should be updated or left alone. That is what the if statement does:
if ($operation == 'edit' && $record->isPublished())
This says that if we are on the edit page and the Model is published, skip dynamically setting the slug.
You might also want to make the slug field disabled if the record is already published, and that can be accomplished easily:
TextInput::make('slug')
->required()
->maxLength(255)
->unique(Article::class, 'slug', fn ($record) => $record)
->disabled(fn (?string $operation, ?Model $record) => $operation == 'edit' && $record->isPublished())
Thanks to Alex Six for helping me set this up and work.
The post Generating slugs from a title in Filament appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.