Accessing distant relationship with belongstoMany

So each user can own multiple pages, and each page can have multiple users (assigned a role), and each page can have a job. Now, I am getting the pages owned by the user(s) like so:


 * Get the pages.
 * @return App\Modules\Pages\Entities\Pages
public function pages()
    return $this->belongsToMany('App\Modules\Pages\Entities\Pages')->withTimeStamps();

Now, I am trying to get the user's jobs, that belong to all and any of their pages

I have a relationship on the pages model, where the page can have many jobs like so:


 * Get the jobs.
 * @return App\Modules\Jobs\Entities\Jobs
public function jobs()
    return $this->hasmany('App\Modules\Jobs\Entities\Jobs');

The relationship is like so:

User table

id | name | password.. etc

Pages table

id | name

Pages pivot table

id | pages_id | user_id

Jobs Table

id | pages_id | name

So, my question is: how can I get all of the jobs that belong to all or any of the pages the user owns, or is associated with. I have tried the following:

$jobs = User::with('')
    ->where('id', Auth::user()->id)

Which just gets the user's table, not the jobs.

Now, I understand I could do the following, but this is resource intensive, and not the way I am looking for:

@foreach(Auth::user()->pages as $page)
    @foreach($page->jobs as $job)
        // ...

So, is there anyway to achieve this with a hasmanyThrough, or any other solution?

1 answer

  • answered 2018-01-11 21:11 Alexey Mezenin

    Use the whereHas() method:

    Job::whereHas('page.users', function($q) {
        $q->where('id', auth()->id());

    I assume that these relations are defined. If not, define those. In the Pages model:

    public function users()
        return $this->belongsToMany('App\Modules\Jobs\Entities\Users');

    In the Jobs model:

    public function page()
        return $this->belongsTo('App\Modules\Jobs\Entities\Pages');

    If you do not follow naming conventions, you also need to add pivot table name and foreign key names to these relationship definitions.