In Laravel 5.6 an Illuminate\Database\Eloquent\Relations\BelongsTo
relation was given the ability to support default models. This allows a model that will be returned if the relationship is empty.
Most of the code for doing this lives in the Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels
trait, which the BelongsTo
relation uses.
Here's an example of a method in the relation calling the getDefaultFor
method from the trait:
/**
* Get the results of the relationship.
*
* @return mixed
*/
public function getResults()
{
return $this->query->first() ?: $this->getDefaultFor($this->parent);
}
The getDefaultFor
method only exists in the trait. It's not defined on the class itself. For some reason I was always under the impression that this is not 'proper'. In other words, if I were to remove the trait, the class would break. Shouldn't the class have some sort of fallback getDefaultFor
method defined on it that the trait can override?
I realize this is an extremely nitpicky question and doesn't really matter since the code works, but I am just trying to understand from a code design perspective if this is the proper way to do things.
Does anyone have any thoughts on this?