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

dcabane's avatar

Problem with attribute appended to model

Hello, I have a User model in my app. I use the Spatie package to define roles and added the following code to have a "teachers" attribute on the model :

public function getTeachersAttribute()
    {
        if($this->hasRole('hod') || $this->hasRole('admin')){
            return User::whereHas("roles", function($q){ $q->where("name", "teacher"); })->get();
        }

        return null;
    }

The code works in tinker ($user->teachers returns the expected array) but I can't append this attribute to the model. I tried to add the code bellow to my model :

protected $appends = ['teachers'];

The app just blanks out for 30s and then times out. I guess there must be some kind of infinite loop somewhere but I can't see it.

Would anyone be able to help me out ?

0 likes
5 replies
martinbean's avatar

@dcabane You shouldn’t be doing queries like that in an accessor. It’s just going to lead to N+1 problems. But I don’t really know what you’re trying to do in the first place.

Why are you trying to fetch all users with the teacher role, from a user instance? That doesn’t really make sense. Why not use a relationship, or a scope if you want to fetch only “teacher” users?

2 likes
dcabane's avatar

@martinbean OK I think I get the problem now, thanks ! Here is what I want to do : My app has teachers and students (few teachers, lots of students). I want teachers to be able to access one another's details. Hence my attempt : when a teacher logs in, I have access to a list of his colleagues on the user object in the front end. Does that make sense ?

martinbean's avatar

@dcabane Then just add a scoop to your User model if you just want to fetch users that are teachers:

$teachers = User::teacher()->get();
Snapey's avatar

The app just blanks out for 30s and then times out. I guess there must be some kind of infinite loop somewhere but I can't see it.

because you append the results of the query. So you get a user and append any users that are teachers. And for each of those users, you append any users that are teachers, and for each of those users append any users that are teachers. A recursive loop that you cannot break out of.

Otherwise, I revert to @martinbean answer.

2 likes

Please or to participate in this conversation.