2

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!

Brain Music
  • 73
  • 1
  • 8
  • Sounds like you need a joint key of `song_id` and `playlist_id` to prevent duplicates on this table (which I assume is a pivot for a many-to-many between `songs` and `playlists`) – Tim Lewis May 29 '17 at 17:17

1 Answers1

5

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
}
Sandeesh
  • 11,486
  • 3
  • 31
  • 42