0

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?

1 Answer 1

4

Far from being an expert, but I had the same question in mind for a while as well. This is what I have gathered.

  • The generic (across languages) definition does emphasize that a trait can extend the functionality of a class. So if added to a class, the class indeed would not work without it.
  • There is no clear consensus on it in the community (for instance), even though it was a core addition to php 5+.
  • Just about every search package for Laravel is a trait and therefore the controller heavily depends on it without a fallback.
  • Laravel's own code often makes idiosyncratic uses of patterns, such as their Facades, but it's one of those cases of where the 800-pound elephant sits wherever it wants.

In my own code, I use traits for common operations, like string manipulation. Traits seem to be fancy ways to avoid copy and paste of functions that don't need classes.

Just my amateur opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.