Tricks

Automatically set the slug for new records only

Jul 20, 2022
Elliot
Admin panel, Form builder

For models with slugs, often you don't want the slug to (automatically) change after the model has been created, to ensure that URLs don't become broken.

To do that, I use the following:

TextInput::make('title')
->required()
->reactive()
->afterStateUpdated(function (Closure $set, $state, $context) {
if ($context === 'edit') {
return;
}
 
$set('slug', Str::slug($state));
}),
 
TextInput::make('slug')
->required()
->maxLength(255)
->rules(['alpha_dash'])
->unique(ignoreRecord: true),

With thanks to Dan Harrin for the steer.

No comments yet…