kinggs
kinggs

Reputation: 1168

How to set a Laravel attribute on a condition

I have a question around Laravel's eloquent ORM and I was unsuccessful in finding an answer here. Hopefully the following makes sense but if you need any clarification, please ask.

I'm looking to create an attribute in my User model for availability.

My current User model looks like this:

class User extends Authenticatable implements MustVerifyEmailContract
{

    ...

    /**
     * Get the dates available for the user.
     */
    public function dates()
    {
        return $this->hasMany(Date::class);
    }

    ...

}

This returns all the dates from the database for which the user is available and this works fine.

The columns for dates looks like id, from, to with from and to being dates.

What I'd like to do is access within my views something similar to the following whilst also keeping the dates collection:

$user->is_available_today

Is there a way to create an attribute which will give me this data.

For example:

public function getIsAvailableTodayAttribute()
{
    $today = date("Y-m-d");
    return $this->from <= $today && $this->to => $today;
}

Thanks

Upvotes: 0

Views: 1484

Answers (1)

user10896277
user10896277

Reputation:

You can do it like this:

public function getIsAvailableTodayAttribute()
{
    return $this->dates()->where([
        ['from', '<=', now()],
        ['to', '>=', now()],
    ])->count() > 0;
}

Upvotes: 2

Related Questions