I'd love to see another exists validation rule that works for polymorphic objects. For example if a form is getting messageable_id and messageable_type, it would be great to ensure the object that is being referred to actually exists.
You can set extra where conditions on the exists rule. See documentation.
In the documentation, it shows that you can add a where clause to the exists rule. I'm not really sure how that helps in this case since it looks like you still need to specify a single table to look in as the first argument to the exists rule.
It's like the $table-> morphs () creates index keys instead of unique keys. Why doesn't it care for?
Any solution please?
You can dynamically define a 'model_exists' rule in your request class. Something like this:
public function rules()
{
$messageableIdRule = 'required_with:messageable_type';
if ($this->has('messageable_type')) {
$messageableIdRule .= '|model_exists:' . $this->messageable_type . ',id';
}
return [
'messageable_type' => 'required_with:messageable_id',
'messageable_id' => $messageableIdRule,
];
}