Let's say, my model has the following DB structure:
name:string
last_name:string
And I wish to update the model, with this $request->input()
array given:
name => 'Quinn',
last_name => 'Daley',
middle_name => 'Phill'
I would get an error message, because it would try to update the middle_name
field, which does not exist in the DB.
So here is my question:
How can I make it so only existing fields are updated? Without using the protected $fillable
property.
Edit: the reason I don't want to use $fillable is that I don't want to list all the existing fields from the database. What if I have a large model with 50 fields in it? Isn't there a possibility to only accept parameters that exist in the model DB from the $request->input()
?
UPDATE
There is a cleaner solution using $model->getAttributes()
:
$user->update($request->only(array_keys($user->getAttributes()))
This solution is also better if you are using a different $connection
for the model, which was my case.
Instead of using
input()
orall()
, you can use theonly()
orexcept()
methods on the request to limit the fields. For example:Edit
If you want to get the column names of the table, you can do this using
Schema::getColumnListing($tableName);
. So, in this case, your code would look something like:You can use fillable array in this way:
And filter data from
$request->input()
; Also you can make middleware for this perpose.protected $fillable will be required, if you are using create or update function. however, I think you solve it in this way without using the protected $fillable property.