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
Efficient Reporting & Big Data Reports with Queues
Jul 07, 2025
How to cache report queries with fixed timelines How to generate large reports asynchronously using job queues 1. 🧠 Report Query Caching wi...
Using useCallback in React: Benefits, Limitations, Best Practices
Jul 31, 2025
The useCallback hook in React is used to return a memoized version of a callback function, so it's only recreated when its dependencies change. The...
Is Laravel Slow? Optimize Queries & Indexes for Maximum Performance
Jul 20, 2025
A detailed, example-rich guide to avoid slowdowns in Laravel apps by optimizing data retrieval and employing indexing smartly. 1. 🧠 Fetch Only...
Laravel 12.18.0 Update
Jun 17, 2025
Laravel 12.18.0 Update The Laravel team released version 12.18.0 with several cool updates: String encrypt() & decrypt() helpers are...
React History – A Professional Developer’s Perspective
Jul 26, 2025
1. Origins: Born Inside Facebook In 2011, Facebook engineers faced the increasing complexity of building interactive UIs at scale. They developed...
Bypassing $fillable Safely with forceFill() in Laravel
Jul 02, 2025
Bypassing $fillable Safely with forceFill() in Laravel Ever used create() in Laravel and noticed some fields like role or status didn’t save? T...
