Laravel’s Various Relationship Types in PHP

Feedback


Question:

Although I have successfully established the connections between CourseModel, CourseTimeModel, and CourseInstructorModel, I am encountering a slight challenge in
Laravel Relationships
. Specifically, I am seeking a way to retrieve the instructor_name from the instructor table via the established relationship in
instructor table
. Is it feasible to accomplish this task using the existing relationship?

This refers to a file named “CourseModel.php”.

class CourseModel extends Model {
    protected $table = 'course';
    protected $fillable = [
       'course_name',
       'fee',
       'duration',
       'description',
       'created_at',
       'updated_at',
    ];
    public function courseInstructor() {
        return $this->hasMany('AppCourseInstructorModel');
    }
    public function courseTime() {
        return $this->hasMany('AppCourseTimeModel');
    }
    public function getCourses() {
        $courses = $this->with(['courseTime', 'courseInstructor'])->paginate(10);
        return $courses;
    }
}

The PHP file named “CourseInstructorModel.php”.

class CourseInstructorModel extends Model
{
    protected $table = 'course_instructor';
    protected $fillable = [
        'course_id',
        'instructor_id', 
        'created_at',
        'updated_at',
    ];
    public function course()
    {
        return $this->belongsTo('AppCourseModel');    
    } 
}

PHP file named CourseTimeModel.

class CourseTimeModel extends Model
{
    protected $table = 'course_time';
    protected $fillable = [
        'course_time',
        'course_id',
        'created_at',
        'updated_at',
    ];
    public function course()
    {
        return $this->belongsTo('AppCourseModel');    
    } 
}



Solution 1:

To resolve my issue, I implemented a Many-to-Many Relationship linking CourseModel and InstructorModel. I have included the code I wrote in the CourseModel.php file.

public function instructor() {
    return $this->belongsToMany('AppInstructor');
}


Solution 2:


Obtaining the name of the instructor can be achieved through the following method:

$courseModel = CourseModel::find(1);
$instructor_name = $courseModel->courseInstructor->instructor_name;

Frequently Asked Questions

Posted in Php