Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MahmoudAdelAli's avatar

Use new attribute cast

Hi , i want to use new attribute way stand for laravel 10 , to create a slug from name so i write this code inside Course Model

 protected function name(): Attribute
    {
        return new Attribute(
            set: fn($value) => [
                'name' => $value,
                'slug' => Str::slug($value)]
        );
    }

It works , but i have some questions is the function name affect on ? and is this way is write way and best practice ? and what if i need to add new cast , should i create new function or just append it on

0 likes
5 replies
tykus's avatar

Personally, I would use a Model Event to generate a slug rather than a mutator.

what if i need to add new cast , should i create new function or just append it on

That depends; is the "new cast" depending on the name attribute?

1 like
MahmoudAdelAli's avatar

@tykus as you see you personally prefer to use model event , can i ask why ? just to understand and learn, benefit from your experience.

tykus's avatar

@MahmoudAdelAli in my opinion it is cleaner this way. You can choose whether the slug should be set whenever the model is creating or updating (you might not want the slug to change after creation). Although ultimately both approaches will work, in my opinion, having this side-effect in a name mutator is a somewhat opaque.

1 like

Please or to participate in this conversation.