Confused about Laravel "sometimes" validation works - laravel

I'm really confused about why this is happening? I had successfully added a record then when I tried to update the record It says that the field is required even I passing it already. Then when I tried to add "sometimes" on the validation. Now, it works. Why? Please enlighten me. Thank you!
my Test Model
This was the result when I tried to remove "sometimes"

As per the doc sometimes is used for :
Validating When Present In some situations, you may wish to run
validation checks against a field only if that field is present in the
input array. To quickly accomplish this, add the sometimes rule to
your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email', ]);
Therefore since the request is not containing the expected fields, the validation is successful

Adding sometimes effectively disables the required rule and allows the client to simply not pass that field into the input.
In your case, the validator is probably not receiving the correct data from input. Because If it did, the required rule would act correctly.
Please post the code of your validator to be able to debug the problem.

sometimes is when you sometimes include the field.
Let's see an example of validation when creating a user:-
$validation = [
"name" => "required|string|",
"email" => "required|email",
"hobbies" => "sometimes|array"
];
Sample payloads
{
name: "Bob",
email: "bob#gmail.com"
}
// this will pass
{
name: "Bob",
email: "bob#gmail.com",
hobbies: ["fishing", "swimming"]
}
// this would also pass
{
name: "Bob",
email: "bob#gmail.com",
hobbies: "swimming"
}
// this would fail since it doesn't match "array" validation

Related

Validation in Laravel Spark broken after changing user fields

I have minimally changed the registration process - instead of name, I'm using firstname and lastname. No problem.
form: $.extend(true, new SparkForm({
firstname: '',
lastname: '', email: '' }),
Spark.forms.updateContactInformation)
That works fine for CREATION of the user object, however upon successful registration, I want the user to fill in the rest of their profile - of which there are many new fields I'm adding.
So, in adding all the new fields to the settings page (for example, lastname), on clicking the update button, it seems something is still validating the name, instead of firstname, and I'm unsure where to put in my new fields for validation purposes.
Getting error The name field is required.
As per the docs, I'm using Spark::validateUsersWith to validate the firstname instead of name, hence the create user works - but where is the validation for updating ? I cant seem to locate that.
I can see its using ContactInformationController#update and confirm its being hit with some logging, however even trying explicitly
$this->validate($request, [
'lastname' => 'nullable|max:255',
]);
in there doesn't do the trick - must be something in here but not sure how it works:
$this->interaction(
$request, UpdateContactInformation::class,
[$request->user(), $request->all()]
);

Laravel Array Validation - Continue with passed items

I would like to apply validation rules a request containing an array but handle each exception separately, and continue with the elements that passed the validation.
Lets say I have
{ students: [ {name: 'foo'}, {name: 'barbaz' ] }
and my validator looks
like this:
$validatedStudents = request()->validate([
'students.*.name' => 'required|string|max:3'
]);
I still want to continue with student 'foo' and handle student 'barbaz' separately. Laravel will throw an exception for the entire request and don't continue with any students.
One solution to this would be to loop through students and validate each student, but this is not possible since
foreach (request()->all() as $student) { ... }
will give $student as array and not request. Is it possible to run validate on array/collection like a request?
Thanks

How to combine Laravel validation required_if and required_without_all rules?

I have a situation with a subscription form, which must have different validation rules depending on user selection.
I almost complete this, but I'm stuck in a point which need a combination of rules that I think I can't get with predefined laravel rules.
As shown in the following chart, the point is when a user select invoicing preferences, with options Digital and Printed, if user option is Printed I need at least one physical address, so street address field group OR district address fields group must be mandatory.
Mandatory field unless other field is filled can be achieved by required_without_allrule, so I've trying with no success, a combination of required_if and required_without_allrules, like the following example:
public function rules()
{
return [
...
'invoicing_preferences' => 'required',
'invoicing_email' => 'email|required_if:invoicing_preferences,digital',
'invoicing_street_name' => 'string|required_if:invoicing_preferences,printed|required_without_all:invoicing_district,invoicing_parcel',
'invoicing_street_number' => 'number|required_if:invoicing_preferences,printed|required_without_all:invoicing_district,invoicing_parcel',
'invoicing_street_flat' => 'number|required_if:invoicing_preferences,printed|required_without_all:invoicing_district,invoicing_parcel',
'invoicing_street_dep' => 'alpha_num|required_if:invoicing_preferences,printed|required_without_all:invoicing_district,invoicing_parcel',
'invoicing_district' => 'alpha_num|required_if:invoicing_preferences,printed|required_without_all:invoicing_street_name, invoicing_street_number; invoicing_street_flat,invoicing_street_dep',
'invoicing_parcel' => 'alpha_num|required_if:invoicing_preferences,printed|required_without_all:invoicing_street_name, invoicing_street_number; invoicing_street_flat,invoicing_street_dep',
...
];
}
This combination doesn't work because always results in the required_with_allrule no matter if I've checked digital at the first point.
The rules() method is a method that is expected to return array of rules. Why would I write about such an obvious thing? Well, insert any kind of validation logic inside it, which means that it can also do some evaluation of posted data and gradually build up the returning array.
public function rules()
{
$this; // holds information about request itself with all the data POST-ed
if (something) {
return []; // something is true...
}
return []; // default behaviour (ehm, something is not true)
}
Another similar approach is to use multiple arrays and in the end merge them together (build them up). Which may result in nicer code. Also do not be afraid of using one or two private methods to clean up the code.

Adding Custom Merge Tags in Mailchimp API 3.0

I have get around everywhere, but cannot find any clue to add custom merge tags through the api v3.0. The documentation seems to be very poor and cryptic.
I saw that in the previous version, it can be done through listMergeVarAdd() method.
What I want to do is adding any merge_tags dynamically.
How do I can add custom merge_tags through mailchimp api 3.0 for the use in a custom subscribe form?
Since v3.0 is RESTful, you make a POST call to the /3.0/lists/{list_id}/merge-fields endpoint. The data you pass should match the List Merge Field Instance schema.
Here is an example after some researches, may be someone will find it useful.
This is using VATPS Wrapper available here https://github.com/vatps/mailchimp-rest-api
$api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-usx";
$mc = new MailChimp();
$mc->setApiKey($api_key);
// Create Custom Merge Tags - Example
$result = $mc->post('/lists/{list-id}/merge-fields', array(
"tag" => "CUSTOM_SST",
"required" => false, // or true to set is as required
"name" => "Custom Field",
"type" => "text", // text, number, address, phone, email, date, url, imageurl, radio, dropdown, checkboxes, birthday, zip
"default_value" => "", // anything
"public" => true, // or false to set it as not
"display_order" => 2,
"help_text" => "I try to help you!"
));
print_r($result);
// Check If Merge Tags Already Exists - Example
$result = $mc->get('/lists/{list_id}/merge-fields');
print_r($result);

Default value for a model validate rule

I have a question regarding default values for model fields, this problem has been driving me crazy for a while.
To give you an example, I have a model with a status field that must be validated:
$validate = array (
...
'status' => array(
'list' => array(
'rule' => array('inList', array('0','1')),
'allowEmpty' => true
)
)
)
The data that is inserted in the database is not submitted from a form.
If the status field is missing, I want it to default to 1, otherwise it must be validated.
Is there a way to do this from the model without using custom validation rules? I know I can set the default value in the MySQL table, but I still want to validate it from the model, in case a different value is submitted.
EDIT
I looked at the Validation class code and the inList validation is just a stupid wrapper for an in_array check:
Cake.Utility.Validation.php
public static function inList($check, $list, $strict = true) {
return in_array($check, $list, $strict);
}
What do you know, there is also a third param that is not mentioned in the CakePHP Api docs ($strict), which defaults to true.
From the in_array docs:
If the third parameter strict is set to TRUE then the in_array()
function will also check the types of the needle in the haystack.
It still doesn't solve my problem, but now I know why array('inList', array('0','1')) was not validating empty fields even though allowEmpty was set to true.
Thank you.
You can use the beforeSave method to set a default value. Don't forget to return true or you will abort the save.

Resources