11 months ago

Reusing called accessor

Posted 11 months ago by fabricecw

I'm using an accessor which loads a custom relationship field:

public function getHandoverDedicatedAreaAtAttribute()
        $activity = $this->activities()->select('created_at')->where('status', 6)->first();

        if($activity) {
            return $activity->created_at;

        return null;

And in another accessor, I call the accessor above:

public function getIsOverdueAttribute()
        return Carbon::parse($this->handover_dedicated_area_at) > Carbon::parse($this->delivery_at);

But as I analyzed with Debugbar, if I call the is_overdue and handover_dedicated_area_at attributes, the query from getHandoverDedicatedAreaAtAttribute() is called twice.

Is there a way to reduce this to one query and use the attribute value from the Model once it's loaded?

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