Search code examples
phpjsonlaravellaravel-5.3laravel-validation

Laravel array of objects validation


I'm trying to do a validation in Laravel for an associative array of objects.

A valid JSON string that I pass to the controller looks like this:

{
    'create': [
        {
            'artnr': '123456',
            'unit':  'Stk.'
        },
        {
            'artnr': '23456',
            'unit':  'Kg.'
        }
    ],
    'update': [
        {
            'id': 1
            'artnr': '567890',
            'unit':  'Stk.'
        },
        {
            'id': 2
            'artnr': '67836',
            'unit':  'Kg.'
        }
    ]
}

The controller function which validates the data looks like this:

public function store(Request $request)
{
    $request->replace(array(
        'create' => json_decode($request->create),
        'update' => json_decode($request->update)
    ));

    $validator = Validator::make($request->all(), [
        'create' => 'required|array',
        'create.*.artnr' => 'required|max:20',
        'create.*.unit' => 'max:20',
        'update' => 'required|array',
        'update.*.id' => 'required|exists:products,id',
        'update.*.artnr' => 'required|max:20',
        'update.*.unit' => 'max:20'
    ])->validate();
}

Although I specify in the store function that an artnr must exist for every object, the controller doesn't throw an error when I pass an object without an artnr.

Any ideas what I am doing wrong?


Edit

Okay so after following user2486's suggestion and using different sample data, I now found out that the validator works when I pass the properties like id, artnr, unit as an associative array. Like this:

$arr = array(
    'create' => array(
        array(
            'artnr' => '123456',
            'unit' => 'Kg'
        ), array(
            'unit' => 'Stk.'
        )
    ), 'update' => array(
        array(
            'id' => 1,
            'unit' => 'Stk.'
        ), array(
            'id' => 2,
            'artnr' => '123456',
            'unit' => 'Kg'
        )
    )
);

When I decode my JSON string however, the properties are parsed into an object and therefore no errors are thrown!

Is it possible that the validator rules use a different kind of notation for objects?

If it should not be possible to validate objects, I think I would just convert every object into an associative array.


Solution

  • Okay so the solution was to call my json_decode functions like this json_decode($request->create, true). With the second parameter set to true the function converts every JSON object into an associative array.