티스토리 뷰

배움/PHP

Laravel의 Scope 기능

spaces25 2025. 4. 11. 10:01
반응형

Laravel의 Scope 기능은 Eloquent ORM에서 자주 사용되는 쿼리 조건을 재사용 가능하게 만들기 위한 강력한 기능입니다. Scope를 사용하면 복잡한 쿼리를 깔끔하고 가독성 좋게 구성할 수 있어 유지보수도 쉬워집니다.


🔹 Scope의 종류

Laravel에는 크게 두 가지 종류의 Scope가 있습니다:

  1. Local Scope
  2. Global Scope

✅ 1. Local Scope

특정 쿼리 조건을 메서드로 만들어 재사용할 수 있게 함

📌 사용 예시

// App\Models\Post.php

class Post extends Model
{
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }
}
 

📌 사용 방법

$posts = Post::published()->get();
 
  • scopePublished라는 메서드는 published()로 호출됨
  • scope 접두사는 메서드 선언에서만 필요하며, 호출할 땐 빼고 사용

⚙️ 파라미터 사용

 
public function scopePopular($query, $minViews)
{
    return $query->where('views', '>=', $minViews);
}

$popularPosts = Post::popular(100)->get();

✅ 2. Global Scope

모델에 항상 적용되는 조건 (예: soft delete 외 추가 필터)

📌 사용 예시

 
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class PublishedScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('is_published', true);
    }
}
// App\Models\Post.php

class Post extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new PublishedScope);
    }
}
  • Post::all()을 해도 항상 is_published = true 조건이 붙음
  • 특정 상황에서 제외하고 싶을 때는:
 
Post::withoutGlobalScope(PublishedScope::class)->get();

✨ Scope의 장점

  • 코드 재사용성 증가
  • 가독성 향상
  • 유지보수 용이
  • 테스트 편리함
반응형

'배움 > PHP' 카테고리의 다른 글

Laravel 11 라라벨 스케줄링(Scheduling)  (0) 2025.04.16
Lavavel Console Command Argument 옵션  (0) 2025.04.15
Laravel 의 Concurrency 기능  (0) 2025.04.14
PHP Carbon  (1) 2025.04.11
Laravel Command 기능  (0) 2025.04.11
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함