How to make json array validation in Laravel?

Viewed 44

I have one json array like and it's have limited questions.

{
"section_slug": "personal_info",
"questions": [
    {
    "question_slug":"whats-your-hobbies",
    "answers":[
            {
                "answer_slug":"Cooking",
                "answer":"Cooking"
            },
        ]
    },
    {
        "question_slug": "education",
        "answers": [
            {
                "answer_slug": "Masters",
                "answer": "Masters"
            }
        ]
    },
    {
        "question_slug": "state",
        "answers": [
            {
                "answer_slug": "Alaska",
                "answer": "Alaska"
            }
        ]
    },
]

}

I want to need expected outpoot is :

  1. "section_slug is required",
  2. "education is required",
  3. "education answer is required",
  4. "State is required",
  5. "State answer is required"

In case user have not added quastion like 'city' So need show error city is required.

Please I need your supports. Thanks.

1 Answers

If you use this in the case of receiving a request from a form, then in this case you'd better use the request class:

php artisan make:request StoreFormRequest
// app/Http/Requests/StoreFormRequest

And denote the rules of all fields inside it:

public function rules()
{
    return [
        'section_slug' => 'required|regex:/^[a-z-0-9]+$/'
        // ...

    ];
}

public function messages()
{
    return [
        'section_slug.required' => 'Slug is required.',
        'section_slug.regex' => 'Slug has incorrectly format.'
    ];
}

The controller method code will not be executed if the validation of the fields is not passed. Use like this:

public function store(StoreFormRequest $request)
{
    Form::create($request->validated());
}
Related