dantreacy's avatar

Models & Objects

OK it may be because it's late and it's been a long day but I'm having a real brain snap about this.

I'm updating some legacy code and it's (going to be) using Eloquent.

The code I'm updating at the moment is very procedural and function based and the refactoring is going slowly.

The user completes a task and earns some points

so I grab myself the user

$user = User::find($id)

work out how many point they deserve and it's come time where I have to add a reward to the users account.

So naturally my first though is

$user->addReward($reward) 

all good until I go to the User model and have a complete brain spasm regarding how to go about it.

in the User Model and I'm sitting there staring at it working out how I'm supposed to do this

public function addReward($reward) 
{
    \\ new points = points + reward
    $this->points =+ $reward
}

Then I'm doubting myself as to whether this is going to be referencing the right model and updating the correct user and then it's all downhill from there.

It's simple enough to pass through the userid and make sure but for whatever reason it doesn't feel right.. I've already grabbed the user now all I need to do is update their points..

shakes head I think I should just go to bed and try it again when I'm awake..

0 likes
3 replies
phildawson's avatar
Level 26

@tenyardtech

Then I'm doubting myself as to whether this is going to be referencing the right model and updating the correct user and then it's all downhill from there.

Yes it's all fine. $this is acting on the User object representing that user row. It's just affecting that.

I'd get some sleep though, if you think you need sleep, then you def need it.

class User extends Model
{
    function addReward($reward)
    {
        $this->points += $reward;
    }
}

$user = User::find(1);
$user->addReward(10);
$user->save();

the only mistake is its += for the combined operator

martinbean's avatar

@tenyardtech If you’re just incrementing a column value, then you can use the aptly-named increment() method:

public function addPoints($amount)
{
    return $this->increment('points', $amount);
}

If you’re adding points then I’d name the method such rather than flipping between ‘points’ and ‘rewards’. Different terms for the same thing will just lead to confusion between you and team members, as writing good code is already complicated enough ;)

In terms of your question, $this will refer to the user you’ve fetched. So if you fetch a user with an ID of 10 like this:

$user = User::find(10);

Then any operations using $this (including the example above) will act on that particular user.

dantreacy's avatar

Thanks guys,

Nice to have a sanity check every now and then.

Sleep achievement unlocked and it's onward from here.

Please or to participate in this conversation.