1

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?

1
  • 1
    If the condition doesn't meet then null will be returned. Commented Jun 1, 2018 at 20:48

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.