0

I am trying to check unique validation on three columns employee_id,designation_id,station_id but the data are coming as an array which is making my situation unique and different from other SO questions/answers. I already checked few question like below: checks unique validation on multiple columns

But in my case, I can't get the value as they are inside an array. I also tried to implement Custom Rule or Request but in vain. For all the attempts, I am failing to get the field value such as $request->employee_id as they are inside an array for my case. May be I'm not trying it right.

Controller Code:

    $this->validate($request, [
        'posting.*.employee_id' => 'required,unique: // what to do here ??',
        'posting.*.designation_id' => 'required',
        'posting.*.station_id' => 'required',
        'posting.*.from_date' => 'required|date',
    ]);

I am trying to validate uniqueness for both create and update (along with ignore $this->id facility) but don't know how to implement it here for array. It would be no problem if there was no array. Any help/suggestion/guide is much appreciated. Thanks in advance.

Farhan Ibn Wahid
  • 926
  • 1
  • 9
  • 22

1 Answers1

0

You can do this by creating a rule i.e UniquePosting so your controller code would look like

$this->validate($request, [
    'posting' => ['required'],
    'posting.*' => ['required', new UniquePosting()],
    'posting.*.employee_id' => 'required',
    'posting.*.designation_id' => 'required',
    'posting.*.station_id' => 'required',
    'posting.*.from_date' => 'required|date',
]);

Now inside your UniquePosting rule passes function will look like

public function passes($attribute, $value) {
    $exists = Posting::where(['employee_id' => $value['employee_id'], 'designation_id' => $value['designation_id'],'station_id' => $value['station_id')->exists();
 return !$exists;
}

Add any change if needed, overall that's the concept for testing uniqueness of the whole array.

Faizan Khan
  • 19
  • 1
  • 3