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 namespace a Laravel route group?

How could you include a custom function for every single time PHP runs?

How to get the last character of a string in JS?

How to check if a object has a static variable defined?

What are the SPL Iterators in PHP?

What does 'final class' and 'final function' (final method) mean in PHP?

What is the difference between var, let and const in Javascript?

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to check if an object or variable is an array, in JS?

What are Template literals (Template strings) in JS?