John Doe
John Doe

Reputation: 171

Laravel PHP Traits with models

I have a PHP trait that I will use in any model that can do a certain set of actions. For example one of these actions is completion where completed_at is marked with a timestamp.

The trait method is:

/**
 * @return $this
 * @throws Exception
 */
public function markCompleted(){
    if($this->canDoAction('complete')){
        $this->completed_at = Carbon::now();
        return $this;
    }
}

In my controller I am calling this on a model that can do this action like below.

$app->markCompleted()->save();

The $app when I view its contents it is not null.

Running this command returns an error like

local.ERROR: Call to a member function save() on null

Wouldn't $this represent the model that uses this trait?

Upvotes: 1

Views: 946

Answers (2)

Turtle1363
Turtle1363

Reputation: 331

Another variation on what The Alpha said.

/**
 * @return $this
 * @throws Exception
 */
public function markCompleted(){
    if($this->canDoAction('complete')){
        $this->completed_at = Carbon::now();
    }
    return $this;
}

This way you always return a model, and you can chain other functions before the save is performed if you needed.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146269

If the condition doesn't meet then null will be returned, so instead of calling the save separately, do that inside that method, for example:

public function markCompleted()
{
    if ($this->canDoAction('complete')) {
        $this->completed_at = Carbon::now();
        return $this->save(); // true/false
    }
}

Then use it like:

$app->markCompleted();

The way way, you coded, the save method will be called even if the condition doesn't match and that's a side effect.

Upvotes: 0

Related Questions