1

I have an array that makes in front end with js and pass that to my controller with ajax.

Ajax:

var values = [{FirstName: "fff"},{LastName: null}]
$.ajax({
    method: "POST",
    url: "/api/store-step",
    data: { values: values, step: activePanelNum }
    }).fail(function (jqXHR, textStatus, error,result) {
       console.log(jqXHR.responseJSON.errors);
    }).done(function( result ) {
       console.log(result);
    });

structure of array is this:

[{FirstName: "fff"},{LastName: null}]

Controller:

public function storeSteps(Request $request)
{     
    $validator = Validator::make($request->values, [
       'FirstName' => 'required',
       'LastName' => 'required',
    ]);

    if ($validator->fails()) {
       return response()->json(['success'=>false, 'errors' => $validator->getMessageBag()->toArray()],422);
        }
}

I can't validate this array with request validation Laravel. Now I'm going to turn this array into a Larval request to apply the rules to it.

Can any one helps?

1 Answer 1

7

you can validate array element like this

$validator = Validator::make($request->all(), [
            'values' => 'required',
            'values.*.FirstName' => 'required',
            'values.*.lastName' => 'required','
        ]);

by using . you can access an index in a array and * apples all indexes in the array.

Sign up to request clarification or add additional context in comments.

9 Comments

in addition to this above, you might need to json_decode() that array first.
what is array_name here?
@MohammadHosseini you need to passe you array in a name that what I meant by that. array_name : [{FirstName: "fff"}, {LastName: null} ]
Here I don't have $maked_laravel_request_from_array I want to create that
I update question and explain Clearer my problem. I want to make laravel request from array....means from $request->values
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.