Can I modify a model's values on a relationship before returning the results?

Posted 2 years ago by mmacdonald

So I have a User model (which in this case is acting as a "student"). I also have a Classroom model which has a relationship that gets all the Users in that class.

The relationship works and looks like this:

public function students(){
        return $this->belongsToMany('App\User', 'classroom_student', 'classroom_id', 'student_id');

Each user has a 'name' column which formats like this: "Firstname Lastname".

Occasionally I need to get the students with their names formatted like this: "Lastname, Firstname". I could change the table to have two separate columns, but I already have a few thousand users in there and I'm already using their full names in a bunch of places. So changing the formatting this way seems easier.

I tried creating a custom function on the Classroom model that looks like this:

public function studentsLastNameFirst(){
        $students = $this->students();
        foreach($students as $student){
            $name = $student->name;
            $nameArray = explode(' ', $name);
            $nameArray = array_reverse($nameArray);
            $name = implode(", ", $nameArray);
            $student->name = $name;
        return $students;

The php part isn't really a concern as I know it will split the name at the space, flip the names, and add a comma... (I tested it independently).

The issue is that on my view it just returns the 'students' relationship. Their names don't change at all... Is there a better way to do this? Do you see a glaring issue I'm missing here?


Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.