← Back to Course

Using Traits for Reusable Code

PHP traits let a chunk of reusable method logic be shared across multiple classes, without the rigid single-inheritance limitations of extending a base class.

Defining a Trait

trait Loggable
{
    public function logActivity(string $message): void
    {
        Log::info(static::class . ': ' . $message);
    }
}

Using a Trait

class Order
{
    use Loggable;
}

$order->logActivity('Order shipped');

Traits Laravel Itself Uses Heavily

When to Reach for a Trait

Traits work well for small, focused, cross-cutting behaviour — logging, soft deletes, UUID generation — rather than for organizing an application's core business logic, which benefits more from dedicated classes like repositories and services.

That distinction leads naturally into the next topic: structuring business logic itself with the repository and service layer patterns.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course