Laravel: Deny empty PUT requests in validation - laravel

Laravel 5.3's $api->resource() routes map PUT requests to the controller's update method.
I fail to trigger a validation error when an empty HTTP PUT request is made. My $this->validate() rules are all optional, since no field is required in an update.
But I'd really like to let validation fail if the request is empty (count($request->all() == 0).
Is there a way to do that with the in-built validation rules?
A validation rule of '*' => 'min:1' does not work.

I did not find a working in-built rule, so I registered a custom rule:
\Illuminate\Support\Facades\Validator::extendImplicit(
'requestnotempty',
function($attribute, $value, $parameters, $validator) {
return count($validator->getData()) !== 0;
}
);
Then I used it:
$this->validate(
$request,
[
'' => 'requestnotempty',
//...
]
);

Related

Use `trans_choice()` in request validation messages with validation rule parameter

I need a request validation rule to return a custom message upon failure, and since the field being validating is an array with a min:x rule i'd like to have a custom message for both singular and plural variations.
I'm just wondering how to pass to the trans_choice() function the :min parameter from the validation rule:
Translation file:
'array' => [
'field' => [
'min' => 'You need to select at least one item.|you need to select at least :min items',
],
],
Request message() method:
public function messages() {
'my.array.field.min' => trans_choice('translations::array.field.min', ???),
}
It seems like there's nothing built into Laravel to use trans_choice whenever you can pluralise a translation string.
A way you could solve that is by temporarily (or permanently, whatever fits your use-case) changing the replacer for the min rule to something like this:
Validator::replacer('min', function ($message, $attribute, $rule, $parameters, $validator) {
$minValue = $parameters[0];
$message = Str::contains($message, '|')
? trans_choice($message, $minValue)
: $message;
return str_replace(':min', $minValue, $message);
});
Or by extending the Validator factory to work in your favour, but since that requires you to change many of it's methods I don't really recommend that.

Data validation in Laravel is not working

I've created a custom request in my project, but somehow it is not working. I'm facing two errors. I'm trying to show a message on view if validation fails through Ajax.
1) 422 Unprocessable Entity error
and
2) Undefined variable: teacherrequest
validation rules which i set in Request folder,
TeacherRequest.php:
public function rules()
{
return [
'Name' => 'required|regex:/^[\pL\s\-]+$/u',
'FName' => 'required|regex:/^[\pL\s\-]+$/u',
];
}
Controller:
public function update(TeacherRequest $request, $id)
{
if ($teacherrequest->fails()) {
return response()->json([
'msg' => 'Please Enter Correct Data',
]);
}
}
AJAX:
success: function (data) {
if(data.msg){
alert("please validate data");
}
}
Update:
if i remove if condition, i am getting 422 error, how to show that on view?
First, public function update(TeacherRequest $request) so in the function you need to use $request not $teacherrequest.
And second You need to have public function authorize() returning true.
You define TeacherRequest as $request TeacherRequest $request
but in next line use it as
if ($teacherrequest->fails()){ // this is wrong
correct one should be define like this
TeacherRequest $teacherrequest
or if you didn't change the dependency injection, just change the validator like this
if ($request->fails()){
summary: why error happened already specifically explained which is undefined teacherrequest variable, therefore 2 solutions above can solve it
If you type hint your request class as a parameter in your controller's action method (like you are doing in the example above) Laravel will automatically run your validation rules and return a 422 Unprocessable Entity if validation fails. You don't need to manually check if validation fails like you're doing above; in your controller's update method you can just implement the logic you want to run when validation passes.
Also on your front end you will need to use the error ajax callback to display the error message because a 422 status code is not considered successful.
See the documentation on creating form requests.
So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic.

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.3 set second attribute name in custom validation rule

I have the following custom validation rule...
Validator::extend('empty_with', function ($attribute, $value, $parameters, $validator) {
$other = array_get($validator->getData(), $parameters[0], null);
return ($value != '' && $other != '') ? false : true;
}, "The :attribute field is not required with the :other field.");
And am using it like...
$validator = Validator::make($request->all(), [
'officer' => 'sometimes|integer',
'station' => 'empty_with:officer,|integer',
]);
The current error message am getting is
The station field is not required with the:otherfield.
Versus what I would like to have;
The station field is not required with the officer field.
How do I set a the second parameter 'officer' in the error message, the same way :attribute is...??
You'll need to add in a custom replacer to go with your custom validation rule. See 'Defining the error message' here.
\Validator::replacer('empty_with', function ($message, $attribute, $rule, $parameters) {
return str_replace(':other', $parameters[0], $message);
});
This code tells Laravel that when the empty_with rule fails, the message should be run through that closure before being passed back to the user. The closure performs a simple string replacement and returns the amended error message.
For the most part, each validation rule has its own replacement rules for messages since it's dependent on the specific attributes and their order. Although :other being replaced with the first parameter happens for a few rules, it's not automatic and is defined explicitly for each rule that uses it. It's worth looking in the Illuminate\Validation\Concerns\ReplacesAttributes trait to get an idea of how Laravel deals with replacement for its built-in rules.

Laravel custom validation: only validate input if input given

So I followed this tutorial to learn how to upload images with Laravel using Vue: Image upload and validation using Laravel and VueJs
Everything works fine, but I want to make the image upload optional. Now the custom validation fails for the AppServiceProvider. if it does not have any input then i get this error
trying to access an attribute inside an array that does not exist. Undefined offset: 1
I could avoid the error by asking
if (request('image'))
In the controller and applying the validation for the other fields only if no image is given. However, this gets incredibly messy.
So I am looking for a way to get the custom validation rule working if there is no input. Or is that the wrong way?
Here is the custom validation rule:
public function boot()
{
Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
$type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
if (in_array($type, $parameters)) {
return true;
}
return false;
});
Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
return str_replace(':values',join(",",$parameters),$message);
});
}
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
In the example above, the email field will only be validated if it is present in the $data array.
Reference: Conditionally Adding Rules
Laravel provides a validation called 'nullable' in case other validation rules should not be run if the given value is null: A Note On Optional Fields

Resources