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 27, 2025
π What Exactly is Array.fromAsync()? Array.fromAsync() is a static method introduced in ES2024 as part of JavaScript's growing support for asynchr...
Jul 26, 2025
1. Origins: Born Inside Facebook In 2011, Facebook engineers faced the increasing complexity of building interactive UIs at scale. They developed...
Sep 13, 2025
If you want to send Push Notifications from your Laravel app to mobile or web clients, the fastest and simplest way is to use Notifire. It integrate...
Jul 24, 2025
π§ What is Dynamic Import? Dynamic import allows you to load JavaScript modules at runtime—only when needed. This approach is fantastic for r...
Aug 17, 2025
Laravel Global Scopes: Automatic Query Filtering Eloquent Importance: Enforce consistent filters across all model queries (e.g., Soft Del...
Jul 01, 2025
π£ Complete React Hooks Guide with Practical Examples π§ useState What it does: Adds local state to a function component. Code Example: impo...