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

Sky7ure's avatar

Format Nova field input before validation

I have an attribute slug that is both nullable and unique. Validation in Nova doesn't seem to hold place using: ->rules('required_if:is_article,1', 'unique:newsfeeds,slug')

I'm getting a constraint violation (duplicate entry), so the validation isn't working, I guess! Are the rules used correct?

P.S. Since it's a slug, I'm using ->resolveUsing(function ($slug) { return Str::slug($slug); }) too; or should I?

P.P.S. How can I override the Nova field entry (input) exactly?

P.P.P.S. I'm using a mutator to set the attribute to be Str::slug()ed, but it's not helping still...

0 likes
3 replies
aurawindsurfing's avatar

Should you be creating your slug by hand in first place? Let the model handle it for you while you create/update it.

Sky7ure's avatar

I have a description attribute that could be used as a slug and the rest are Translatable stuff. I don't want Admins to have to input that in a slug format, so I AM using a mutator to setDescriptionAttribute() in slug format in the database.

The issue is that validation of the Nova Field beforehand isn't recognizing this mutator to check for a unique rule and stop duplicating records from reaching the database.

Is there any way to format the Nova Text Field input to be used for validation?

Sky7ure's avatar
Sky7ure
OP
Best Answer
Level 8

I had to abandon the Field's validation with ->rules() and use ->fillUsing() method as follows:

->fillUsing(function ($request, $model, $attribute, $requestAttribute) {
    if ($request->exists($requestAttribute)) {
        // apply the slug format
        $value = Str::slug($request[$requestAttribute]);
        $request[$requestAttribute] = $value;

        if ($request->method() === 'POST') {
            // validate a new record (POST)
            $request->validate([
                $requestAttribute => 'required_if:is_article,1|unique:newsfeeds,slug',
            ]);
        } elseif ($request->method() === 'PUT') {
            // validate an updated record (PUT)
            $request->validate([
                $requestAttribute => 'required_if:is_article,1|unique:newsfeeds,slug,'.$model->id,
            ]);
        }

        // upon a validation pass
        $model->{$attribute} = $value;
    }
})
1 like

Please or to participate in this conversation.