Sunday, May 21, 2017

Using multiple Laravel scopes in OR context

I have a Subscription model which contain start and end dates in my Laravel app. I have created two query scopes, scopeActive and scopeFuture to find active and future subscriptions (respectively).

I would like to know how I can build a query using both scopes in OR context, so that I can find any active or future subscriptions.

Subscription Model

/**
 * Scope a query to only include active subscriptions.
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeActive($query)
{
    return $query->where('start_date', '<', Carbon::now())
                 ->where('end_date', '>', Carbon::now());
}

/**
 * Scope a query to only include future subscriptions.
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeFuture($query)
{
    return $query->where('start_date', '>', Carbon::now());
}

Controller

Subscription::active()->get();



via Imran

Advertisement