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

How to check if a (blade) view file exists

What is an example of an object literal?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

What is the null coalescing operator in PHP7?

How to return JSON data to the user in Laravel?

What is YAGNI?

How to check if a relation was loaded on an Eloquent model already?

When is __destruct called in PHP?

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess

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