vendredi 29 septembre 2017

Validate that each comma separated value exists in database?

Using Laravel 5.4, my users have an auto-complete helper to put values into an input. I want to validate that each of the values exists in the database when inserting.

Inputted value for "unit" : "12,13,14"

How do I check that, unit "12" and unit "13" and unit "14" exist in the database before doing the insert?

$units = array_filter(array_unique(explode(",", $request->unit))); 
 // input "12,13,14" becomes [12,13,14]

$this->validate($request,[
        'unit'  => 'required|exists:units.id,'.$units,
]);

Do I have to use a custom validation rule, or does laravel have something handy like 'required|existsAllValuesInThisArray' sorta thing? Haven't found anything in documentation about it.


I also found this, but it's for like multiple select fields or checkboxes sorta thing from the looks of it.

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire