有没有办法使用 Laravel 的验证语法来验证外键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29611807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:20:50  来源:igfitidea点击:

Is there any way to validate a foreign key using Laravel's Validation syntax?

phpvalidationlaravel

提问by ReactingToAngularVues

Say I have an objectwhich relates to a mission. Users can upload objects and say that it has a relationship with one of these missions. Is there anyway to check that the mission_idthat the user has selected for this object actually exists in this database using Laravel's Validationclass and rules?

假设我有一个object与 a 相关的mission. 用户可以上传对象并说它与这些任务之一有关。无论如何要mission_id使用 Laravel 的Validation类和规则来检查用户为此对象选择的对象是否确实存在于该数据库中?

This way, I can check that mission_idis not only an integer, but also exists in the database.

这样,我可以检查它mission_id不仅是一个整数,而且还存在于数据库中。

For example, I guess I'm looking for something like:

例如,我想我正在寻找类似的东西:

$rules = array(
    'mission_id' => 'foreignKeyExistsInMissions|integer'
)

Where foreignKeyExistsInMissionsis the validation rule I'm looking for.

foreignKeyExistsInMissions我正在寻找的验证规则在哪里。

回答by Jeff Lambert

This should work:

这应该有效:

'mission_id' => 'required|exists:missions,id',

And the message:

和消息:

'mission_id.exists' => 'Not an existing ID',

Source(v4.2 docs)

(v4.2 文档)

Source(v5.5 docs)

(v5.5 文档)