1

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!

ag16920
  • 41
  • 6
  • Your question is unclear. Also, what have you tried to achieve your wanted results? What has your research concerning your problem shown? Can you provide code of your tries? [How do I ask a good question](https://stackoverflow.com/help/how-to-ask) and {How much research effort is expected}(https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) might be helpful to improve your question. – Geshode Jan 11 '18 at 00:47
  • @Geshode please see edited post. I know that I can loop through the response data and check whether the field exists or not, but I just want to know if there's a faster, cleaner way to achieve this. – ag16920 Jan 11 '18 at 03:57
  • Can you provide the structure of $multipleRowsWithAttributesNotInTable? – wahdan Jan 11 '18 at 04:44

1 Answers1

0

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.

wahdan
  • 1,208
  • 3
  • 16
  • 26
  • 1
    It seems people are clamoring for an Eloquent bulk insert feature. Yes I filter the array by looping through it, I just thought there was a faster way to do it that I didn't know about. Thanks @wahdan! – ag16920 Jan 11 '18 at 15:33