1

Using laravel validation, I would like to ensure that a field is unique, but in an array context. (I have seen this and this but they don't address the array context.)

Let's suppose I have this html:

<input name="sites[1][id]"><input name="sites[1][site_mrn]">
<input name="sites[2][id]"><input name="sites[2][site_mrn]">
<input name="sites[3][id]"><input name="sites[3][site_mrn]">

In my validation rule, I want to ensure that each site's id is valid, and that the site_mrn is not blank, so I have:

public function rules()
{
    return [
        'sites.*.site_mrn' => 'required|min:1',
        'sites.*.id' => 'exists:sites,id'
    ];
 }

So that part works. My problem is that I want to ensure that each pair of site site_id and site_mrn are unique in the mpi_sites table, but I don't know how to access each id/site_mrn pair in the input. I want to do something like this:

'sites.*' => Rule::unique('mpi_sites')->where(function ($q) {
        $q->where('site_id', $xxxxx)->where('site_mrn', $yyyyy);
    })
mankowitz
  • 1,864
  • 1
  • 14
  • 32
  • Did you check the after validation hook? It may be a possibility for you? https://laravel.com/docs/8.x/validation#after-validation-hook – Daantje Apr 16 '21 at 00:47
  • Maybe this gives you inspiration on how to solve your issue: https://stackoverflow.com/questions/43147584/laravel-validation-rules-if-value-exists-in-another-field-array – Roël Gonzalez Apr 16 '21 at 20:25

0 Answers0