Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Chron's avatar
Level 6

Validating array of ids

There's a validation called unique and exists, but I'm getting Array to string conversion error because I'm passing an array of ids. Is there a way to check if these ids passed the validation?

0 likes
10 replies
Chron's avatar
Level 6

I'm still getting Array to string conversion

    public function rules()
    {
        return [
            'data.*' => ['required', 'string', 'unique:table,id,'.$this->data],
        ];
    }
MichalOravec's avatar

What is $this->data?

public function rules()
{
    return [
        'data.*' => 'required|integer|unique:table,id'
    ];
}

Also you have propably id as integer not a string.

Chron's avatar
Level 6

Also you have propably id as integer not a string.

Ohh, I didn't noticed that, sorry.

What is $this->data

That contains the array of ids when I'm updating data.

MichalOravec's avatar

You don't need to put it there. Just use what I posted before and it will be work.

Chron's avatar
Level 6

I removed it and I'm getting The id has been taken validation error. I added that because it wouldn't throw an error if I submitted the data without updating it, but it doesn't work, I'm getting array to string conversion error.

MichalOravec's avatar

If you get "The id has been taken." so it means that your validation works. But honestly I don't know why you want to allow insert ids. It should be autoincrement and just check other values when you insert new data.

Chron's avatar
Level 6

I'm not adding the ids as primary keys, I'm adding them as a data for a pivot table.

Chron's avatar
Level 6

I think we're not on the same page.

I'm trying to do this.

https://laravel.com/docs/5.8/validation#rule-unique

I don't need exists when updating data, I have unique because the data has to be different from the other data in the table. I also want to ignore the data if it is not changed. If I didn't used unique with an extra param, when I submitted an update form but didn't changed the data, it will throw an error.

Please or to participate in this conversation.