0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting; technically the docs do specify to create a new Model prior to save. I figured $this->key would be overwritten each iteration so I wouldn't have to create a new model instance. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.