Laravel unwritten guideline: Traits

debuqer
2 min readNov 18, 2023

If you’re a user of Laravel and a fan of traits, this article will help you understand the Laravel way of creating and using traits.

Introduction to Traits

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.[PHP documentation]

Let’s take a look at a PHP example of traits:

Traits in Laravel

Traits are widely used in Laravel as they significantly reduce code duplication. The Laravel core leverages the advantages of traits and encourages users to do the same. As a Laravel user, you’re probably already familiar with these traits.

class ProcessPodcast implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

/**
* Create a new job instance.
*/
public function __construct(
public Podcast $podcast,
) {}

/**
* Execute the job.
*/
public function handle(AudioProcessor $processor): void
{
// Process uploaded podcast...
}
}

Laravel provides several traits that you can use. You can check out some of these traits here.

Tips for naming traits

  1. Be Descriptive: Traits should be named in a self-explanatory manner. Since they are located at the highest level in a class, right before the class definition, their names should clearly indicate their purpose and functionality.
  2. Avoid Trait Postfixes: If you’re using namespaces correctly, there’s no need to add “Trait” as a postfix to your trait names. It’s redundant and unnecessary. Instead, name your traits based on their behavior.

Laravel’s Trait Naming Convention

Laravel follows a naming convention that uses prefixes to describe trait behavior. Some common prefixes include “Can,” “CanBe,” “InteractsWith,” “Must,” “Handles,” and “Has.” Additionally, the postfix “able” can be used to indicate the kind of behavior the trait adds to a class. This naming convention is easy to implement and improves code readability.

Let’s see more example

class Student extends Model
{
use HasFactory;

public $fillable = [
'name',
'email',
];
}
class User extends Authenticatable implements AggregateRoot
{
use HasApiTokens, HasFactory, Notifiable;
}
class BroadcastEvent implements ShouldQueue
{
use Queueable;
...
}

class Command extends SymfonyCommand
{
use Concerns\CallsCommands,
Concerns\ConfiguresPrompts,
Concerns\HasParameters,
Concerns\InteractsWithIO,
Concerns\InteractsWithSignals,
Concerns\PromptsForMissingInput,
Macroable;
...
}

Conclusion

Using traits instead of duplicating code can greatly improve code maintainability. However, it’s important to follow good naming conventions for traits to ensure clean and readable source code. If you’re a fan of the Laravel eco-system, following its rules can be beneficial to have a cleaner codebase and more readability.

--

--