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

Greeenone's avatar

Authorize perform actions on all sub data

Hello!

I have one question abour policies and gates. Now, in my project I’m authorizing everything one by one. Is it possible to allow edit all „sub data”?

Here is an exemple what I would like to do:

I have teachers, teachers_students (Pivot), and students table. Each teacher can „own” students (ManyToMany).

I have also additional tables for students like „Notes”, „Homeworks”, „Exams” etc (OneToOne)

I would like to allow teachers to edit all tables that are linked to they students.

For exemple:

Student (Id 2) has two exams (id:5 and id:6). His teacher has id 34. When teacher want to edit student’s exams, we are only verify if user belongs to teach via pivot table. So teacher can edit these table, because in pivot table he is linked to his student

0 likes
1 reply
Nakov's avatar
Nakov
Best Answer
Level 73

Yes, I will go with a Gate for such a general check, and policy if you need each action to have it's own check.

So something like this: (https://laravel.com/docs/9.x/authorization#writing-gates)

Gate::define('manage-student', function (User $user, Student $student) {
    return $user->students()->where('students.id', $student->id)->exists(); // check on the db level

// return $user->students->contains($student->id);  -- this is loading all students in memory
});

then to check:

if (Gate::forUser($user)->allows('manage-student', $student)) {
    // The teacher can manage the student
}

the $user above is the Teacher in your app.

1 like

Please or to participate in this conversation.