import csv and generate slug before save the post

I need to generate a slug while the records are imported. I tried to use beforeCreate function but can't find any example about how to use it. I tried:
protected function beforeCreate() : void
{
$this->data['slug'] = Str::slug($this->data['name']);
}
protected function beforeCreate() : void
{
$this->data['slug'] = Str::slug($this->data['name']);
}
but does not seems to work, when import the data I get a sql error because of missing slug.
4 Replies
toeknee
toeknee5mo ago
I would either do it on the fly, so the users can see it. with ->live() in a hidden field. or tbh, I like using model attributes: setSlugAttribute() and if empty slug, str::slug. But the probably is then you don't have a unique rule. so you need to ideally then create a unique validation too.
Nijholt
Nijholt5mo ago
I would suggest you use: mutateFormDataBeforeCreate
spinther
spinther5mo ago
public function fillRecord(): void
{
parent::fillRecord(); // Call the parent method to fill standard fields

// Manually fill additional fields
$additionalFields = [
'slug',
];
foreach ($additionalFields as $field) {
if (array_key_exists($field, $this->data)) {
$this->record->{$field} = $this->data[$field];
}
}
}

protected function beforeFill(): void
{
$this->data['slug'] = Str::slug($this->data['name']);
}
public function fillRecord(): void
{
parent::fillRecord(); // Call the parent method to fill standard fields

// Manually fill additional fields
$additionalFields = [
'slug',
];
foreach ($additionalFields as $field) {
if (array_key_exists($field, $this->data)) {
$this->record->{$field} = $this->data[$field];
}
}
}

protected function beforeFill(): void
{
$this->data['slug'] = Str::slug($this->data['name']);
}
Tim van Heugten
Tim van Heugten5mo ago
When using the import action you can do this in the resolveRecord() function (https://filamentphp.com/docs/3.x/actions/prebuilt-actions/import#updating-existing-records-when-importing). You can access $this->data here, create the slug and then initiate the model with the slug.