PHP Laravel Validation data key names - laravel

I got such problem.
What I want to do - is to make 1 place for validation rules for a user data. These data consists of Patient, Address and other objects.
So I created rules:
protected function validationRules()
{
return [
'Patient.firstName' => 'required|string|min:2',
'Patient.lastName' => 'required|string',
'Patient.sex' => 'required|string',
'Address.city' => 'required|string',
'Address.states' => 'required|string',
'Address.address1' => 'required|string|min:2',
'Address.zip' => 'required|string|min:2',
'Phone.mobileArea' => 'string|min:3|required_with:Phone.mobilePhone',
'Phone.mobilePhone' => 'string|min:7|required_with:Phone.mobileArea',
'Phone.homePhone' => 'string|min:7|required_with:Phone.homeArea',
'Phone.homeArea' => 'string|min:3|required_with:Phone.homePhone',
];
}
In form i have inputs like
<input id="firstName" type="text" class="form-control" name="Patient[firstName]" value="{{ $user->getFirstName() }}" required autofocus placeholder="First Name">
And on save everything works correctly.
The code
$this->validate($request, $this->validationRules());
Performs validation very well. BUT....
On another place, when I want to show that some information is missing in the user profile, I perform such validation and its failed:
$validator = Validator::make([
'Patient[firstName]' => $user->getFirstName(),
'Patient[lastName]' => $user->getLastName(),
'Patient.lastName' => $user->getLastName(),
'Patient->lastName' => $user->getLastName(),
'Patient.sex' => $user->getSex(),
'Address.city' => $address->getCity(),
'Address.states' => $address->getState(),
'Address.address1' => $address->getStreet1(),
'Address.zip' => $address->getZip(),
'Phone.mobileArea' => $mobilePhone->getArea(),
'Phone.mobilePhone' => $mobilePhone->getNumber(),
'Phone.homePhone' => $homePhone->getArea(),
'Phone.homeArea' => $homePhone->getNumber(),
], $this->validationRules());
As you can see, i tried different variations of naming Patient->lastName key in data array. But i still have error that last name is required.
When i print validator i can see such structure:
Validator {#300 ▼
#data: array:12 [▼
"Patient[firstName]" => ""
"Patient[lastName]" => "Colohanin"
"Patient->lastName" => "Colohanin"
"Patient->sex" => "female"
"Address->city" => "GOSHEN2"
"Address->states" => "NY"
"Address->address1" => "Aleco Russo 59/1 a.68"
"Address->zip" => "109242"
"Phone->mobileArea" => "793"
"Phone->mobilePhone" => "906990"
"Phone->homePhone" => "022"
"Phone->homeArea" => "3322278"
]
#initialRules: array:1 [▼
"Patient.lastName" => "required|string"
]
}
As I understand, the validator has rules for "Patient.lastName" but in data array Laravel transform this key to object and Validator can't find this key in data bag. In result, I have error - > patient last name required(for testing purposes, I removed other rules)
So there is my question. Does anyone know, how to set data array in "dot" sintancs? How should i name "Patient.lastName" in data array(first parameter in Validator::make())?
The rewriting keys using underscore doesn't accept(patient_firstName)

Suddenly i found that laravel helper have array_set helper for such arrays.
So in result:
$data = [
'Patient[firstName]' => $user->getFirstName(),
'Patient[lastName]' => $user->getLastName(),
'Patient["lastName"]' => $user->getLastName(),
'Patient.lastName' => $user->getLastName(),
'Patient->lastName' => $user->getLastName(),
'Address.city' => $address->getCity(),
'Address.states' => $address->getState(),
'Address.address1' => $address->getStreet1(),
'Address.zip' => $address->getZip(),
'Phone.mobileArea' => $mobilePhone->getArea(),
'Phone.mobilePhone' => $mobilePhone->getNumber(),
'Phone.homePhone' => $homePhone->getArea(),
'Phone.homeArea' => $homePhone->getNumber(),
];
Fails validation, but if you add elements throw array_set helper it helps
array_set
array_set($data, 'Patient.lastName' , $user->getLastName());
After that, validation by lastName is no longer fails.
Hope it helps somebody

try this:
$this->validate($request->get('Patient'), $this->validationRules());
form input:
all name changes it to :
<input id="firstName" type="text" class="form-control" name="Patient[firstName]" value="{{ $user->getFirstName() }}" required autofocus placeholder="First Name">
<input id="mobileArea" type="text" class="form-control" name="Patient[mobileArea]" value="{{ $user->mobileArea() }}" required autofocus placeholder="mobileArea"
>
and change all validationrules using:
protected function validationRules()
{
return [
'Patient.firstName' => 'required|string|min:2',
'Patient.lastName' => 'required|string',
'Patient.sex' => 'required|string',
'Patient.city' => 'required|string',
'Patient.states' => 'required|string',
'Patient.address1' => 'required|string|min:2',
'Patient.zip' => 'required|string|min:2',
'Patient.mobileArea' => 'string|min:3|required_with:Patient.mobilePhone',
'Patient.mobilePhone' => 'string|min:7|required_with:Patient.mobileArea',
'Patient.homePhone' => 'string|min:7|required_with:Patient.homeArea',
'Patient.homeArea' => 'string|min:3|required_with:Patient.homePhone',
];
}
Hope it help

Related

Laravel 9 Field doesn't have a default value

In my project, I got many forms, so I've decided to specify each one with an iscription field, for exemple: Kids' form => <input = 'hidden' name = 'inscripted_in' value = 'kids'>. I want to set each one with a default value, but whenever I sign in, I get this error message:
SQLSTATE[HY000]: General error: 1364 Field 'inscripted_at' doesn't have a default value
Although when I go to Laravel Debug, I still get the inserted constant value, what's the problem?
This is one of my forms
<div class="InputBox">
<input type="hidden" name="inscripted_at" value="Adults">
<input type="hidden" name="status" value="pending">
</div>
my controller:
public function store(Request $req)
{
$this->validate($req,[
'name' => 'required|max:120',
'surname' => 'required|max:120',
'job' => 'required|max:120',
'day' => 'required',
'month' => 'required',
'year' => 'required',
'hobby' => 'required|max:120',
'help' => 'required|max:120',
'place' => 'required|max:120',
'residence' => 'required|max:120',
'email' => 'required|email|unique:users',
'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'scholar_year' => 'required|max:120',
'tel' => 'required|regex:/(05)[0-9]{8}/',
]);
Chababounauser::create($req->all());
return redirect()->route('chababounausers.index')
->with('success','chababouna User inserted successfully.');
}
Check the fillable property of the Chababounauser model.
P.S.: Please, don't put spaces in HTML between attribute name and it's value.
Isn't 'inscripted_at' a default column in the database giving the date of inscription ? If so, you can't default a value to that kind of output.

Problems in implement reCaptcha V3 in laravel

I am using Google reCaptcha v3. I am trying to implement it onto my profile page.It's load and shown in my page ,but when I want to verify it ,it does not work ,I am using this package:https://github.com/RyanDaDeng/laravel-google-recaptcha-v3#settings
in this config :
'secret_key' => env('RECAPTCHA_V3_SECRET_KEY', '6LcqC'),
'site_key' => env('RECAPTCHA_V3_SITE_KEY', '6LcqnrO-K-xb'),
in this blade :
<form>
{!! GoogleReCaptchaV3::renderOne('contact_us_id','contact_us') !!}
</form>
in my controller:
public function get_data_edit(Request $request)
{
$request->validate(
[
'phone' => ['required', 'max:11', new phone],
'year' => 'nullable|numeric',
'month' => 'nullable|numeric|max:12',
'day' => 'nullable|numeric|max:31',
'sex' => 'nullable|boolean',
'marital_status' => 'nullable|boolean',
'f_name' => 'required|max:15',
'l_name' => 'required|max:20',
'job' => 'nullable|string',
'email' => 'nullable|email',
'national_code' => 'nullable|min:10|max:10',
'family_role' => 'nullable|string',
'g-recaptcha-response' => [new GoogleReCaptchaV3ValidationRule('contact_us')]
],
[]
);
where is my problem ?

Yii2 - Add additional data attributes to dropDownList() elements and have it selected?

Question already exists with answer (below link), but:
1) doesn't work for me
2) doesn't include the added need to have a selected option
yii2 how to add additional attributes to dropDownList() elements??
Can help?
IM USING:
<?=$form->field($invoice, 'id')
->dropDownList(ArrayHelper::map($some_items_array, 'value_field', 'show_field'), [
'options' => [
$some_selected_id => ['Selected'=>true]],
'data' => ['attrib1' => "valueA', 'attrib2' => "valueB']
'class' => 'form-control',
'prompt' => ''])->label(false);
?>
I NEED, BUT DO NOT GET:
<select name="name">
<option value="value" data-attrib1="valueA" data-attrib2="valueB">text< option>
</select>
Already answered here > YII - Add another attribute to dropDownList
$attributes = [
'attrib1' => 'valueA',
'attrib2' => 'valueB',
];
foreach ($some_items_array as $index => $att) {
$dropdownlist_options[$index] = $attributes;
}
<?=$form->field($invoice, 'id')
->dropDownList(ArrayHelper::map($some_items_array, 'value_field', 'show_field'), [
'options' => $dropdownlist_options, /* [
$some_selected_id => [
'selected' => true,
'attrib1' => 'valueA',
'attrib2' => 'valueB',
],
$some_other_id => [
'attrib1' => 'valueA',
'attrib2' => 'valueB',
],
],*/
'class' => 'form-control',
'prompt' => '',
])->label(false);
?>

How to apply a validation rule to every element present within an array?

How to apply validation rules to every item within an items[] array? For example:
...->validate($request, [
'items[]' => 'required' // <-- what is the correct syntax?
]);
Try something like this
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Where person is the name of the input field and email is the key
Laravel 5.2 has an array validation all you need to do is :
In your view assuming that you have an inputs like this :
<input type="text" name="example[]" />
<input type="text" name="example[]" />
The [] are the key for this :)
And in your controller you can just do :
$this->validate($request, [
'example.*' => 'required|email'
]);
$this->validate($request, [
'items' => 'required|array',
'items.*.title' => 'required',
]);

Laravel Spark - Adding additional fields to registration form, but when empty no errors are returned

I'm building my first app with Laravel 5.2 & Laravel Spark. The front end is built using Vue.js I believe and despite adding the following to register-common-form.blade.php:
<!-- Username -->
<div class="form-group" :class="{'has-error': registerForm.errors.has('username')}">
<label class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input type="name" class="form-control" name="username" v-model="registerForm.username" autofocus>
<span class="help-block" v-show="registerForm.errors.has('username')">
#{{ registerForm.errors.get('username') }}
</span>
</div>
</div>
I can't actually see a way to fully register that extra field so that it is picked up for error handling. I've got it so that the UserRepository handles the field and inserts it, but just can't get the front end errors to show properly.
Is anyone able to help with this at all?
Okay I finally stumbled across it :D
In Laravel\Spark\Interactions\Auth\CreateUser.php there is a $rules method like so:
public function rules($request)
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
All I have done is add my username field, and it works brilliantly!
public function rules($request)
{
return [
'name' => 'required|max:255',
'username' => 'required|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
Above answer is just for validation rules you also need to navigate to spark\src\Repositories\UserRepository.php and add 'username' => $data['username'], to the create() method like this:
public function create(array $data)
{
$user = Spark::user();
$user->forceFill([
'name' => $data['name'],
'username' => $data['username'], // ADDED THIS
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => str_random(30),
'last_read_announcements_at' => Carbon::now(),
'trial_ends_at' => Carbon::now()->addDays(Spark::trialDays()),
])->save();
return $user;
}

Resources