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 install and use optipng on Linux CentOS

How to return JSON data to the user in Laravel?

How to replace values in a string, in JS

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

An overview of every main PHP array function

What is the difference between integration and unit tests?

How to increment a value in the database

How to exclude URLs from the Laravel CSRF protection?

How to make Apache force download of files (in .htaccess)

301 Redirect a single URL in .htaccess to a new location