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;
I get error using the trait Trait "app\Models\Traits\HasOwnership" not found
Have you imported the namespace correctly?
Here's a few things to check:
If you could, please add your code examples of these things - we'll double check for you, maybe there is a typo somewhere :)
Now it's working. By mistake I put "app" instead of "App". Thanks for the quick reply! one small typo killed almost an hour