Alex Lomia
Alex Lomia

Reputation: 7235

How to perform mass update using eloquent?

I have a model Post and want to bulk-update it's records. I'm aware of this method:

Post::where('id', '>', '10')->update(...)

But I need to increment the times_seen property of the records. In other words, I need to increase the value of times_seen property by 1, for each record matching a where(...) conditional. For example:

Post::where('id', '>', '10')->update(['times_seen', ?]) // '?' = 'times_seen + 1'

How should I do this?

Upvotes: 1

Views: 620

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

Try the increment() method of the query builder:

Post::where('id', '>', 10)->increment('times_seen');

If you need to increment it by more than one, you can pass the exact value as second parameter:

Post::where('id', '>', 10)->increment('times_seen', 5);

Upvotes: 3

Related Questions