Reputation: 21
I have a table GateAccess: id, person_id, gate_id, time_id. When adding a new record to this table I'd like to prevent adding several records with the same gate_id for one person_id. Gate_id must be unique for particular person_id.
I'd like to have table like this:
id, person_id, gate_id, time_id
1, 2, 1, 1
2, 2, 2, 2
but not the one:
id, person_id, gate_id, time_id
1, 2, 1, 1
2, 2, 1, 2
I have a validator:
$validator = Validator::make($data, [
'first_name' => 'required',
], $messages);
Can you help me to make rule for this validator?
Upvotes: 2
Views: 138
Reputation: 61
You need specify when you unique validation rules applied. With laravel validator in like this:
[
'some_field'=>'unique:table,field,NULL,id,criteria,compare'
]
That rule says that "some_field" will by unique when "criteria" are equal to "compare"
For you example is like this
$person_id = Request::get('person_id');
$gate_id = Request::get('gate_id');
[
'person_id' => 'unique:GateAccess,person_id,NULL,id,gate_id,' . $gate_id;
'gate_id' => 'unique:GateAccess,gate_id,NULL,id,person_id,' . $person_id;
];
So person_id will by unique when gate_id are equal to $gate_id and the same way for gate_id
Upvotes: 1
Reputation: 3972
you could use the validator rule
to achieve what you want, so in your case your validation should look like this.
Validator::make($data, [
'gate_id' => [
'required',
Rule::unique('GateAccess')->where(function ($query) use($data){
$query->where('person_id', $data->person_id);
})->ignore($request->id),
],
])->validate();
It will set the gate_id as unique where the person id in your record is equal to the person id you passed.
don't forget to add this above in your code
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
Upvotes: 1