#Getting count of relationship works, but unable to actually load records

2 messages · Page 1 of 1 (latest)

leaden marten
#

In the case where a Dues model has a hasMany relationship to a Payments model (payments()), and conversely, Payments has a belongsTo relationship (dues()) back to Dues, then if this statement gets an accurate count

$hasDues = $user->dues()->where('year', $duesYear)->has('payments')->count() > 0;

and I want to get those payments records, then why does this fail?

$payments = $user->dues()->where('year', $duesYear)->payments()->get();

This returns the error Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$payments, even though I have exactly that defined in the Dues model:

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

I get the same error if I try this:

$payments = $user->dues()->where('year', $duesYear)->payments;

This seems pretty straightforward. What am I missing?

#

The rubber duck strikes again. I got it to work with this

$payments = $user->dues()->where('year', $duesYear)->with('payments')->get()

However, if there's a better way, I'm open to it.