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
| Feature | Traits | Inheritance |
|---|---|---|
| Type | Code reuse | Parent-child relationship |
| Multiple use | Yes (many traits in one class) | No (single parent class) |
| Flexibility | High | Limited |
🎯 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.