Search code examples
jsonlaravellaravel-validation

Using Laravel, is there a way to run validation on one ajax call with data for multiple models?


Assuming one were to post multiple data sets of one model at the time through JSON, it is possible to insert these using Eloquent's Model::create() function. However in my case I'll also need to validate this data.

The Validator only takes a Request object as input, and as far as I've seen I can't create a new Request instance with only one model.

Assuming this would be the input data (JSON), and index is the value for the browser to know what data belongs to an what item (as they have no unique ID assigned at the point of creation)

[
    {
        "index" : 1,
        "name"  : "Item 1",
        "value" : "Some description"
    },
    {
        "index" : 2,
        "name"  : "Item 2",
        "value" : "Something to describe item 2"
    },
    (and so on)
]

Every object in the root array needs to be ran through the same validator. The rules of it are defined in Model::$rules (public static array).

Would there be a way to run the validator against every item, and possibly capture the errors per item?


Solution

  • You can utilize Validator for manual validation:

    ...
    use Validator;
    ...
    $validator = Validator::make(
        json_decode($data, true), // where $data contains your JSON data string
        [
            // List your rules here using wildcard syntax.
            '*.index' => 'required|integer',
            '*.name' => 'required|min:2',
            ...
        ],
        [
            // Array of messages for validation errors.
            ...
        ],
        [
            // Array of attribute titles for validation errors.
            ...
        ]
    );
    
    if ($validator->fails()) {
        // Validation failed.
        // $validator->errors() will return MessageBag with what went wrong.    
        ...
    }
    

    You can read more about validating arrays here.