Laravel increment column and Update Records

Laravel increment column and Update Records

Posted on:September 9, 2019 at 10:00 AM

Today I saw a code where the programmer wants to update a laravel model at the same time, he wants to increment a column’s value. Today, I will show you the easiest way how to increment column and update Laravel records.

Just imagine that we have a table called posts, that’s structure is like that-

posts

- id
- title
- body
- visits

Now, for some reason, you may want to update the visits column of the post only where id is 1. There are a few ways to do that.

Way 1

$posts = App\Post::where('id', 1)->update([
	'visits' => \DB::raw('visits+1')
]);

Way 2

Besides that, you can use increment() function too.

$posts = App\Post::where('id', 1)->increment('visits', 1);

Isn’t that easier?

Now, what if you want to find more than 1 post and try to update the visits column? You can apply either one style from above for updating more than 1 record.

For example-

$posts = App\Post::whereIn('id', [1,2,3,4,5])->increment('visits', 1);

Or

$posts = App\Post::whereIn('id', [1,2,3,4,5])->update([
	'visits' => \DB::raw('visits+1')
]);

Thanks.