Stop Copy-Pasting Code! Learn How to Use Traits in Laravel the Right Way
July 1, 2025🚫 Stop Copy-Pasting Code!
Ever duplicated slug logic or logging across multiple models? Laravel's Traits got your back.
1. What’s a Trait?
A Trait is a snippet of reusable methods you can “mix into” any class.
trait Sluggable {
public function createSlug(string $text): string {
return \Illuminate\Support\Str::slug($text, '-');
}
}
2. How to create one
Use Artisan:
php artisan make:trait Traits/Sluggable
This creates app/Traits/Sluggable.php with the code above.
3. Use it in a model
namespace App\Models;
use App\Traits\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
use Sluggable;
protected static function booted() {
static::creating(fn($p) => $p->slug = $p->createSlug($p->name));
}
}
4. When to use Traits
- ✅ Shared logic across many classes
- ✅ You want DRY code without complex inheritance
5. Real-world examples
HasUuid– auto-fill UUID on modelsLogsActivity– track user actionsApiResponse– uniform JSON responses
6. When not to use Traits
- ❌ Complex logic needing DI
- ❌ Too many unrelated methods grouped
- ❌ Only used by a single class
- ❌ Core business logic – better in Services
Conclusion
Traits are a powerful tool for reusable, maintainable code—if used wisely. Next time you're about to copy-paste, ask: can I make this a Trait?
Blog
Jan 27, 2026
Introduction React Native is one of the most widely used frameworks for cross-platform mobile application development. However, iOS build time ha...
Jul 01, 2025
🚀 Laravel Queue & Job System We’re gonna walk you through Laravel queues from setup to deploying in production using Supervisor. Step 1...
Jul 20, 2025
Laravel Context is one of the most powerful new features in Laravel 12. It allows you to attach contextual data (like user ID, IP address, request pat...
Jul 06, 2025
🔍 ECMAScript 2025 – Detailed Feature Guide All new ECMAScript 2025 features with code examples and explanation of their importance for front...
May 23, 2026
The Journey of a Request Inside Laravel: The Core Concept and Complete Lifecycle A deep dive into how Laravel processes requests from start to...
Jul 27, 2025
Here’s a complete breakdown of essential tools to level up your Laravel development: Inertia.js v2, View Creators, and the Laravel HLS package...