orWhereHas cancelling out my other condition

Posted 3 months ago by packy

So I am trying to do a query that is filtered by a date range. The issue is I need to do a orWhereHas query as well which is not using mywhereBetween.

So I have 2 tables Promos and Member_Promo. To get the upcoming promos for a user I use a function like Auth::user()->upcomingPromos('ytd'). The function looks like:

public function upcomingPromos($type)
        switch ($type) {
            case 'ytd':
                $range = [Carbon::today(), Carbon::now()->endOfYear()];

            case 'mtd':
                $range = [Carbon::today(), Carbon::now()->endOfMonth()];

        return Promo::where('owner_id', $this->id)
            ->whereBetween('date', $range)
            ->orWhereHas('members', function ($query) {
                $query->where('user_id', $this->id);

So basically what it should do is get all the promos a user owns or is part of from today to the end of the year or end of the month. The issue stems from the orWhereHas is not limiting that query by the date range. So if a user is a member of a promo that is not in that range it still returns when it should not.

Please sign in or create an account to participate in this conversation.