laravel 'unique' validation property not working - validation

In my Laravel project, I have a form that receives as input name, email etc. and submits the values to a store method in my controller. I created a request to validated the submitted input before storing them in the datebase. Here are the the validation rules and custom messages:
public function rules(){
return [
'name' => 'required|unique:users|min:8',
'email' => 'required|email',
];
}
public function messages(){
return [
'name.required' => 'You must enter name',
'name.unique' => 'Sorry, that name is already taken',
'email.required' => 'An email address is required',
];
}
Ajax and every other part of the code (like the ajax, and laravel) works just fine without the unique validation proberty. But when I include the unique validation, the form does not submit but instead when I look at the developer tools I get the following error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
all_ajax.js:54 Uncaught TypeError: Cannot read property 'name' of undefined
Please what could I be doing wrong?
For the benefit of doubt let me just add the controller method

I believe the table users don't have a column name, you should specify the corresponding column of the table

Related

How can i Skip email Form unique Validation when update user data In Laravel

Hello Guys And Hi I Have This Validation Inside My Request
public function rules()
{
return [
'email' => 'required|email|unique:admins,email,' ,
'name' => 'required|unique:admins,name',
'code' => 'required|min:2|unique:admins,code',
'password' => 'required|min:8',
];
}
I want to ignore an email when updating data during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, I want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, I do not want a validation error to be thrown because the user is already the owner of the e-mail address. I only want to throw a validation error if the user provides an e-mail address that is already used by a different user.
I'm Fixing It I'm Passing The Id To The Request Like This
<input name='id' value="$item -> id" hidden >
and i write in Validation
'email' => 'required|email|unique:admins,email,' . $this -> id ,

Custom error message for `requiredIf` validation in laravel

I'm working on a Laravel 5.8 project and trying to show custom validation messages for a validation which uses the requiredIf validation rule.
Here is how I have it set up:
$validation = Validator::make(
$request->all(),
[
...
'sum' => [
Rule::requiredIf(function() use ($request){
$model = Model::find($request->id);
return $model->is_special; //returns a boolean value
}),
'numeric'
],
...
],
[
...
'sum.required_if' => 'This cannot be blank',
'sum.numeric' => 'Must use a number here',
...
]
);
Now the validation is working correctly and the custom message for the numeric validation shows as should, but the message I get for the requiredIf() method is Laravel's default error message.
I also tried using 'sum.requiredIf' => '...' but that didn't work either and can't seem to find any documentation or example for this scenario.
I was tinkering with this for a while and noticed that for this to work I needed to define
'sum.required' => 'This cannot be blank'
and not 'sum.required_if' => 'This cannot be blank',.
Not sure if this is expected behavior or just a workaround but my deduction is that with the callback Rule::requiredIf(function() use ($request){...}) the parameters :other and :value are not passed so it falls back onto required messaging and I guess this makes sense since required_if and required would not be used on the same :attribute.
Hope this helps anyone who comes across this problem.
First, create a rule name isSpecial or whatever
php artisan make:rule isSpecial
Go to App\Rules\isSpecial.php
private $id;
public function __construct($id) // pass id or what you need
{
//
$this->id=$id;
}
public function passes($attribute, $value) // customize your rules here
{
//
return Model::find($request->id)->is_special;
}
public function message() // here is answer for your question
{
return 'The validation error message.'; // your message
}
in your controller
use App\Rules\isSpecial;
\Validator::make($request->all(), [
'sum' => new isSpecial() ,
])->validate();
another idea :
Specifying Custom Messages In Language Files
In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.
'custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
],
Simple notice:
- I suggest using HTTP Requests instead use validation in your controller and function direct
Looks like as of Laravel 8, using required_if works as expected, and alternatively will not fall back on required as mentioned previously:
'sum.required_if' => 'This cannot be blank',

Laravel: Validate input only if available in DOM

I created a form with the following fields:
Name
Email
Country
City
Address
If the user selects a country that has states (ex. United States) then the form transforms to:
Name
Email
Country
State
City
Address
To validate this I created a separate form request like so:
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email,
'country_id' => 'required|integer',
'state_id' => 'nullable|integer',
'city_id' => 'required|integer',
'address' => 'required',
];
}
The problem is that if I leave it like that, then if I don't select a state it will pass validation.
If i make it:
'state_id' => 'sometimes|nullable|integer',
Then again it passes validation.
If I make it:
'state_id' => 'required|nullable|integer',
It will not pass validation, but then again it will throw a validation error if there is no state field in the form.
I read a lot of articles about this but nothing seems to solve it for me.
PS1: I want to solve this in the form request, not in the controller. I assume that an
if($request->has('states')){...}
can help, but then again, i would like to keep everything tidy in the form request.
PS2: I am using VueJS and Axios to add/remove states from the form. The whole form is actually a Vue component.
Any clues?
Thank you in advance!
You can conditionally add rules via the sometimes method on Validator.
$v->sometimes('state_id', 'required|integer', function ($input) {
return in_array($input->countries, [1,2,3,4...]
});
You could use the required_with line of parameters, but because the validation is based on the value of the input instead of just the presence, the custom validation rule is probably your best bet.
Per https://laravel.com/docs/5.7/validation#conditionally-adding-rules

Laravel Email validation message

I'm new to Laravel and trying to fix a email validation message. The scenario is:
If I send empty value, the validator returns a response "The User Email field is required".
If I send an invalid value like 'my_email_id' [ without # sign ], it still returns "The User Email field is required".
If I send empty value like 'my_email_id#domain', it still returns "The User Email must be a valid email address.".
Now, my question is how can I return the response "The User Email must be a valid email address." for Case 2 as well? Is there any way or is it just how Laravel does it by default?
Thanks.
You should make it with your custom validation message like this :
$rules = array(
'email'=>'required|email|unique:users'
);
$messsages = array(
'email.required'=>'The User Email must be a valid email address'
);
$validator = Validator::make(Input::all(), $rules, $messsages);
Laravel has a built-in validation for email addresses, and it just so happens that the examples directly solve your specific needs too.
You will need to look into using the email validator and adding custom error messages, both are documented in detail in the linked documentation.
However, I've gone ahead and combined the two solutions directly from the linked resource to solve your needs:
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
], [
'email.required' => 'The User Email must be a valid email address.'
)];

Validate field as unique with scope in cakephp

I am creating a CakePHP application which have an edit form which contain one text box named air_id. In my table I am using project_id and air_id as composite primary key. So while updating air_id I need to validate uniqueness.
My table structure is like:
project_id air_id
1 test#test.com
1 test1#test.com
Currently I am using cakephp3.0 and I am using validateUnique rule with scope,
Following is my code:
$validator
->add('air_id', [
'unique' => [
'rule' => ['validateUnique', ['scope' => 'project_id']],
'provider' => 'table',
]
]);
And my controller is like this
$projectCustomers = $this->ProjectCustomers->newEntity($formData);
Now it is giving validation message every time. What I need is when I change the value test#test.com to test1#test.com it should raise the error and if I change it to some other value it should not raise the error. Is there something wrong in my validation?
CakePHP Unique Field Rules:
We have cakephp unique field rules that might be even better:
In your table(eg. UsersTable.php):
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(
['air_id', 'project_id'],
'Your validation error here.'
));
return $rules;
}
At the top of your table , don't forget to include this class:
use Cake\ORM\RulesChecker;
See Here (CakePHP Unique Fields Rules).

Resources