Scopes و Accessors في Eloquent: كود يقرأ كأنه جملة
كيف تحول الشروط المكررة إلى Scopes بأسماء واضحة وتستخدم Accessors و Casts لتنظيف طريقة عرض البيانات.
قارن بين هذين السطرين:
Post::where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())->get();
Post::published()->get();
كلاهما يفعل نفس الشيء. الثاني يخبرك ماذا تريد لا كيف تحصل عليه.
Local Scopes
class Post extends Model
{
public function scopePublished(Builder $query): void
{
$query->where('status', 'published')
->where('published_at', '<=', now());
}
public function scopeInCategory(Builder $query, Category $category): void
{
$query->where('category_id', $category->id);
}
}
والاستخدام يتسلسل بشكل طبيعي:
Post::published()->inCategory($laravel)->latest('published_at')->paginate();
الفائدة الأكبر: لو تغير تعريف "منشور" غدا (مثلا: أضفنا شرط ألا يكون محذوفا) تعدله في مكان واحد.
Global Scopes: بحذر
protected static function booted(): void
{
static::addGlobalScope('active', fn (Builder $q) => $q->where('active', true));
}
تطبق على كل استعلام تلقائيا. هذا قوي لكنه مصدر ارتباك عندما ينسى أحد أن الشرط موجود. استخدمها لقواعد لا استثناء لها تقريبا مثل فصل بيانات العملاء في نظام متعدد المستأجرين.
Accessors: قيم محسوبة
protected function readingTime(): Attribute
{
// str_word_count لا يعد الكلمات العربية لذلك نقسم على المسافات
return Attribute::get(function () {
$words = preg_split('/\s+/u', trim(strip_tags($this->body)), -1, PREG_SPLIT_NO_EMPTY);
return max(1, (int) ceil(count($words) / 200));
});
}
// الاستخدام
$post->reading_time;
ومثال آخر مفيد:
protected function url(): Attribute
{
return Attribute::get(fn () => route('posts.show', $this->slug));
}
بدل تكرار route('posts.show', $post->slug) في عشرين ملف Blade.
Mutators: تنظيف عند الحفظ
protected function email(): Attribute
{
return Attribute::set(fn (string $value) => strtolower(trim($value)));
}
Casts: أنواع صحيحة تلقائيا
protected function casts(): array
{
return [
'published_at' => 'datetime',
'is_featured' => 'boolean',
'settings' => 'array',
'status' => PostStatus::class, // Enum
];
}
الآن $post->published_at كائن تاريخ يمكنك تنسيقه و $post->settings مصفوفة جاهزة و $post->status قيمة Enum وليست نصا حرا.
متى لا تستخدمها؟
- Accessor ينفذ استعلاما لقاعدة البيانات: سيتكرر في كل حلقة ويصنع مشكلة N+1.
- Scope بعشرة معاملات: الأفضل كلاس استعلام مستقل.
الهدف ليس استخدام كل ميزات Eloquent بل أن يقرأ زميلك الكود فيفهم قصده من النظرة الأولى.


