I am retrieving data from an API response and then save it to the database. There are some fields from the API response that I'd like to ignore when inserting to the database, because those fields do not exist in the table. I learned that it works by assigning the necessary fields to $fillable on the model, and this automatically ignores the fields, however it only works for Model::create($singleRowWithAttributesNotInTable)
which only inserts a single row, but I'd like to perform a bulk insert with multiple rows. Model::insert($multipleRowsWithAttributesNotInTable)
does the bulk insert however it ignores the $fillable variable and returns a Column not found
error.
Is there any way to do this, or do I have to loop through the API data and add Model::create()
inside the loop? Thank you!
According to these threads :
Laravel 5.2 Model $fillable gets ignored?
Laravel 4 mass assignment guarded not work
[Request] Allow Eloquent to save multiple records at once #1295
The Query Builder's method insert
is exist in Illuminate\\Database\\Query\\Builder
class not in Illuminate/Database/Eloquent/Model.php
.Which means that you are not using Eloquent model.
That's why the $fillable
attribute is not triggered.If you have any additional data in your array like ( _token
, _submit
, etc.. ) will cause your error.
You can make a workaround solution by filtering your array before calling insert
method using getFillable method to make sure that the inserted array doesn't have any additional values.
Note: if you have created_at
, updated_at
fields in your table and you are using insert
method , you have to add them into your array too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.