vendredi 28 septembre 2018

Laravel scope using calculated value

I have the following problem in Laravel 5.4: There´s a user table and a membership table, where a user can have many memberships, and a membership belongs to a user. The memberships are of annual duration, but a member will get an additional free day for each friend they recommend that registers on my site, thus the number of free days is constantly changing; this in turn changes the membership´s expiration date. So the question is: How to scope the active memberships for a given user, if the expiration date is a variable? I will need to do something like this:

First the expiration date in Membership.php:

This calculates the total days for each membership: Note that the friendsDays are calculated per user in User.php

public function getTotalDaysAttribute() {
        $days = $this->paidDays + $this->user->friendsDaysRemaining;
        return $days;
    }

This calculates the expiration date for each membership:

public function getExpirationDateAttribute() {
    $date = $this->startDay->addDays($this->TotalDays);
    return $date;
}

So far so good... Now, this is where I´m stuck (pseudo code):

public function scopeActive($query, $dateToCheck = Null) {
   $query->where($dateToCheck >= $this->expirationDate);
}

How to code this properly to get:

dump($user->membership()->active()->get());

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire