fredmarks
1 month ago

better way to validate an optional, nullable field

Posted 1 month ago by fredmarks

I have an optional form field, which, when it is filled, I want to check against the users table (if it exists)

This is working, but its verbose

            'account_manager' => [
                'nullable',
                function ($attribute, $value, $fail) {
                    if ($value != '') {
                        if (\App\Models\User::Where('id', $value)->doesntExist()) {
                            return $fail('User not found');
                        }
                    }
                },
            ],

This is cleaner but its checking the exist rule, even when no value has been passed

            'account_manager' => [
                'nullable',
                Rule::exists('users', 'id'),
            ],

is there a way to make the above, slimmer code work?

Please sign in or create an account to participate in this conversation.