php – Eloquent "with" returns null-ThrowExceptions

Exception or error:

i’m getting all courses with user (author of this course), but it returns me null.
After debuging i tried diferent way to get relation, but it gives me diferent result.

i’m confused because of $course->user (null) | $course->user()->first() (expected result), but for some of users $course->user gives me expected result…

$coursesModel = Course::latest()->with(['user.profile', 'reviews:course_id'])->get();

    foreach ($coursesModel as $key => $course)
    {
        if (!$course->user)
            dd($course, $course->user, User::find($course->user_id), $course->user()->first());
    }

Result:

enter image description here

enter image description here

User Model:

public function courses()
{
    return $this->hasMany(Course::class);
}

Couse Model:

public function user()
{
    return $this->belongsTo(User::class);
}

DataBase:

-users
  ->id
-courses
  ->id
  ->user_id
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *