0

I can not find why it does not work.

In my Course model I have defined relation:

class Course extends Model {

    public function courseDates() {
        return $this->hasMany(CourseDate::class, 'course_id');
    }

}

And in my CourseDate model this:

class CourseDate extends Model {

    public function course() {
        return $this->belongsTo(Course::class);
    }

}

When I try to access CourseDates from Course I will always get null, but when I access Course from CourseDate, it works and I see all data:

var_dump(CourseDate::where('id', 1)->first()->course->name); => output: "Course 1"
var_dump(Course::where('id', 1)->first()->courseDate); => output: null

And what's strange when I try it with another course (like ID 2) then it works. The data is absolutely the same in the database. Any Ideas?

Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
  • Check class name in `CourseDate` model. Please add your database details. – iamab.in Nov 29 '18 at 08:56
  • 1
    You have a typo in your `var_dump`. You are trying to access `courseDate` but the relationship method is called `courseDates`. – Remul Nov 29 '18 at 09:01

1 Answers1

0

You shouldent add class like CourseDate::class instead you should add it like below

class Course extends Model {
   public function courseDates() {
       return $this->hasMany('App\CourseDate', 'course_id');
   }
}

And in your CourseDate model

class CourseDate extends Model {
   public function course() {
       return $this->belongsTo('App\Course');
   }
}

And your relationship method for Course model is courseDates so you should use it like below

var_dump(Course::where('id', 1)->first()->courseDates);

Documentation : https://laravel.com/docs/5.7/eloquent-relationships

Leena Patel
  • 2,423
  • 1
  • 14
  • 28