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

colinlongworth's avatar

indexQuery in Laravel Nova for Many to Many Polymorphic Relationship

I have a polymorphic relationship of User, Student, Course. They can all belong to many Groups.

When a User logs in, I want them to only be able to see the Students and Courses that are in their Groups.

If we examine the Student resource in Nova, every student is returned on the index hence a User can see every Student in the school. viewAny and view as part of Polices don't solve this problem, and Laravel Nova docs suggest overriding the indexQuery to filter the results.

My question is, how do I alter the $query (Builder) to only return Students that are part of the Users group?

class User extends Authenticatable implements MustVerifyEmail
{

    public function groups() {

        return $this->morphToMany(Group::class, 'groupable');
    }
}

class Student extends Model
{

    public function groups() {

        return $this->morphToMany(Group::class, 'groupable');
    }
}

class Group extends Model
{

    /**
     * Get all of the students that are part of this group
     */
    public function students()
    {
        return $this->morphedByMany(Student::class, 'groupable');
    }

    /**
     * Get all of the users that are part of this group
     */
    public function users()
    {
        return $this->morphedByMany(User::class, 'groupable');
    }

    /**
     * Get all of the users that are part of this group
     */
    public function courses()
    {
        return $this->morphedByMany(Course::class, 'groupable');
    }
}


The closest I've got so far is:


$query = $query->whereHas('groups', function($q) use($request) {
            $q->whereIn('id', $request->user()->groups);
        })

But this gives an error:

General error: 1 ambiguous column name: id 

from the SQL:


select * from "students" where exists (select * from "groups" inner join "groupables" on "groups"."id" = "groupables"."group_id" where "students"."id" = "groupables"."groupable_id" and "groupables"."groupable_type" = ? and "id" in (?)) order by "students"."id" desc  

SOLUTION

The issue was my use of $request->user()->groups in the whereIn clause. This works:

$query->whereHas('groups', function($q) use($request) {

            $q->whereIn('groups.id', $request->user()->groups->pluck('id'));
           
        });
0 likes
2 replies
bugsysha's avatar

Show your database structure and relationships.

Please or to participate in this conversation.