3
votes

I'm having trouble validating an input array and checking using the unique: validation rule, and I was hoping someone could help me further.

Input (multiple of) from view:

<input type="text" class="form-control" name="contactNames[]" required>

an example of my dd($request):

+request: ParameterBag {#44 ▼
    #parameters: array:6 [▼
        "_token" => "0WBYH4G4aB4XtkQ1Vx29cIvaH7SbYYVcXI6yOuNn"
        "name" => "Brand Name"
        "groupCheckbox" => array:3 [▶]
        "contactNames" => array:2 [▼
            0 => "Contact Name 1"
            1 => "Contact Name 2"
        ]
        "emails" => array:2 [▼
            0 => "[email protected]"
            1 => "[email protected]"
        ]
        "contactNumbers" => array:2 [▼
            0 => "07777777777"
            1 => "07777777777"
        ]
    ]
}

and within my controller, my validation:

$request->validate([
    'name' => 'required|string|max:255|unique:brands',
    'contactNames' => 'required|array',
    'contactNames.*' => 'required|max:255|string|distinct|unique:brand_managers',
    'emails' => 'required|array',
    'emails.*' => 'required|max:255|email|distinct|unique:brand_managers',
    'contactNumbers' => 'array',
    'contactNumbers.*' => 'numeric',
    'groupCheckbox' => 'required|min:1'
]);

I need to check whether a username is unique or not - the validation works fine if I don't use the unique: validation rule and the data posts correctly to my database, however I don't want multiple brand managers with the same details so need to validate the uniqueness of name and email address

The error I am getting is:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'contactNames.0' in 'where clause' (SQL: select count(*) as aggregate from brand_managers where contactNames.0 = Contact Name 1)

Thanks for your help in advance

1
can you post the controller code that you have the validation, where you update the model ? - Vidal
brand_managers is a table name? - Iftikhar uddin

1 Answers

4
votes

I have found a solution - thanks for the help though - for anyone else in the future who may have the same problem here was my solution:

$request->validate([
    'name' => 'required|string|max:255|unique:brands',
    'contactNames' => 'required|array',
    'contactNames.*' => ['required', 'max:255', 'string', 'distinct', Rule::unique('brand_managers', 'name')],
    'emails' => 'required|array',
    'emails.*' => ['required', 'max:255', 'email', 'distinct', Rule::unique('brand_managers', 'email')],
    'contactNumbers' => 'array',
    'contactNumbers.*' => 'numeric',
    'groupCheckbox' => 'required|min:1'
]);