directly increment or decrement number update from column using Laravel Eloquent
Asked Answered
J

2

5

I have a query where in I use Eloquent for finding the ID but what I need is to directly subtract inside the eloquent query ? same as in Query Builder,

Documentation code

$flight = App\Flight::find(1);

$flight->name = 'New Flight Name';

$flight->save();

What I need is to directly to substract

$flight = App\Flight::find(1);

$flight->value =- 1;

$flight->save();
Jordison answered 27/6, 2019 at 7:1 Comment(0)
R
8

use laravel increment() or decrement() method see

App\Flight::find(1)->decrement('value',1);

second way u can achieve by update query

 App\Flight::where('id', 1)->update(['value' => \DB::raw('value - 1')]);
Robins answered 27/6, 2019 at 7:4 Comment(0)
A
1

you need to do this

$flight = App\Flight::find(1);

$flight->value = $flight->value-1;

$flight->save();

hope it helps! :)

Armil answered 27/6, 2019 at 7:3 Comment(2)
Please add an explanation to improve the insight and give the OP some more informationLazaro
This option is suitable if you want to retrieve the updated row id. The accepted answer is more suitable and clean if you just want to update and not get the id.Preoccupied

© 2022 - 2024 — McMap. All rights reserved.