"laravel how to check validate unique table two field" Code Answer

1

this is the rule that need to apply. tested with sample data and it works as desired.

use illuminatevalidationrule;

$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
}
By anthonysmothers on May 23 2022

Answers related to “laravel how to check validate unique table two field”

Only authorized users can answer the Search term. Please sign in first, or register a free account.