1
votes

I am trying to validate a model before saving it. Obviously if the model isn't valid, it shouldn't be saved to the database. When validation fails, it throws an exception and doesn't continue to save. This below works:

$question = new Question([...]);
$question->validate();
$question->save();

I have a problem with the answers() hasMany relationship. According to this answer I should be able to call add() on the relation object:

$question = new Question([...]);
$question->answers()->add(new Answer([...]));
$question->validate();
$question->save();

The above fails:

Call to undefined method Illuminate\Database\Query\Builder::add()

I thought the answers() function would return a HasMany relationship object, but it looks like I'm getting a builder instead. Why?

2
If answers is a relationship, you'll want to call $question->answers instead of $question->answers() (don't invoke the function). Make sure that you use the name of the function defining the relationship, and not the model name itself (it's ok if they're the same).Hypaethral

2 Answers

2
votes

answers() does return a HasMany object. However, because there is no add method on a HasMany object, Laravel resorts to PHP's __call magic method.

public function __call($method, $parameters)
{
    $result = call_user_func_array([$this->query, $method], $parameters);

    if ($result === $this->query) {
        return $this;
    }

    return $result;
}

The __call method gets the query instance and tries to call the add method on it. There is no add method on the query builder though, which is why you are getting that message.

Finally, the add method is part of Laravel's Eloquent Collection, not a part of HasMany. In order to get the Collection class, you need to drop the parenthesis (as shown in the answer provided in your link) and do this instead:

$question->answers->add(new Answer([...]));
0
votes

There's no add method. Use the save method:

$question->answers()->save(new Answer([]));