Jakeones
Jakeones

Reputation: 39

How to call a named function as a callback in laravel?

I got two functions in my model:

function getPersonsByGroup($groupId, $callback) {
        $group = StutGroup::where('stg_id', $groupId)->get();
        $persons = [];
        foreach($group as $gr) {
            foreach($gr->students as $stud) {
                $persons[] = $stud->person;
            }
        }
        return $callback(collect($persons));
    }

function joinStudentsToPersons($person) {
    return $person->each(function ($pers) {
            $pers->student = \DB::connection('pgsql2')->table('students')->where('stud_pers_id', $pers->pers_id)->get();
        });
    }

I'm trying to call the function getPersonsByGroup in my controller passing the reference to the callback as follows:

$students = $studGroup->getPersonsByGroup($request->group, $studGroup->joinStudentsToPersons);

But if I pass an anonymous function to the getPersonsByGroup everything works well:

$students = $studGroup->getPersonsByGroup($request->group, function($person) {
      return $person->each(function ($pers) {
          $pers->student = \DB::connection('pgsql2')->table('students')->where('stud_pers_id', $pers->pers_id)->get();
      });
});

What am I doing wrong?

Upvotes: 0

Views: 668

Answers (1)

Kurt Friars
Kurt Friars

Reputation: 3764

The solution to your problem, if you want to keep this kind of structure, is to make the method return the closure like so:

function joinStudentsToPersons() {
    return function ($person) {
        $person->each(function ($pers) {
            $pers->student = \DB::connection('pgsql2')->table('students')
                                ->where('stud_pers_id', $pers->pers_id)
                                ->get();
        });
    };
}

And then call it like:

$students = $studGroup->getPersonsByGroup($request->group, $studGroup->joinStudentsToPersons());

Upvotes: 1

Related Questions