/** * Load pages user is allowed to access and set the collection as 'pages' relation * */ protected function loadPages() { $pages = Page::join('page_role as pr', 'pr.page_id', '=', 'pages.id')->join('role_user as ru', 'ru.role_id', '=', 'pr.role_id')->where('ru.user_id', $this->id)->distinct()->get(['pages.*', 'user_id']); $hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Page::query(), $this, 'user_id', 'id'); $hasMany->matchMany([$this], $pages, 'pages'); // If there is no collection to set the relation on, create a blank one if (!isset($this->pages)) { $this->setRelation('pages', new Collection()); } return $this; }