Laravel how to check validate unique table two field

帅比萌擦擦* 提交于 2020-02-02 12:59:47

问题


I have tableA that there are 2 field

1. song_id
2. playlist_id

I want to check laravel validate unique func example: I have inserted data

id =>  1
song_id => 2
playlist_id => 34

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

thank you for your help!


回答1:


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);
    })
];

Sample condition

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

Sample test code

$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
}


来源:https://stackoverflow.com/questions/44247440/laravel-how-to-check-validate-unique-table-two-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!