问题
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