I want to validate my input against the database, What i tried is,
$input = Input::all();
$notificationRules = Array(
'isReadAll' => 'required|boolean',
'visitedNotificationId' => 'required|exists:notification',
);
$runValidation = Validator::make($input, $validations);
but i need to check the existence only if isReadAll == false, Is there any option in laravel validations or do i need to create a custom one ?
What you want is the Conditionally Adding Rules section:
$runValidation->sometimes('visitedNotificationId', 'required|exists:notification', function($input)
{
return ( ! ($input->isReadAll));
});
Related
I am new to Laravel. I try to validate an array in Laravel 9.
for using a unique filter I have a problem.
at first, I try to use this way
$rules = [
'*.id' => 'integer|required',
'*.key' => 'string|unique.settings|max:255|required',
'*.value' => 'array|nullable|max:255',
];
For the Create method, this works, but for updating, the logic is wrong. I need to ignore the current field.
for the update, I try to use this way
private function update(): array
{
foreach ($this->request->all() as $keys => $values) {
// dd($values['id']);
$rules[$keys .'.id' ] = 'integer|required';
$rules[$keys .'.key'] = ['string|max:255|required', Rule::unique('settings', 'key')->ignore($values['id'])];
$rules[$keys .'.value'] = 'array|nullable|max:255';
}
// dd($rules);
return $rules;
}
I got this error
BadMethodCallException: Method Illuminate\Validation\Validator::validateString|max does not exist. in file /Users/mortezashabani/code/accounting/vendor/laravel/framework/src/Illuminate/Validation/Validator.php on line 1534
how can I validate an array in the update method in Laravel 9?
PS: without Rule::unique('settings','key')->ignore($values['id'])] all filter is works without any problem
hello you can try this code in your function
$validated = $request->validate([
'id' => 'required',
'key' => 'string|unique.settings|max:255|required',
'value' => 'array|nullable|max:255',
]);
I wanted to validate inputs from a GET request without using the
this->validate($request... or \Validator::make($request...
and prefer to do it like
$input = $request->validate([... rules ...]);
however since get requests doesn't have $request parameters how can I achieve it?
public function sampleGet($param1, $param2) {
// How can I pass the $param1 and $param to to validate?
$input = $request->validate([
'param1' => 'required',
'param2' => 'required
]);
}
You can do so and it will have same behavior as validate
validator($request->route()->parameters(), [
'param1' => 'required',
'param2' => 'required'
....
])->validate();
If you want all the route parameters you can get them as an array:
$request->route()->parameters()
Since you already have those parameters being passed to your method you can just build an array with them:
compact('param1', 'param2');
// or
['param1' => $param1, 'param2' => $param2];
You are not going to be using the validate method on the Request though, you will have to manually create a validator. Unless you want to merge this array into the request or create a new request with these as inputs.
There is nothing special about the validate method on a Controller or on a Request. They are all making a validator and validating the data the same way you would yourself.
When manually creating a validator you still have a validate method that will throw an exception, which would be the equivalent to what is happening on Request and the Controller with their validate methods.
Laravel 7.x Docs - Validation - Manualy Creating Validators - Automatic Redirection
You can do like that.
public function getData(Request $request)
{
try {
$input['route1'] = $request->route('route1');
$input['route2'] = $request->route('route2');
$valid = Validator::make($input, [
'route1' => 'required',
'route2' => 'required'
]);
} catch (\Throwable $th) {
echo "<pre>";print_r($th->__toString());die;
}
}
Or you can follow the below link for more info.
https://laravel.com/docs/7.x/validation#manually-creating-validators
I want to redirect a user to another page, if he enters duplicate data to 5 attributes (if duplicated only for 4 or less, he should not be redirected).
I'm trying to do it using laravel 5.1's built in Validator.
$failure = Validator::make($request->all(), [
'firstName' => 'unique:registrations',
'lastName' => 'unique:registrations',
'line1' => 'unique:registrations',
'city' => 'unique:registrations',
'country' => 'unique:registrations'
]);
how to write an if condition to execute if all of the 5 attributes above fail,
if ($failure->fails())
this code executes if at least one attribute fails. Please help me with a solution.
list($key,$messages) = array_divide($failure->errors()->toArray());
if($key == ['firstname','lastname','line1','city','country']){
//all has failed
}
$check = $failure->errors();
if ($check->has('firstName') && $check->has('lastName') && $check->has('line1') && $check->has('city') && $check->has('country')) {
return redirect('<path>');
}
this worked
If no matter what attributes are duplicated more suitable way:
if (count($failure->getMessageBag()) >= 4) {
return ...
}
If only for some fields, more beautiful way:
if($validator->getMessageBag()->has(['firstName', 'lastName', 'line1', 'city', 'country'])) {
return ...
}
You can use errors() or getMessageBag() - it's no matter :)
I have a custom validation rule, is_admin, that checks if a user is an administrator.
Does Laravel have an "opposite" operator (like how ! works in PHP), such that I can do something like not:is_admin, which would check that the user isn't an admin:
$rules = array(
'user_id' => 'required|numeric|not:is_admin'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
// return error
}
else
{
// continue
}
Thanks.
Yes we can by using conditional statements on rules array.
$rules is an array that we pass to validation class or define in Request class.
Example #1:
public function rules{
//here we return an array of rules like shown below.
return [
'field_a' => 'required',
'field_b' => 'required',
];
//we can add any operator by a little change.
save validation rules array in variable like shown below.
$rules = [
'field_a' => 'required',
'field_b' => 'required',
];
//now we can add any rule in $rules array using common ways of writing conditional statements.
//For example field_c is required only when field_a is present and field_b is not
if(isset($this->field_a) && !isset($this->field_b)){
$rules['field_c' => 'required'];
}
//we can apply any kind of conditional statement and add or remove validation rules on the basis of our business logic.
}
Example#2
public function rules(){
$rules = [];
if ($this->attributes->has('some-key')) {
$rules['other-key'] = 'required|unique|etc';
}
if ($this->attributes->get('some-key') == 'some-value') {
$rules['my-key'] = 'in:a,b,c';
}
if ($this->attributes->get('some-key') == 'some-value') {
$this->attributes->set('key', 'value');
}
return $rules;
}
Yes, you can validate it through required_if:field,value.
You can check more details at http://laravel.com/docs/5.0/validation#rule-required-if
Or you can use not_in:foo,bar.
You can check more details at http://laravel.com/docs/5.0/validation#rule-not-in
I have an Ardent (Laravel 4) model with validation rules as below:
public static $rules = array(
'title' => 'required|alpha_num|min:4',
'friendly' => 'required|alpha_num|url'
);
When I try this:
$page = Page::find($id);
$page->menu=1;
$page->save();
It fails, because of the validation rules of other fields. My question is how can I update only one field as above?
Force save without validation in Laravel
If you want to force save your model without validation, simply use the forceSave() method instead of save().
$model->forceSave()
Adding "sometimes" worked in my case. Equivalent code for you would be:
public static $rules = array(
'title' => 'sometimes|required|alpha_num|min:4',
'friendly' => 'sometimes|required|alpha_num|url'
);
See: http://laravel.com/docs/4.2/validation#conditionally-adding-rules