What are Traits in Laravel

In Laravel, Traits are a feature of PHP that Laravel uses to reuse common methods across multiple classes—without using inheritance.


🔹 Simple Meaning

A Trait = Reusable piece of code

It lets you:

“Write code once, use it in many classes.”


🧠 Why Traits are Useful

PHP does not support multiple inheritance (a class can extend only one class).
So Traits help to:

  • Share common functionality
  • Avoid code duplication
  • Keep code clean and modular


🔧 Example of a Trait

trait Logger
{
public function log($message)
{
return "Log: " . $message;
}
}

Using Trait in a Class

class UserController
{
use Logger;

public function index()
{
return $this->log("User accessed");
}
}

👉 Now UserController can use the log() method.


💡 Laravel Example

Laravel uses traits a lot internally. For example:

use Illuminate\Foundation\Auth\AuthenticatesUsers;

This trait provides:

  • Login logic
  • Validation
  • Redirect handling


🔁 Traits vs Inheritance

FeatureTraitsInheritance
TypeCode reuseParent-child relationship
Multiple useYes (many traits in one class)No (single parent class)
FlexibilityHighLimited


🎯 Common Laravel Traits

  • AuthenticatesUsers
  • DispatchesJobs
  • ValidatesRequests
  • SoftDeletes


🧩 In Short

Traits in Laravel = Reusable methods that can be included in multiple classes to avoid repeating code.

To Top