OctoberCMS用户关联字段必填验证失效问题求助
Ah, I see the issue here—you're validating the relation name instead of the actual foreign key field that gets populated when you select a user in the backend. Let me break down how to fix this quickly:
Step 1: Update Your Validation Rules
Change your $rules array to target the foreign key user_id instead of the relation name. This is the field that actually gets set when you pick a user via the backend relation picker:
/** * @var array Validation rules */ public $rules = [ 'user_id' => 'required' ];
Step 2: (Optional) Add Extra Rigor with an Existence Check
If you want to make sure the selected user ID actually corresponds to a valid user in the database, extend the rule with exists:
public $rules = [ 'user_id' => 'required|exists:users,id' ];
(Note: users is the default table name for Rainlab User's User model—adjust this if you’ve customized the table name in your setup.)
Why This Works
When you use the backend relation picker configured in your config_relation.yaml, it renders a field that submits the selected user’s ID to the user_id column in your model’s table. Your original rule targeted the user relation object, which hasn’t been loaded yet during the initial form submission—so the validation always failed, even when a user was selected.
By validating user_id directly, you’re checking the actual value that gets stored, which aligns perfectly with how the form data is processed.
内容的提问来源于stack exchange,提问作者Ronaldo Ribeiro de Sousa

