Laravel Version: 5.4.27
PHP Version: 7.1.3
Description
I am trying to upload an optional image to the back-end and am validating the image if it is uploaded.
I am using the following rule:'channelImage' => 'nullable|image',
I even tried replacing nullable with sometimes but to no avail. I used sometimes and nullable together, but that didn't work either.
Steps To Reproduce:
validator([
'image' => null
], [
'image' => 'nullable|image'
])->validate();
The above works fine and no validation errors are provided.
Please ask on the forums, this repo is for bug reporting only. You can use https://laracasts.com/discuss or https://laravel.io/forum which are forums with a very large community of developers helping each other.
I was suffering this problem also, but I figured it out by sniffing $this->request->all() inside the validation rules function:
public function rules(): array
{
\Log::debug($this->request->all());
return [
'logo' => 'nullable|image',
];
}
The problem for me was that JavaScript was setting logo to undefined which Laravel is for some reason converting into Strings.
The solution for me was to set the image field to '' (empty String) for its default/reset state. This causes Laravel to interpret it correctly as NULL in the request payload.
So my suggestion is to check to make sure your controller isn't receiving a string called 'undefined' or 'null'. Instead, send an empty String.
[edit] The '' solution works to allow nullable|image rule combo to work, but it is causing other issues in my code related to prop types in the Buefy input, so I am now sending an empty Array instead: []. This is also interpreted as NULL by Laravel.
agm1984 you, rock man, you save me the headache.
Most helpful comment
I was suffering this problem also, but I figured it out by sniffing
$this->request->all()inside the validation rules function:The problem for me was that JavaScript was setting
logotoundefinedwhich Laravel is for some reason converting into Strings.The solution for me was to set the image field to
''(empty String) for its default/reset state. This causes Laravel to interpret it correctly asNULLin the request payload.So my suggestion is to check to make sure your controller isn't receiving a string called
'undefined'or'null'. Instead, send an empty String.[edit] The
''solution works to allownullable|imagerule combo to work, but it is causing other issues in my code related to prop types in the Buefy input, so I am now sending an empty Array instead:[]. This is also interpreted asNULLby Laravel.