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

aarontharker's avatar

Can anyone think of how to make this a relationship

I'm currently appending a list of courses students are doing as an attribute but I would like to turn it into a relationship instead so I can query the actual models.

public function getCurrentSemesterCoursesAttribute()
    {
        $semester = now()->month > 7 ? 1 : 2;
        $year = now()->month > 7 ? now()->year : now()->year-1;
        $courses = $this->sittings()->where('semester', $semester)->where('year', $year)->with('course')->pluck('course_id');
        return Course::whereIn('id', $courses)->get();
    }

This is how I'm getting the attribute, anyone have any ideas on how to turn that into a relationship?

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To convert the getCurrentSemesterCoursesAttribute into an actual relationship, you can define a custom relationship method in your Student model. Since this relationship is not a standard Eloquent relationship, you'll need to use the whereHas method to filter the related models based on the conditions for the semester and year.

Here's how you can define the relationship:

public function currentSemesterCourses()
{
    $semester = now()->month > 7 ? 1 : 2;
    $year = now()->month > 7 ? now()->year : now()->year - 1;

    return $this->belongsToMany(Course::class, 'sittings')
                ->wherePivot('semester', $semester)
                ->wherePivot('year', $year)
                ->withTimestamps(); // Assuming you have timestamps on the pivot table
}

In this example, I'm assuming that there is a many-to-many relationship between Student and Course models, with sittings being the pivot table. The belongsToMany method is used to define this relationship, and the wherePivot method is used to add additional constraints to the pivot table columns.

Now, you can use this relationship like any other Eloquent relationship:

$student = Student::find(1);
$currentSemesterCourses = $student->currentSemesterCourses;

This will give you a collection of Course models that are related to the student for the current semester and year. You can now use Eloquent's eager loading, lazy loading, and other relationship methods on currentSemesterCourses.

Remember to replace Student and Course with the actual names of your models, and adjust the sittings pivot table name and any other column names as necessary to match your database schema.

Randy_Johnson's avatar

Use Eloquent. It will save you a lot of time in the long run.

Please or to participate in this conversation.