Debiprasad Debiprasad - 4 months ago 13
MySQL Question

Laravel - eager loading a method (not a relationship) of an Eloquent model

Like we can eager load a relationship of an Eloquent model, is there any way to eager load a method which is not a relationship method of the Eloquent model?

For example, I have an Eloquent model

and it has the following method:

public function totalScore()
return $scores = DB::table('grade_report_scores')->where('grade_report_id', $this->id)->sum('score');

Now I am getting a collection of
Eloquent models.

$gradeReports = GradeReport::where('student_id', $studentId)->get();

How can I eager load the returning values of
method for all
Eloquent models in the collection?


You can add arbitrary properties to your models by adding them to $appends array and providing a getter. In your case the following should do the trick:

class GradeReport extends Model {
  protected $appends = ['totalScore'];

  public function getTotalScoreAttribute() {
    return $scores = DB::table('grade_report_scores')->where('grade_report_id', $this->id)->sum('score');

Now all GradeReport objects returned from your controllers will have totalScore attribute set.