Laravel 5.6 Validation on empty fields

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Laravel 5.6 Validation on empty fields



Somehow I feel like this should be a common question, but I can't seem to find a definite answer on that one.



The problem is quite simple:
On validating a form, I would like to exclude the empty non-required fields from the resulting array - and this in order to use the default value set at database level.



Since Laravel is using the ConvertEmptyStringsToNull middleware by default (and I am not so keen on changing that), it means that my empty fields will be converted to 'null' and sent to my database (hence not getting their default value, and actually breaking the query since those fields are not nullable at database level).


$userData = $request->validate([
'email' => 'required|string|email|max:255|unique:users',
'number_of_whatever' => //if this field is empty, I want it stripped out the $userData array - or automatically default to the database default
]);



Any help on how to solve this in the cleanest way possible would be much appreciated! I was thinking about making a custom rule that would exclude the field itself (so I could reuse this validation rule across the project without having to manually do it every time we come across the situation).
Another option would be to set it at Model level - but not so keen on doing that, it seems weird to have to do it there when it's already done at DB level.



Thanks!









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

gy,p 9UNSyk
aKpkl7Mp13kzyXun6,xecVqC7WuKaPjwl

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results