0
votes

I have a cron task in my Laravel 4 project that gets data from an API and stores it to the db using Eloquent. I need it to do this for every user stored in my users table. I figured I could iterate over each user, get the data and $this->save() it within my model. Only the last record is being added.

I did a simple test:

$this->user_id = 23;
$this->save();
$this->user_id = 43;
$this->save();

and still only the last entry is being added. Clearly I'm not using Eloquent properly or something. Should I not be using Eloquent?

1

1 Answers

2
votes

You're only updating your model ($this) each run of the loop, so only the last value will be shown.

You should create one record each time instead :

Model::create([
    "user_id" => 23
]);

Where Model is your Eloquent model.