Never mind everyone. Brain finally kicked in almost straight after posting this. Surprise surprise the last part of Jarek's post is the missing link.
Funny how accessors don't do anything until you actually "access" the data :)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a parent - student relationship and I want to return a count of students.
The relationship works fine and I get back the correct count. However the accessor does not trigger and so I simply get an array like a normal relation. I use the Laravel Debug Bar and have tried to log some text from the accessor but the line of code seems to never execute.
I followed Jarek's blog post to get this far: http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/
Here is my code:
//Relation
public function studentCount()
{
return $this->hasOne('App\Models\ParentLink', 'parent_id')->selectRaw('parent_id, count(*) as count')->groupBy('parent_id');
}
//Accessor
public function getStudentCountAttribute()
{
Debugbar::info("hey");
//if relation is not loaded already, let's do it first
if ( ! array_key_exists('studentCount', $this->relations))
{
$this->load('studentCount');
}
$related = $this->getRelation('studentCount');
// then return the count directly
return ($related) ? (int) $related->count : 0;
}
Returns only:
"student_count":{"parent_id":"2","count":"4"}
Never mind everyone. Brain finally kicked in almost straight after posting this. Surprise surprise the last part of Jarek's post is the missing link.
Funny how accessors don't do anything until you actually "access" the data :)
Please or to participate in this conversation.