Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation - comma separated string input as array

How can I validate one input with multiple values? I'm using bootstrap tagsinput plugin. It returns all tags in one field. I need to validate this tags - unique. First I'm trying to place this tags into array and then validate it in request but still no luck. Here is my code in request:

public function all()
{
    $postData = parent::all();

    // checkbox status
    if(array_key_exists('keywords', $postData)) {

        // put keywords into array
        $keywords = explode(',', $postData['keywords']);

        $test = [];
        $i = 0;
        foreach($keywords as $keyword)
        {
            $test[$i] = $keyword;
            $i++;
        }
        $postData['keywords'] = $test;

    }

    return $postData;

}

public function rules()
{
    $rules = [
        'title' => 'required|min:3|unique:subdomain_categories,title|unique:subdomain_keywords,keyword',
        'description' => '',
        'image' => 'required|image',
        'keywords.*' => 'min:3'
    ];

    return $rules;
}

But as soon as keyword becomes invalid I get this error:

ErrorException in helpers.php line 531: htmlentities() expects parameter 1 to be string, array given.

Any ideas what's wrong?

like image 562
general666 Avatar asked Jan 29 '23 10:01

general666


2 Answers

I was running into a similar problem with comma separated emails on 5.4. Here's how I solved it:

In your request class, override the prepareForValidation() method (which does nothing by default, btw), and explode your comma separated string.

/**
 * @inheritDoc
 */
protected function prepareForValidation()
{
    $this->replace(['keywords' => explode(',', $this->keywords)]);
}

Now you can just use Laravel's normal array validation!

Since my case needed to be a bit more explicit on the messages, too, I added in some attribute and message customizations as well. I made a gist, if that's of interest to you as well

like image 170
zerodahero Avatar answered Feb 02 '23 08:02

zerodahero


Instead of mutating your input, for Laravel 6+ there is a package to apply these validations to a comma separated string of values:

https://github.com/spatie/laravel-validation-rules#delimited

You need to install it:

composer require spatie/laravel-validation-rules

Then, you can use it as a rule (using a FormRequest is recommended).

For example, to validate all items are emails, not long of 20 characters and there are at least 3 of them, you can use:

use Spatie\ValidationRules\Rules\Delimited;

// ...

public function rules()
{
    return [
        'emails' => [(new Delimited('email|max:20'))->min(3)],
    ];
}

The constructor of the validator accepts a validation rule string, a validation instance, or an array. That rules are used to validate all separate values; in this case, 'email|max:20'.

like image 28
nelson6e65 Avatar answered Feb 02 '23 08:02

nelson6e65