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
Jul 26, 2025
1. Origins: Born Inside Facebook In 2011, Facebook engineers faced the increasing complexity of building interactive UIs at scale. They developed...
Jul 06, 2025
Using Web Components the Smart Way A lot of developers assume Web Components are meant to replace full SPA frameworks like React or Vue. But in rea...
Jun 26, 2025
CSS Specificity: Cascade Layers vs BEM vs Utility Classes This article compares three approaches to managing CSS specificity — BEM, utility‑f...
Jul 06, 2025
🔍 ECMAScript 2025 – Detailed Feature Guide All new ECMAScript 2025 features with code examples and explanation of their importance for front...
Jun 26, 2025
Color Everything in CSS – Simple Guide Today we’re diving into CSS colors: how to define them, especially with modern methods like lab(...
Jul 07, 2025
Mastering Laravel 12 Conditional Validation Laravel 12's validation system is super powerful, and conditional validation makes your forms...