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

geek123's avatar

Append attribute to Model if exists in Pivot?

With these many to many models:

class StudentLesson extends Pivot
{
    /* student_lesson(student_id, lesson_id, subscribed_at) */
}

class Lesson extends Model
{
    /* lessons(id, title) */
    
    public function students()
    {
        return $this->belongsToMany('App\Student', 'student_lesson', 'lesson_id', 'student_id') 
            ->using('App\StudentLesson')
            ->withPivot('subscribed_at')
            ->withTimestamps();
    }
}

class Student extends Model
{
    /* students(id, name) */

    public function lessons()
    {
        return $this->belongsToMany('App\Lesson', 'student_lesson', 'student_id', 'lesson_id') 
            ->using('App\StudentLesson')
            ->withPivot('subscribed_at')
            ->withTimestamps();
    }
}

How to implement this function?

function getLessons($title, $studentId) {

    // return lessons that have title like '%'.$title.'%' with subscribed_at if $studentId exists in student_lesson
}

exemple:

lessons:

[
    {
        id: 1,
        title: "Lesson 01",
    },
    {
        id: 2,
        title: "Lesson 010"
    },
    {
        id: 3,
        title: "Lesson 03",
    },
    {
        id: 4,
        title: "Lesson 012"
    }
]

student_lesson:

[
    {
        student_id: 7,
        lesson_id: 1,
        subscribed_at: "2020-08-05 07:32:20"
    },
    {
        student_id: 7,
        lesson_id: 4,
        subscribed_at: "2019-02-07 10:00:00"
    }
]

getLessons('01', 7) returns :

[
    {
        id: 1,
        title: "Lesson 01",
        subscribed_at: "2020-08-05 07:32:20"
    },
    {
        id: 2,
        title: "Lesson 010"
    },
    {
        id: 4,
        title: "Lesson 012",
        subscribed_at: "2019-02-07 10:00:00"
    }
]
0 likes
2 replies

Please or to participate in this conversation.