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

martleby's avatar

What to return from a Service?

Hi all,

I have a model called Student. I've created a service class that can take a Student and calculate the attendance for that student (or lots of them).

In my blade file I want to be able to foreach through the Students and access all the model attributes (name, dob etc.) but also access the attendance data calculated as if they were part of the model.

I'm scratching my head here. Should I look at some sort of wrapper class (eg StudentWithAttendance perhaps?) and return a collection of those?

Any thoughts or help greatly appreciated!

Thanks, M.

0 likes
2 replies
MichalOravec's avatar
Level 75

To your model Student you can add custom accessor with ValueObject

https://laravel.com/docs/7.x/eloquent-mutators#defining-an-accessor

ValueObject it's like your service class.

https://laracasts.com/series/whip-monstrous-code-into-shape/episodes/6

public function getAttendanceAttribute()
{
    return new AttendanceValueObject($this->yourRelationship);
}

Inside AttendanceValueObject you will have your logic to calculate an attendance.

Ten you can call it like

$student = Student::first();

$student->attendance->calculate(); // or whatever you want to have there
martleby's avatar

Thanks Michal - I refactored my code yesterday to your suggestion and it's working nicely.

Please or to participate in this conversation.