Optimizing OOP with Laravel Traits: A Practical Relationship Guide

Ferdy Hahan Pradana
2 min readOct 2, 2024

Case Study

Imagine you’ve got a bunch of models like `Post`, `Comment`, and `Like`, and each of them needs to relate to a `User`. Writing the same relationship code again and again can be pretty annoying, right? 😩

Example Without Traits

// Post.php
public function user()
{
return $this->belongsTo(User::class);
}
// Comment.php
public function user()
{
return $this->belongsTo(User::class);
}
// Like.php
public function user()
{
return $this->belongsTo(User::class);
}

This repetition can become cumbersome, especially if you need to maintain consistency across many models. 😩

Example With Traits

Wouldn’t it be better if you could refactor this into a trait and reuse the relationship logic? 😍

// Post.php
use HasUser;
// Comment.php
use HasUser;
// Like.php
use HasUser;

Cleaner, right? Now, let’s break down how to implement this for better maintainability and readability.

Step-by-Step Guide

Create a Custom Command to Generate Traits (For Laravel Versions Below 11)

If you’re using Laravel under version 11, you can create a command to generate the trait. Run this command:

php artisan make:command CreateTraitCommand

Then, open the generated file in app/Console/Commands/CreateTraitCommand.php and add edit the code like this:

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class CreateTraitCommand extends Command
{

protected $signature = 'make:trait {name}';
protected $description = 'Create a new trait';
public function handle()
{
$name = $this->argument('name');
$traitPath = app_path("Traits/{$name}.php");
// Cek apakah trait sudah ada
if (File::exists($traitPath)) {
$this->error("Trait {$name} already exists!");
return;
}
// Membuat direktori jika belum ada
if (!File::exists(app_path('Traits'))) {
File::makeDirectory(app_path('Traits'));
}
// Template isi trait
$traitTemplate = "<?php
namespace App\Traits;
trait $name
{
// Add your methods here
}
"
;
// Menulis file trait baru
File::put($traitPath, $traitTemplate);
$this->info("Trait {$name} created successfully.");
}
}

Create Trait

Run this command to create a trait:

php artisan make:trait HasUser

Then, open the generated file in app/Traits/HasUser.php and add the relationship code like this:

<?php

namespace App\Traits;

trait HasUser
{
public function user()
{
return $this->belongsTo(User::class);
}
}

Use Trait in Model

Use the trait in your model like this:

// Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
use HasUser;
}

and so on for other models like `Comment` and `Like`, and you’re good to go! 😎

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Ferdy Hahan Pradana
Ferdy Hahan Pradana

Written by Ferdy Hahan Pradana

Tech explorer | Always learning & experimenting with new tech | Sharing knowledge & experiences

No responses yet

Write a response