Reputation: 3108
I recently upgraded to laravel 5.4 (from 5.2) to make use of the nullable
validation rule.
I have a field act_post_code
which can be either an integer
OR null
. So I provided the following rule in my Request
class.
'act_post_code' => 'integer|nullable'
In Postman using form-data
, I provide a key = act_post_code
with its value = null
.
The response I get is the following:
{
"act_post_code": [
"The act post code must be an integer."
]
}
Upvotes: 6
Views: 9194
Reputation: 144
One can die and dump request parameters and check whether the actual value is null or "null" (in string). Sometimes when submitting a form via javascript we use FormData() to append data to the form, in those scenarios it may send a null value as in string type "null"
array:5 [
"firstName" => "Kaustubh"
"middleName" => "null" // null as string
"lastName" => "Bagwe"
"contactNumber" => null // null value
"photo" => null
"_method" => "PUT"
]
Upvotes: 2
Reputation: 5168
Unfortunately, it seems that nullable
is only valid with certain other validations.
For example: 'act_post_code' => 'nullable|integer'
will give you the error: "validation.integer"
However, 'act_post_code' => 'nullable|date'
works fine.
As a work around for these validations, you can make them dynamic. For example, before the validator:
$act_post_code_rules = $request->act_post_code ? 'integer' : '';
then, within the validate:
'act_post_code' => $act_post_code_rules
Upvotes: 7
Reputation: 417
After Some Test I found that nullable rule only work if only the data that we pass really was a null data.
so in my test case i use the validation rule like this :
"counter" => "nullable|numeric"
and in the blade file, I use Form::text('counter','')
as element to input my data.
Then i use it with few test case:
counter
data with a non-numeric value it will response with error: "the counter must be a number"
.counter
data with a numeric value it will pass the validation test.counter
it will pass the validation test.so i check the data manually using dd($request_data)
or if you using ajax just return $request_data
and print it using console.log("data")
like:
$.ajax({
type:'POST',
data:{_token:"{{ csrf_token() }}",
counter:$('input[name="counter"]').val()
},success:function(data){
console.log(data);
}
});
and found out that when input field is emptied it will give the null
value.
Upvotes: 1
Reputation: 19
In order to validate the field act_post_code
which can be either be of type integer or nullable, you can try out the following :
act_post_code
declare the column like $table->integer('act_post_code')->nullable();
'act_post_code' =>'sometimes|nullable|integer'
Upvotes: 2
Reputation: 1005
Open your migration file and make the this field as nullable
For e.g
Schema::create('your_table_name', function (Blueprint $table) {
$table->integer('act_post_code ')->nullable();
});
Make sure it is present in your model file in the fillable section
protected $fillable = ['act_post_code'];
Upvotes: 1