2

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?

1
  • In addition to validation, consider a unique key at the database level. Commented Feb 25, 2020 at 15:18

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.