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.
@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?
@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 ?
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.