How to increment a value in the database

Laravel: How to increment a value in the database

You can just use the ::increment methods to 'plus one' a value. You can also send how many to increment in the 2nd param.

  1. \App\User::findOrFail($user_id)->increment("profile_view_count");
  2. // or to increment by 5
  3. \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:

  1. $query = \App\User::where("id",1);
  2.  
  3. $query->decrement("profile_view_count",5);
  4. $query->increment("profile_rating",1);
  5.  
  6.  
  7. // this will result in an error:
  8.  \App\User::where("id",1)->decrement("profile_view_count",5)->increment("profile_rating",1);
  9.  
  10.  //although you could do it with just one:
  11.  $num = \App\User::where("id",1)->decrement("profile_view_count",5);

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to increment a value in the database

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

PHP Date commonly used formats

What does PEAR stand for?

How to round a number in JS?

What is an example of an object literal?

How to add comments in PHP

How do you run a PHP script from the command line?

How to find the intersection (same values) from two arrays?

How to output (echo/print) content in PHP

How to find out which php.ini file PHP is using?

How to block IPv6 IP addresses in .htaccess