Laravel: conditional validation rules - laravel

In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.
SomeController.php
private function validations($customRules = [])
{
# variables
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'required|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
$messages = [
'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
'contact_person.min' => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',
'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
'mobile_number.numeric' => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',
'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
'email.email' => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',
'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
'pword.min' => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',
'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
];
if(!empty($customRules))
$rules = \array_merge($rules, $customRules);
# returning
return request()->validate($rules, $messages);
}
After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.
Currently I am forced to do this.
public function update()
{
...
# validating submitted data
if(!empty(request()->pword))
$this->validations([ 'pword' => 'min:6' ]);
else
$this->validations([ 'pword' => '' ]);
....
}

You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
So your method would be like
private function validations($request,$update = false){
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'nullable|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
}

Related

Sending custom verification emails from a controller method

I have some data i am receiving from new users and extracting the email to send to the new user. This is how i am doing it
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$data = $request->all();
$name = $request->input('name');
$data['role'] = 'manager';
$email = $request->input('email');
User::create([
'email' => $request->input('email'),
'name' => $request->input('name'),
'role' => 'manager',
'password' => Hash::make($request->input('password')),
//'email_verified_at' => now()
]);
$user = User::where('email','=',$email)->first();
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
I am getting this error
403 THIS ACTION IS UNAUTHORIZED
The docs say its because of signed urls https://laravel.com/docs/9.x/urls#signed-urls
I haven't modified the existing email verification code as shipped with laravel. How do i use the signed urls feature in my case?.
Not an answer, but your code could be significantly simpler, making it easier to manage in the future.
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$user = User::create([
'email' => $validatedData['email'],
'name' => $validatedData['name'],
'role' => 'manager',
'password' => Hash::make($validatedData['password']),
'email_verified_at' => now()
]);
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
But why ask the user to verify their email when you are already setting the email_verified_at timestamp (indicating that verification has been performed)

Laravel make custom error validation messages

Greeting, this is my code and I need to make custom error messages for every rule
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return response()->json($errors);
}
Its better to create a separate request for validation purpose
public function rules(): array
{
return [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
]
}
public function messages(): array
{
return [
'name' => 'Please enter name'
];
}
you can create your own custom validation messages in two ways:
1- in resources/lang/en/validation.php you can change the validation message for every rule
2- you can pass your custom message for each validation like this:
$validator = Validator::make($input, $rules, $messages = [
'required' => 'The :attribute field is required.',
]);
you can check here for more information
specific to your question:
$messages = [
'required' => 'The :attribute field is required.',
'min' => ':attribute must be more than 3 chars, less than 100'
]
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
], $messages);

parse_url() expects parameter 1 to be string, array given when creating user laravel

Im building my onw registration in laravel and when im trying to hash my password i get the error parse_url() expects parameter 1 to be string, array given
//Controller
HomeController.php
$filteredValidation = $request->except('_token');
$password = Hash::make($filteredValidation['password']);
UserRegistrationRequest::create([
'firstname' => $filteredValidation['firstname'],
'lastname' => $filteredValidation['lastname'],
'email' => $filteredValidation['email'],
'year' => $filteredValidation['year'],
'avatar' => $filteredValidation['firstname'],
'buddy' => $filteredValidation['firstname'],
'password' => $password,
]);
//request
UserRegistrationRequest.php
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'year' => 'required',
'password' => 'required',
];
}
I have no idea why this is happening

Validate Age Variable - Laravel RegisterController

I have added 3 fields to the Laravel OOB Registration Form, they are Birth Month, Day, and Year. I pass these fields to the validator function in the RegisterController and convert them to an age with Carbon:
$theAge = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;
This part works fine, I can pass the variable to a field in the table and see the correct age.
How do I add $theAge to my Validator?
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users|confirmed',
'password' => 'required|string|min:8|confirmed',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'address' => 'required|string|max:255',
'city' => 'required|string|max:255',
'state' => 'required|string|max:2',
'zipcode' => 'required|string|max:10',
'brand' => 'required',
'opt_in' => 'required',
'g-recaptcha-response' => 'required|captcha',
'birthmonth' => 'required',
'birthday' => 'required',
'birthyear' => 'required',
]);
I have tried the following but it appears to be ignored on validation:
$theAge => 'bail|min:21'
I have looked into the After Validation Hook but don't understand how to use it in my situation.
you can add the $theAge variable to the data array.
$data['age'] = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;
You can put the calculated value back in the $data before you call the validator like this:
$theAge = Carbon::createFromDate($data['birthyear'], $data['birthmonth'], $data['birthday'])->age;
$data['age'] = $theAge;
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users|confirmed',
'password' => 'required|string|min:8|confirmed',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'address' => 'required|string|max:255',
'city' => 'required|string|max:255',
'state' => 'required|string|max:2',
'zipcode' => 'required|string|max:10',
'brand' => 'required',
'opt_in' => 'required',
'g-recaptcha-response' => 'required|captcha',
'birthmonth' => 'required',
'birthday' => 'required',
'birthyear' => 'required',
'age' => 'min:21'
]);
Alternatively, you can let the user select their date of birth using date picker (e.g. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date) like this:
<input name="birthday" type="date">
and in your validator, do this define the age check plus a custom error message:
return Validator::make($data, [
// ... snipped
'birthday' => 'required|date|before_or_equal:' . Carbon::now()->subYears(21)->toDateString()
], [
'birthday.before_or_equal' => 'You must be at least 21 years old.'
]);

laravel validate unique fields on update

I am using the L5 repository and it has the validator package (https://github.com/andersao/laravel-validator) but I am have problems to do the validation of the unique fields on update it, anyone to help me???
******the example bellow I tried in this way on RULE_UPDATE but no success..
((((((FIELDS I WANT TO VALIDATE : people_id, email BECAUSE THESE ARE UNIQUE ONLY FOR REST OF THE USERS, NOT TO THIS CURRENT USER THAT ITS UPDATING )))))))
calling the validation in the UserService.php:
use Prettus\Validator\Contracts\ValidatorInterface;
public __construct(){
$this->validator = \App::make('App\Validators\UserValidator');
}
save($data){
if(!empty($data['id'])){
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_UPDATE);
}else{
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
}
}
namespace App\Validators;
use \Prettus\Validator\Contracts\ValidatorInterface;
use \Prettus\Validator\LaravelValidator;
class UserValidator extends LaravelValidator
{
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'people_id' => 'required|unique:users',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'masters_id' => 'required',
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'people_id' => 'required|unique:users,id,:id',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users,id,:id',
//'password' => 'required|string|min:6|confirmed',
//'masters_id' => 'required',
],
];
protected $messages = [
'id.required' => 'Usuário não encontrado!',
'people_id.required' => 'Pessoa é obrigatório',
'people_id.unique' => 'Pessoa já cadastrada',
'active.required' => 'Obrigatório',
'available_chat.required' => 'Obrigatório',
'email.required' => 'Digite o e-mail',
'password.required' => 'Digite a senha',
'password.min' => 'Digite uma senha com 6 caracteres',
'password.confirmed' => 'Confirme a senha corretamente',
'email.unique' => 'E-mail já cadastrado',
];
}
Try to put the id of the register in method setId
$this->validator->with($data)->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);
While updating you need to force a unique rule to Ignore Given ID
'people_id' => 'required|user,people_id,'.$id
//id is the primary id of the field which you want to update
with unique validation which must be ignored
https://laravel.com/docs/5.2/validation#rule-unique
Try to use the below changes it will work.
Add below code in your Validator for check Unique Email validation
ValidatorInterface::RULE_UPDATE => [
'email' => 'required|unique:customers,email,id'
],
After that set id for validation code like this
$this->validator->with($request->all())->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);

Resources