Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ralphmorris's avatar

Query with conditional logic in relationship has() method always returning true

I have the following relationship set up to show me new applications compared to when a summary of new applications was last sent out..

    // Job Model

    public function applications()
    {
        return $this->belongsToMany('App\Professional', 'applications_pivot')
                    ->withPivot('message')
                    ->withTimestamps()
                    ->with('user.professional')
                    ->orderBy('message', 'desc');
    }

    public function newApplications()
    {
        if (!$this->last_summary_sent_out_at) 
        {
            $date = Carbon::now()->subDays(30);
        }
        else
        {
            $date = $this->last_summary_sent_out_at;
        }

        return $this->applications()->whereDate('applications_pivot.created_at', '>=', $date );
    }

This works well for instances like the below. Showing me only the applications that have been created since the last summary send out.

$job = \App\Job::findOrFail(1);

dd($job->newApplications);

However when I try to use the newApplications in the has() method it seems to return all jobs that have applications, not NEW applications.

$jobs = \App\Job::has('newApplications')->get();

This seems to have something todo with $this->last_summary_sent_out_at returning false in the query builder. This makes sense but not sure how to get what I want.

Any ideas? Let me know if this isn't clear enough.

Thanks!

Ralph

0 likes
2 replies
36864's avatar

The correct way to filter on relationship existence would be using whereHas. Adding where clauses to relationships does not always work as you might expect them to.

Here's a quick stab at fixing your problem (bit rushed and untested, but hopefully it'll nudge you in the right direction):

public function scopeHasNewApplications($query, $date) 
{
    return $query->whereHas('applications', function($query) use($date)
        {
            $query->whereDate('applications_pivot.created_at', '>=', $date);
        }
}

//usage:
$jobs = Jobs::hasNewApplications($date)->get();

I don't have time to go through redoing your logic for getting the date right now, sorry.

ralphmorris's avatar

Hi @36864 ,

Thanks for your reply.

The only trouble is the $date is different for each job so I'm not sure how I can get to it from inside the whereHas?

Please or to participate in this conversation.