Laravel Intermediate Eloquent & Routing · 9 min read

Eloquent Relationships: hasMany and belongsTo

Lesson 7 of 33 in the Laravel learning path.

How do I relate lessons, enrollments, and users?

A relationship method tells Eloquent how two tables connect. Lesson hasMany Enrollment means lessons.id is stored in enrollments.lesson_id. Enrollment belongsTo Lesson and belongsTo User uses those foreign keys to load the parent. Once the methods exist, $lesson->enrollments and $enrollment->user read like properties, and Eloquent runs the query the first time you touch them.

This catalog uses a real Enrollment model rather than a bare pivot, because an enrollment has a status and a timestamp of its own. belongsToMany is the alternative when the middle table is only a pair of ids. Use it for lesson tags. Use the enrollment model for students in a course.

Syntax & Parameters

Syntax
return $this->hasMany(Enrollment::class);

Example

app/Models/Enrollment.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Lesson extends Model
{
    public function enrollments(): HasMany
    {
        return $this->hasMany(Enrollment::class);
    }

    public function tags(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Tag::class);
    }
}

class Tag extends Model
{
}

class Enrollment extends Model
{
    protected $fillable = ['lesson_id', 'user_id', 'status'];

    public function lesson(): BelongsTo
    {
        return $this->belongsTo(Lesson::class);
    }

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

namespace App\Http\Controllers;

use App\Models\Enrollment;
use App\Models\Lesson;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class EnrollmentController extends Controller
{
    public function store(Request $request, Lesson $lesson): RedirectResponse
    {
        $request->validate(['status' => ['required', 'in:pending,confirmed']]);

        $lesson->enrollments()->create([
            'user_id' => $request->user()->id,
            'status' => $request->string('status')->toString(),
        ]);

        return redirect()->route('lessons.show', $lesson);
    }

    public function show(Enrollment $enrollment)
    {
        $enrollment->load(['lesson', 'user']);

        return view('enrollments.show', [
            'enrollment' => $enrollment,
            'student' => $enrollment->user->name,
            'course' => $enrollment->lesson->title,
        ]);
    }
}

Expected Output

POST /lessons/intro-to-routes/enrollments
  status=confirmed
  INSERT enrollments (lesson_id, user_id, status)
  lesson_id taken from the bound lesson

Enrollment show page
  student = Ada Lovelace
  course = Intro to routes

$lesson->enrollments
  collection of Enrollment models for that lesson only

Line-by-Line Walkthrough

  1. enrollments() is a hasMany. Eloquent assumes the foreign key enrollment.lesson_id and the local key lessons.id.
  2. Calling $lesson->enrollments runs that query and returns a collection.
  3. tags() is belongsToMany for a lesson_tag pivot that has no extra behavior.
  4. Enrollment belongsTo Lesson through lesson_id, and belongsTo User through user_id.
  5. The fillable list allows those three columns for create. It does not allow an arbitrary price field.
  6. store is nested under a lesson URL, so the parent is already bound.
  7. enrollments()->create sets lesson_id from the parent model. You do not pass lesson_id in the array.
  8. user_id is the signed-in student, not a hidden field.
  9. status is validated against two values before the insert.
  10. show eager-loads lesson and user in one extra pair of queries instead of querying inside the template.
  11. The view receives plain strings for the student and the course title.
  12. Accessing $enrollment->user->name without load still works, but it issues a query per enrollment if you do it in a loop. That loop is the N+1 problem the next lesson covers.

Common Pitfalls & Security

Guessing the foreign key name is the usual bug. hasMany(Enrollment::class) expects lesson_id. A column named course_id stays empty and the relation looks like it has no rows.

  • Creating an enrollment with Enrollment::create and a client-supplied lesson_id attaches the student to a course they never opened.
  • Forgetting belongsTo and then reading $enrollment->lesson returns null and the template errors on ->title.
  • A belongsToMany call does not belong on enrollments if you need a status column. You would lose a place to store it unless you add withPivot and still lack a model.
  • Loading every enrollment's user in a loop from the catalog page is an N+1 query. Eager load when you know you will print the names.
  • The relationship is not authorization. A student can be blocked from store even though the method exists.
  • Deleting a lesson without a foreign key or a defined cascade leaves enrollment rows pointing at a missing course.

Best Practices & Modern Standards

Name the relationship methods in camel case and type-hint HasMany or BelongsTo so the editor and Laravel know the return. Let the parent create children through $lesson->enrollments()->create so the foreign key is set in one place.

On Laravel 12 the foreign-key convention is {snake_singular_parent}_id. Override the key arguments only when the column really has another name, and then do it in the relationship so every caller inherits the fix. Add the database foreign key in the migration, not only in Eloquent.

Real-World Use

A student confirms a seat in Intro to routes. The enrollments row stores the lesson, the user, and the status. The receipt page loads both parents and prints the course title and the student name. The lesson page lists $lesson->enrollments for the instructor. Tags on the lesson stay a simple belongsToMany because a tag has no status of its own.

Frequently Asked Questions

When do I use hasMany instead of belongsToMany?

Use hasMany when the child table has its own id and columns, like an enrollment with a status. Use belongsToMany when the middle table only pairs two models, like lessons and tags.

Who sets lesson_id?

$lesson->enrollments()->create() sets it from the parent. If you call Enrollment::query()->create(), you must set lesson_id yourself, and it must not come from an unchecked form field.

Why is the related model null?

The foreign key on the row does not match a parent id, or the relationship method uses the wrong key name. Check the column and the belongsTo arguments. A global scope on the parent can also hide it.

Does defining the method run a query?

No. The query runs the first time you read $lesson->enrollments or call load. Defining the method is free and should stay on the model even if a given request never touches it.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…