Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validating An Array in Update Method With Multiple Rows Needing Ignoring

Tags:

php

laravel

I'm trying to validate an array within the update method which means I need to ignore the id's of the rows so that it doesn'r return the error:

contactName has already been taken

Here is my validation from my update method of my controller:

public function update($id, Request $request)
{
    $brand = Brand::findOrFail($id);

    $request->validate([
        'name' => ['required', 'string', 'max:255', Rule::unique('brands')->ignore($id)],
        'contactNames' => ['required', 'array'],
        'contactNames.*' => ['required', 'max:255', 'string', 'distinct', Rule::unique('brand_managers', 'name')->ignore( //what goes here? )],
        'emails' => ['required', 'array'],
        'emails.*' => ['required', 'max:255', 'email', 'distinct', Rule::unique('brand_managers', 'email')->ignore( //what goes here? )],
        'contactNumbers' => ['array'],
        'contactNumbers.*' => ['numeric'],
        'groupCheckbox' => ['required', 'min:1'],
    ]);
}

With the unique validation rule on 'name' I can ignore the id that is coming with the $id using route model binding, but with the contactNames and contactEmails this needs to check a table that has a manyToMany relationship - how do I ignore the id's of the brand_manager rows for multiple validation checks?

I will try and edit my question for more clarity

Thanks!

like image 813
CodeBoyCode Avatar asked Mar 01 '19 12:03

CodeBoyCode


1 Answers

You can easily create validation rules dynamically as you wish.

Here is example from my current project which requires unique field except self.

use Illuminate\Validation\Rule;

$unique_check = Rule::unique('brand_managers', 'email'); // table with some unique rows

//if you need ignore multiple rows/multiple conditions
$unique_check->where(function ($query) use ($brand) {
    return $query->whereNotIn('id', $brand->brand_managers->pluck('id')->toArray());
});

$request->validate([
    'emails.*' => [ // promocode unique string column
        'required',
        $unique_check
    ],
]);
like image 80
Sanasol Avatar answered Sep 28 '22 06:09

Sanasol