How to Increment and Decrement a Column Value in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hey Folks,

In this tutorial, you will learn how to increment a column value in laravel. I would like to share with you increment by update field in laravel. I would like to share with you laravel decrement value from column example. let’s discuss about how to increment and decrement value on column in laravel. Here, Create a basic example of table fields increment in laravel.

Whenever you need to increment or decrement value of column in database, then you do not need to first fetch that record and then update, so that way we will make long code and very hard code, so basically you can increment and decrement by using increment() and decrement() statement of laravel query builder.

If you want to increment or decrement operation using update() method of laravel query builder then you also do that, in following example i am showing you how to increment and decrement value of column in table by using increment(), decrement() and update().

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Example 1: Laravel Eloquent Increment Column Value

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

/* Example 1 */

Post::find(1)->increment('visitors');

/* Example 2 */

$post = Post::find(1);

$post->visitors = $post->visitors + 1;

$post->save();

}

}

Example 2: Laravel Eloquent Decrement Column Value

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

/* Example 1 */

Post::find(1)->decrement('visitors');

/* Example 2 */

$post = Post::find(1);

$post->visitors = $post->visitors - 1;

$post->save();

}

}

I hope it can help you...

Tags :
Shares