Laravel Eloquent: Repeating Relationships Reusable in Traits

If multiple Eloquent models in your project have the same identical relationship methods, like createdBy(), for example, you may extract them in a reusable structure. We will show you an example with Traits.

The image below is a good example:

You can make relationships reusable by simply creating a Trait and adding it to your models:

app/Models/Traits/HasOwnership.php

namespace app\Models\Traits;
 
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
trait HasOwnership
{
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
 
public function updatedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'updated_by');
}
}

This allows you to add the trait to your models simply:

app/Models/Account.php

class Accounts extends Model
{
use HasOwnership;
 
// ...
}

app/Models/Company.php

class Company extends Model
{
use HasOwnership;
 
// ...
}

And so on. Then it gives you access to your relationships as you would expect:

$account = Account::first();
 
$account->createdBy;
$account->updatedBy;
avatar

I get error using the trait Trait "app\Models\Traits\HasOwnership" not found

avatar

Have you imported the namespace correctly?

Here's a few things to check:

  1. Namespace on the trait
  2. Import on the model you are using

If you could, please add your code examples of these things - we'll double check for you, maybe there is a typo somewhere :)

avatar

Now it's working. By mistake I put "app" instead of "App". Thanks for the quick reply! one small typo killed almost an hour

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials