eggplantSword's avatar

Unique Rule on array variable

How can I correctly set these validation rules?

I have an array coming in where the title has a unique rule set to it, but I'm not sure how to grab that items' id? The id on the route for the parent item, so I need to grab the id from the array element too.

    return [
        'survey_charts' => 'array|required',
        'survey_charts.*.id' => 'sometimes',
        'survey_charts.*.title' => 'required|string|unique:survey_charts,title,' + ?,
    ];
0 likes
1 reply
eggplantSword's avatar
eggplantSword
OP
Best Answer
Level 9

what I ended up doing

        $rules = [
            'survey_charts' => 'array|required',
            'survey_charts.*.id' => 'sometimes'
        ];

        $rules['survey_charts.*'] = Rule::forEach(function ($value, $attribute) {
            return [
                'title' => 'required|string|unique:survey_charts,title,' . $value['id'],
            ];
        });

        return $rules;

Please or to participate in this conversation.