Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

Laravel Eloquent: Repeating Relationships Reusable in Traits

August 12, 2023
1 min read

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;

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

J
justgkp ✓ Link copied!

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

M
Modestas ✓ Link copied!

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 :)

J
justgkp ✓ Link copied!

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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.