Relationships are how Eloquent models talk to each other, and they mirror the foreign keys already sitting in your database. The three you'll reach for constantly are hasOne, hasMany, and belongsTo.
If a Course has many Lesson records, the relationship lives on the "one" side as hasMany:
class Course extends Model
{
public function lessons(): HasMany
{
return $this->hasMany(Lesson::class)->orderBy('order');
}
}
On the other side, each Lesson belongs to exactly one Course, so that relationship is belongsTo:
class Lesson extends Model
{
public function course(): BelongsTo
{
return $this->belongsTo(Course::class);
}
}
Once both sides are defined, you call the relationship like a property, not a method — Eloquent handles the query for you and caches the result on the model instance:
$course = Course::find(1);
foreach ($course->lessons as $lesson) {
echo $lesson->title;
}
hasOne works exactly like hasMany but expects a single related record instead of a collection — useful for something like a Course having one Quiz. Eloquent infers the foreign key (course_id) and local key (id) from convention, but you can always pass them explicitly as extra arguments if your column names don't match the default.
Getting the direction right is the part beginners trip over: the relationship method goes on the model that has the others (hasMany), and the foreign key column lives on the model that belongs to the other (belongsTo). If you remember which table actually holds the foreign key, the direction follows naturally.