How to validate array in Laravel?
Asterisk symbol (*) is used to check values in the array, not the array itself.
$validator = Validator::make($request->all(), [
"names" => "required|array|min:3",
"names.*" => "required|string|distinct|min:3",
]);
In the example above:
- "names" must be an array with at least 3 elements,
- values in the "names" array must be distinct (unique) strings, at least 3 characters long.
EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:
$data = $request->validate([
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
How to Validate an array in Laravel
you can use present validation
The field under validation must be present in the input data but can be empty.
'topics' => 'present|array'
Laravel Array:Key Validation
Doing a lot of research and trying hard I found the solution:
For everybody searching desperately for an example of advanced array validation in Laravel 8+:
- Step: ALWAYS use an array, not an object.
For that purpose:
public function fCreateArrayFromObject($Object) {
$toArray = function ($x) use (&$toArray) {
return is_scalar($x)
? $x
: array_map($toArray, (array)$x);
};
return $toArray($Object);
}
- Step: I will use my example to show you how its easily done:
My array ($cart):
array:3 [▼
"user1" => array:2 [▼
"Items" => array:5 [▼
"blue" => 0
"grey" => 1
"brown" => 1
"look" => 0
"black" => 0
]
"User" => array:2 [▼
"LastName" => "alice"
"FirstName" => "Bobby"
]
]
"user2" => ......
]
My rules:
$person_count = 2; // Up to 5
$validation_rules = [];
for ($i = 1; $i <= $person_count; $i++) {
$validation_rules += [
"user$i" => "array:Items,Customer|size:2|distinct",
"user$i.user.FirstName" => "required|string|min:2|max:255",
"user$i.user.LastName" => "required|string|min:2|max:255",
"user$i.Items.*" => "required|numeric|min:0",
"user$i.Items" => "required|array:blue,grey,brown,look,black|size:5|distinct",
];
}
Action:
$validated_input = Validator::make((array)$cart, $validation_rules);
I am not quite sure, why the make method doesn't interpret my $cart array without the (array) as an array, but it works.
Goals:
- validate the whole cart: has to contain each person as an array with exactly 2 elements (up to five person arrays) works
- validate each person itself: has to contain the user and items array works
- validate the user array: has to contain the first and last name between 2 and 255 characters each as strings works
- validate the Items array: has to be exactly of size:5, has to contain all the given keys works
- validate the key values of the Items array: they have to be numeric and at least 0 works
Obviously everything has to be existent as well: "required"
Tags: Laravel Array Validation, Laravel Nested Array Validation
Laravel validation for arrays
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();
}
Check if values in array are in another array using Laravel Validation
True that in
doesn't accept an array but a string. So you can just convert the array into a string.
$my_arr = ['item1', 'item2', 'item3', 'item4'];
Validator::make($request, [
'item' => [ 'in:' . implode(',', $my_arr) ],
]);
implode
Another better solution might be to use Illuminate\Validation\Rule
's in
method that accepts an array:
'item' => [ Rule::in($my_arr) ],
Laravel Validation - Rule::in
How to validate array of files in Laravel?
I have mixed the stackoverflow solution with Laravel's custom validation rule which solved my problem with a modern solution.
https://dev.to/moose_said/create-custom-laravel-validation-rule-for-total-uploaded-files-size-1odb
Laravel validate array and exclude on specific array value
Your problem comes from a misunderstanding of the exclude_if
rule. It doesn't exclude the value from validation, it only excludes the value from the returned data. So it would not be included if you ran request()->validated()
to get the validated input values.
According to the documentation, you can use validation rules with array/star notation so using the required_unless
rule might be a better approach. (Note there's also more concise code to replace the old unique
rule, and I've added a rule to check contents of the role status.)
$rules = [
'displayname' => 'required',
'username' => 'required',
'email' => [
'nullable',
Rule::unique("contacts")->ignore($userid ?? 0)
],
'roles' => 'array',
'roles.*.status' => 'in:I,U,D',
'roles.*.role_id' => ['required_unless:roles.*.status,D']
];
Related Topics
Error Message Strict Standards: Non-Static Method Should Not Be Called Statically in PHP
PHP Login System: Remember Me (Persistent Cookie)
How to Show Ajax Requests in Url
How to Check If an Array Contains a Specific Value in PHP
How Does the Keyword "Use" Work in PHP and How to Import Classes With It
Notice: Trying to Get Property of Non-Object Error
How to Get Single Value from This Multi-dimensional PHP Array
PHP Equivalent of .Net/Java'S Tostring()
Architecture More Suitable For Web Apps Than MVC
Which One Is the Best Pdf-API For PHP
Find the Last Element of an Array While Using a Foreach Loop in PHP
Best Way to Test For a Variable'S Existence in PHP; Isset() Is Clearly Broken
What Exactly Are Late Static Bindings in PHP
How to Round Up a Number to Nearest 10
How to Get Code Point Number For a Given Character in a Utf-8 String