Error Validator.php line 3162 in laravel 5.2 - laravel

BadMethodCallException in Validator.php line 3162: Method [validateThisFieldIsRequired] does not exist.
When I dont't provide data to the field than it is inserted successfully, but I provide data to the field than it shows error.
In model:
public static $rules = [
'name' => 'this field is required'
];
In repository:
public function rules()
{
return State::$rules;
}

The problem is that you're passing a message as the field rule instead of an actual rule. So your rule should be the following:
public static $rules = [
'name' => 'required'
];
As shown in the Laravel Validation Documentation a rule is an array of key value pair, where the key is the name of the field that will be validated and the value is the validation rule. So in your cause the field is name and the validation rule is required.
If you want to modify the rule validation messages from the default ones found in lang/en/validation.php, you can read about it the Custom Error Messages section of the documentation.

Related

Making Laravel 9 validation rule that is unique on 2 columns

I am trying to update a row in the pages table.
The slug must be unique in the pages table on the slug and app_id field combined.
i.e. there can be multiple slugs entitled 'this-is-my-slug' but they must have unique app_id.
Therefore I have found that formula for the unique rule is:
unique:table,column,except,idColumn,extraColumn,extraColumnValue
I have an update method and getValidationRules method.
public function update($resource,$id,$request){
$app_id=22;
$request->validate(
$this->getValidationRules($id,$app_id)
);
// ...store
}
When I test for just a unique slug the following works:
public function getValidationRules($id,$app_id){
return [
'title'=> 'required',
'slug'=> 'required|unique:pages,slug,'.$id
];
}
However, when I try and add the app_id into the validation rules it returns server error.
public function getValidationRules($id,$app_id){
return [
'title'=> 'required',
'slug'=> 'required|unique:pages,slug,'.$id.',app_id,'.$app_id
];
}
I have also tried to use the Rule facade, but that also returns server error. Infact I can't even get that working for just the ignore id!
public function getValidationRules($id,$app_id){
return [
'title'=> 'required',
'slug'=> [Rule::unique('pages','slug')->where('app_id',$app_id)->ignore($id)]
];
}
Any help is much appreciated :)
Thanks for the respsonses. It turned out a couple of things were wrong.
Firstly if you want to use the Rule facade for the validation rules, make sure you've included it:
use Illuminate\Validation\Rule;
The other method for defining the validation rule seems to be limited to the following pattern:
unique:table,column,except,idColumn
The blog post that I read that showed you could add additional columns was for laravel 7, so i guess that is no longer the case for laravel 9.
Thanks for your responses and help in the chat!
I recommend you to add your own custom rule.
First run artisan make:rule SlugWithUniqueAppIdRule
This will create new file/class inside App\Rules called SlugWIthUniqueAppRule.php.
Next inside, lets add your custom rule and message when error occured.
public function passes($attribute, $value)
{
// I assume you use model Page for table pages
$app_id = request()->id;
$pageExists = Page::query()
->where('slug', $slug)
->where('app_id', $app_id)
->exists();
return !$pageExists;
}
public function message()
{
return 'The slug must have unique app id.';
}
Than you can use it inside your validation.
return [
'title'=> 'required|string',
'slug' => new SlugWithUniqueAppIdRule(),
];
You can try it again and adjust this custom rule according to your needs.
Bonus:
I recommend to move your form request into separate class.
Run artisan make:request UpdateSlugAppRequest
And check this newly made file in App\Http\Requests.
This request class by default will consists of 2 public methods : authorize() and rules().
Change authorize to return true, or otherwise this route can not be accessed.
Move your rules array from controller into rules().
public function rules()
{
return [
'title'=> 'required|string',
'slug' => new SlugWithUniqueAppIdRule(),
];
}
To use it inside your controller:
public function update(UpdateSlugAppRequest $request, $resource, $id){
// this will return validated inputs in array format
$validated = $request->validated();
// ...store process , move to a ServiceClass
}
This will make your controller a lot slimmer.

Laravel validation rules - how optional, but only if another condition is true

How can I make a custom rule using Validation, so that the field can be nullable 'since' call function the result is true, otherwise, the field becomes required.
Of course I tried to use the 'nullable', but even if the field is empty, the Validation should execute the checkAreasDiff() function to validate that the field can be empty during the update.
In my controller, I created a function:
private function validator_update(array $data) {
\Validator::extend('areas_diff', function($attribute, $value, $parameters, $validator) {
return checkAreasDiff();
}, 'VALIDATOR AREAS_DIFF OK.');
/**
* RULES
*/
$rules = [
'fiscalizoarea' => 'areas_diff',
];
/**
* Return \Validator
*/
return \Validator::make($data, $rules, $msgs);
}
If I understand the question correctly, you want one field to be required only if another is not null?
There is a Laravel rule for that already: required_with.
required_with:foo,bar,...
The field under validation must be present and not empty only if any
of the other specified fields are present.
Or, if I'm getting your logic back to front: required_without
required_without:foo,bar,...
The field under validation must be present and not empty only when any
of the other specified fields are not present.

Laravel 5.5 - Include Find function inside Validation Rule

I am using validation in an Laravel 5.5 controller like this...
$membership = Membership::find($request->input('membership_id'));
/* Validation Rules */
$rules = [
'key' => [
'required',
Rule::in([$membership->key]),
],
];
This works correctly if membership_id is provided, but if not then it with error....
Trying to get property of non-object
Is there a way I can include the Membership:find function inside of the validation Rule instead so that is respects the require validation?
Use the optional() helper to avoid the "Trying to get property of non-object" error:
Rule::in([optional($membership)->key]),
So, if membership will not be found, null will be returned and a user will be redirected back with validation error message.

YII2 validation check unique between two fields without using active record

I am using two fields "old_password" and "new_password". I want the error message if value in both fields are same.
I am not using Activerecords.
I tried in model :
['a1', 'unique', 'targetAttribute' => 'a2']
but above code will work only for active record.
How can i get error message without using active record ?
You need to use compare validator instead of unique.
['new_password', 'compare', 'compareAttribute' => 'old_password', 'operator' => '!='],
Because unique validator validates that the attribute value is unique across the table
If your model extend yii\base\Model, activeRecerd are not necessary and you can use the rules function
public function rules()
{
return [
['a1', 'unique', 'targetAttribute' => 'a2'],
];
}
for assign your validation rules
and in your controller you can perform validation invoking $model->validation
$model = new \app\models\YourForm();
like suggested in Yii2 guide for validating input
// populate model attributes with user inputs
$model->load(\Yii::$app->request->post());
// which is equivalent to the following:
// $model->attributes = \Yii::$app->request->post('ContactForm');
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}

Validate only if the field is entered in Laravel 5.2

public function rules() {
return [
'num_of_devices' => 'integer'
];
}
I want to validate an integer field if and only if the field is entered. But above rule validates it for integer even if the field is empty. I used somtimes, but no result. But when I var_dump($num_of_devices) it is string.I am using Laravel 5.2. I think It was working fine in 5.1.
From version 5.3 you can use nullable
public function rules() {
return [
'num_of_devices' => 'nullable | integer'
];
}
Add a rule to array, if input is not empty. You could collect all your validation rules to $rules array and then return the array.
if( !empty(Input::get('num_of_devices')) ){
$rules['num_of_devices'] = 'integer';
}
You’re looking for the sometimes validation rule. From the documentation:
…run validation checks against a field only if that field is present in the input array.

Resources