Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Get invalid elements from Validator

Is it possible to get the failing elements from the input array (or indexes at least)?

Example:

$data = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Robert', 'age' => 'nope'],
    ['name' => ['woops'], 'age' => 10]
];

$validator = \Validator::make($data, [
    '*.name' => 'required|string|max:200',
    '*.age' => 'required|int'
]);

if(!$validator->passes()){

    /*
        Get all the failed elements.
        In this case: 
        [
            ['name' => 'Robert', 'age' => 'nope'],
            ['name' => ['woops'], 'age' => 10]
        ]
     */
    $fails = $validator->getFailElements();

    // OR

    /*
        Get failed indexes:
        [1,2]
     */
    $indexes = $validator->getFailIndexes();

    //Proceed...

}

The reason is that I'd like to insert invalid data in a table, so it is possible to fix those entries later...

like image 712
CarlosCarucce Avatar asked Nov 15 '25 06:11

CarlosCarucce


1 Answers

You can call invalid() on the validator to get the failed data.

$failed = $validator->invalid();

enter image description here

Reference: https://github.com/illuminate/validation/blob/master/Validator.php#L544

like image 111
Jeremy Harris Avatar answered Nov 17 '25 20:11

Jeremy Harris