JacopoStanchi
JacopoStanchi

Reputation: 2136

Laravel validation for arrays

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.

Upvotes: 2

Views: 6872

Answers (3)

ISHRAQ KABIR
ISHRAQ KABIR

Reputation: 11

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

Upvotes: 0

Kerel
Kerel

Reputation: 732

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();
}

Upvotes: 5

JacopoStanchi
JacopoStanchi

Reputation: 2136

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

Upvotes: 1

Related Questions