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?