Check if relations are loaded on Eloquent Model

Submitted by chadwithuhc - 10 years ago

I've used this technique to check if I have called any `->with()` or other relations loaded on a model. I had a need for this since I have a lot of methods that require relation data in order to generate an appended property on the model. For example, if I want to pull all of the recent Posts of an Author and I want to store it on the model as `posts_this_month`, I would need to have Posts relation loaded. I want to force myself to eager load that data before I try to access it, otherwise I could run into an n+1 problem.

// Author Model Methods and Properties

    // Appended attributes
    protected $appends = array('posts_this_month');

    /**
     * Attribute mutator
     */
    public function getPostsThisMonthAttribute() {
        // Cancel if we have not retrieved Posts already
        if (!$this->isPostsLoaded()) {
            return null;
        }
        
        // Calculate Posts this month
        $posts_this_month = $this->posts->getPostsThisMonth();
        
        return $this->attributes['posts_this_month'] = $posts_this_month;
    }

    /**
     * Determine if we've already loaded the Posts
     * Used to prevent lazy loading on Posts, we always want to force eager or triggered loading
     * @return bool
     */
    public function isPostsLoaded() {
    	return isset($this->relations['posts']);
    }