Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iambaz's avatar

How do I access my 'grandparent ' relation

I have three related tables.

Users has a many to many relationship with projects with a pivot table. Projects has a one to many relationship with pages.

All the relevant links are set up in the models.

I am building an API and when I show an individual page, I need to check back to the users table to see if the current user is attached to the project which the page is attached to.

Here is my code:

public function show($id)
{
    $userid = 3;
    if(Page::find($id)->project()->users()->contains($userid))
    {
    dd(TRUE);
     }
}

When I run this I get Call to undefined method Illuminate\Database\Query\Builder::users()

Can someone point me in the right direction?

Thanks

0 likes
2 replies
acasar's avatar

It should probably be:

Page::find($id)->project->users()->find($userid)

Note that calling $query->project is the same as calling $query->project()->first(), it's just a syntactic sugar.

amitshahc's avatar

How can we create a relationship in the model to access GrandParent?

Example: Project->hasMany(Sites)->hasMany(Tasks) Also having defined: Tasks->belongsTo(Site)->belongsTo(Project)

How can I define the relationship in Tasks model to attach the Project model using with() keyword.

	public function project()
    {
        return $this->site()->project();
    }

This is not working.

Please or to participate in this conversation.