İçeriğe geç

Laravel Scope Nedir ve Kullanımı

Laravel Scope ile model sorgusuna yeni metod eklenir. Böylelikle sürekli aynı sorgu için metod yazmanıza gerek kalmaz. Örnek olarak aktif üyelere çekmek istediğiniz de sürekli …->where(‘status’, ‘1’); diye ekleme yapmanız gerekiyor. Ancak scope tanımlayarak bu işlemi basit şekilde gerçekleştirebilirsiniz.

class Post extends Model
{
    public function scopeActive($query)
    {
        return $query->where('status', 1);
 }
} 

Sorgu yapacak metod içine;

$activePosts = Post::active()->get();

Daha kullanışlı hale getirmek için parametre ile dinamik scope oluşturalım çevirelim;

class Post extends Model {
    public function scopeActive($query, $value)
    {
        return $query->where('status', $value);
    }
}

Aktif ve aktif olmayanları çekme;

// Get active posts
$activePosts = Post::active(true)->get();
// Get not active posts
$notActivePosts = Post::active(false)->get();
Kategori:EloquentLaravel

İlk Yorumu Siz Yapın

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir