Laravel如何检查验证唯一表的两个字段 [英] Laravel how to check validate unique table two field
本文介绍了Laravel如何检查验证唯一表的两个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有tableA,其中有2个字段
I have tableA that there are 2 field
1. song_id
2. playlist_id
我要检查laravel验证唯一功能 示例:我已插入数据
I want to check laravel validate unique func example: I have inserted data
id => 1
song_id => 2
playlist_id => 34
然后我必须再次插入数据,我要检查是否
playlist_id => 34
已插入song_id = 2
显示消息已经插入",但如果playlist_id => 34
插入song_id = 3
允许插入
then I have to insert data again I want to check that if
playlist_id => 34
already inserted song_id = 2
show message "already insert" but if playlist_id => 34
insert song_id = 3
allow insert
感谢您的帮助!
推荐答案
这是需要应用的规则.经过样本数据测试,可以正常工作.
This is the rule that need to apply. Tested with sample data and it works as desired.
use Illuminate\Validation\Rule;
$playlist_id = request('playlist_id');
$rules = [
'song_id' => Rule::unique('tableA')->where(function ($query) use ($playlist_id) {
$query->where('playlist_id', $playlist_id);
})
];
样品条件
DB data
song_id playlist_id
2 34
3 34
Request data
song_id playlist_id validation
2 34 fail
3 34 fail
4 34 success
2 35 success
3 35 success
示例测试代码
$data = [
'song_id' => 2,
'playlist_id' => 34,
];
$playlist_id = $data['playlist_id'];
$validator = \Validator::make($data, [
'song_id' => Rule::unique('tableA')->where(function ($query) use ($playlist_id) {
$query->where('playlist_id', $playlist_id);
})
]);
if ($validator->fails()) {
// handle failed validation
}
这篇关于Laravel如何检查验证唯一表的两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文