Spacex
Spacex

Reputation: 37

How to add a specific attribute to a model while saving a new instance of it

Lets say I have a User model :

$user= User::first();
$user->name = 'name';
$user->miles = 10;
$user->save();

Say the existing user has 2 miles already in store without using UPDATE I want to add the new 10 miles to the 2 so it will be 12 miles !

Is there any way to do this using mutators maybe ?

Upvotes: 0

Views: 73

Answers (3)

Wahyu Fadzar
Wahyu Fadzar

Reputation: 126

try this :

$plusMiles = 10;
$user = User::find($id);
$user->miles = $user->miles + $plusMiles;
$user->save();

Upvotes: 0

parker_codes
parker_codes

Reputation: 3397

$user->miles += 10;
$user->save();

Alternatively, you can do:

$user->increment('miles', 10);

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50787

You can't really use an observer because you won't have the dirty and fresh copies of the model at the same time, but you can just determine whether or not the user has miles on it given the current model attributes, and react accordingly

$default = 2;
$additional = 10;
$user->miles = is_null($user->miles) ? $default : $user->miles + $additional

In this care those (arbitrary) variables, will dictate how the calculation is performed.

Upvotes: 1

Related Questions