I'm getting data through a classic submitted form but for some reason I don't get all the input's data in request and it only updates the received ones.
Model::find($id)->update($request->all());
This is a bit problematic because I have multiple nullable fields in my database and sometimes I want to pass empty fields (i.e when a user clear an input then submit the form)
Do you know a way to pass empty fields to the Request as well?
The thing is, Laravel transforms the
''
values tonull
by default through the ConvertEmptyStringsToNull middleware. Check your Kernel:app/Http/Kernel.php
This middleware do the following:
As you can see, if the given attribute has a value
''
it will be transformed tonull
.So, to avoid this you could just comment that middleware in the Kernel file. But be aware of this, because this will be applied to your entire application.
Input Trimming & Normalization
Laravel version > 5.4 already has these features included:
For versions < 5.4: make a new middleware with following code:
and assign it to the routes or controller's methods you want it to take place:
REMEMBER:
create()
,update()
, etc. methods work on fields in$fillable
array in your model:Or if you want to exclude some fields and include rest, use
$guarded
array instead:If your field is not in the
$fillable
array in "Model" class, theupdate()
method will not work for that field!!!Reference: Mass Assignment
Somehow I managed to make it work: on my web application I have disabled ConvertEmptyStringsToNull middleware (commented it) so when I log the
$request
I get empty values''
and on the API,$request
logsnull
value for each field.You can use php
array_merge()
like with this code as i use thator test this code: