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

colinlongworth's avatar

Restricting Model access by belongsTo Group

I have a set up whereby a Student and Course are part of a Group. Each Student has an Enrollment in a Course.

When logged into Nova, a User is assigned to a Group. This means they can only access the Course(s) and Student(s) that are in their Group. I achieve this by modifying the indexQuery in Resource.php

Important: Enrollments cannot be added to a Group as it makes the admin effort much higher.


public static function indexQuery(NovaRequest $request, $query)
    {
    
        /* We modify the query to only allow a User to only view models within their assigned Groups */

        if(Str::contains($query->toSql(), ['students', 'courses', 'users'])) {
        
            $query = $query->whereHas('groups', function($q) use($request) {
                $q->whereIn('groups.id', $request->user()->groups->pluck('id'));
            });

            return $query;
        }

        return $query;
    }

The issue is that the Enrollments are not being restricted, therefore if a User has a Course in their Group, they can see all the Enrollments, even of Students that are not in their Group.

In other words, a User should only be able to see the Enrollments of a Student that is part of their group.

I assume there is some way to do this as the Course, Student and Enrollment are all related in their models, I just can't see to correctly modify the indexQuery to achieve this.


class Enrollment extends Model
{
    public function student()
    {
        return $this->belongsTo(Student::class);
    }

    public function course()
    {
        return $this->belongsTo(Course::class, 'course_id', 'external_course-id');
    }

}

class Student extends Model
{
    public function groups() {

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

class Course extends Model
{
    public function groups() {

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

class Group extends Model
{

    public function students()
    {
        return $this->morphedByMany(Student::class, 'groupable');
    }


    public function courses()
    {
        return $this->morphedByMany(Course::class, 'groupable');
    }
}
0 likes
1 reply

Please or to participate in this conversation.