2

I have this request:

GET http://example.com/test?q[]=1&q[]=2&q[]=3

And I have this route:

Route::get('test', function(Request $req) {
    $req->validate(['q' => 'array']);
});

How should I do to add other validation rules to each element of this array using Laravel validator? For example, I want to check that each q value has a minimum of 2.

Thank you for your help.

2

3 Answers 3

5

Take a look at the documentation about validating arrays.

$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);

You can also do this in your controller using the Request object, documentation about validation logic.

public function store(Request $request)
{
  $validatedData = $request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
  ]);

  // The blog post is valid...
}

There is a third option for when you have a lot of validation rules and want to separate the logic in your application. Take a look at Form Requests

1) Create a Form Request Class

php artisan make:request StoreBlogPost

2) Add Rules to the Class, created at the app/Http/Requestsdirectory.

public function rules()
{
  return [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
  ];
}

3) Retrieve the request in your controller, it's already validated.

public function store(StoreBlogPost $request)
{
  // The incoming request is valid...

  // Retrieve the validated input data...
  $validated = $request->validated();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

Route::get('test', function(Request $req) {
    $req->validate([
        'q' => 'array',
        'q.*' => 'min:2'
    ]);
});

For more information on validation of arrays, see => laravel.com/docs/5.6/validation#validating-arrays

Comments

0

Suppose I got an array of users

users: [
    {
        "id": 1,
        "name": "Jack",
    },
    {
        "id": 2,
        "name": "Jon"
    }
]

I would validate it like below :

$request->validate([
    'users[*]'=> [
        "id" => ["integer", "required"],
        "name" => ["string", "required"]
    ]
]);

Here * acts as a placeholder

Comments

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.