Search code examples
laravel-5.3

Laravel 5.3 Scope chain not working as expected


I'm chaining two scopes. I expect that the model will return with only rows that answer the constraints in BOTH scopes.

public function scopeHasImages() {
    return $this->has('images');
}

public function scopeCompleted() {
    return $this->where('status', 'complete');
}

and then I use

Subject::completed()->hasImages()->limit(100)->get()[0]->status;

unfortunately result is "pending"

just to make things clear, this works:

Subject::completed()->limit(100)->get()[0]->status;

result is "complete"


Solution

  • Change your Local Scopes to return a \Illuminate\Database\Eloquent\Builder instance:

    public function scopeHasImages($query) 
    {
        return $query->has('images');
    }
    
    public function scopeCompleted($query)
    {
        return $query->where('status', 'complete');
    }
    

    And then chaining the scopes will work:

    Subject::completed()->hasImages()->limit(100)->get();