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
Task Reminder with Laravel & MongoDB
Jun 30, 2025
📌 Building a Task Reminder App This guide shows how to set up a Laravel app using MongoDB to implement a task reminder system with authentication,...
React Labs: View Transitions & Activity
Jun 17, 2025
React Labs: View Transitions & Activity Published April 23, 2025 by Ricky Hanlon. React Labs is sharing two new experimental featu...
Using Web Components the Smart Way
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...
How OAuth Works
Jun 29, 2025
How OAuth Works OAuth is a protocol that allows third-party applications to access user data without sharing passwords. It's the backbone of secure a...
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...
React Hooks Complete Guide
Jul 01, 2025
🎣 Complete React Hooks Guide with Practical Examples 🧠 useState What it does: Adds local state to a function component. Code Example: impo...
