outl1ne / nova-translatable

A Laravel Nova package that allows you to make any input field translatable.
MIT License
199 stars 58 forks source link

rulesFor is not working #104

Closed marcelosantos89 closed 1 year ago

marcelosantos89 commented 1 year ago

Hey, i'm trying to validate some fields using rulesFor() but nothing is taking effect.

           Text::make('Slug')
                ->hideFromIndex()
                ->translatable()
                ->rules(['max:255']) // Works
                ->rulesFor('en', [  // **Does not work**
                    'required'
                ])
                ->rulesFor(['pt', 'es', 'en'], function ($locale) { // **Does not work**
                    return ["unique:opportunities,slug->$locale{{resourceId}}"];
                }),

I tried to figure out the problem but I can't really get what's wrong. I'm using:

marcelosantos89 commented 1 year ago

I have added this code while this rules are not working

    /**
    * Handle any post-validation processing.
    *
    * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
    * @param  \Illuminate\Validation\Validator  $validator
    * @return void
    */
    protected static function afterValidation(NovaRequest $request, $validator)
    {
        // Check if the slug is unique
        $slug = $request->input('slug'); // Change 'slug' to the actual field name
        $resourceId = $request->resourceId; // Get the resource ID if editing, otherwise null

        foreach($slug as $key => $value) {
            $slugField = "slug->".$key;

            $query = \App\Models\Opportunity::query();
            $query = $query->where($slugField, $value);

            if(!is_null($resourceId)) {
                $query = $query->where('id', '<>', $resourceId);
            }

            if($query->count() > 0) {
                $validator->errors()->add('slug.'.$key, 'Slug is already behing used!');
            }
        }
    }
BobbyBorisov commented 1 year ago

@marcelosantos89 I think you are missing the trait HandlesTranslatable. Link to the documentation

marcelosantos89 commented 1 year ago

@BobbyBorisov you are right I totally forgot that, Thank you.