How to increment a value in the database
October 26, 2018
You can just use the ::increment
methods to 'plus one' a value. You can also send how many to increment in the 2nd param.
<?php
\App\User::findOrFail($user_id)->increment("profile_view_count");
// or to increment by 5
\App\User::findOrFail($user_id)->increment("profile_score_count",5);
You can also of course use the ::decrement method too.
If you use this as part of the query builder you will face some problems chaining this. It will return an int, not the query builder object. You have to do it like this:
<?php
$query = \App\User::where("id",1);
$query->decrement("profile_view_count",5);
$query->increment("profile_rating",1);
// this will result in an error:
\App\User::where("id",1)->decrement("profile_view_count",5)->increment("profile_rating",1);
//although you could do it with just one:
$num = \App\User::where("id",1)->decrement("profile_view_count",5);