This quick reference is a practical guide that explains the most common relationship types with simple examples. Covering hasOne, hasMany, belongsTo, belongsToMany and polymorphic relationships along with eager loading and performance tips, it gives developers a fast and accurate reference.
Laravel 12 requires PHP 8.2+ and embraces modern approaches to migration syntax, model structure and relationship definitions. All examples in this guide follow current Laravel 12+ conventions.
1. One to One Relationship
Scenario
2 models: Student (student) and Profile (profile), 2 tables: students and profiles.
Business Rules:
A Student can have one Profile.
A Profile can belong to only one Student.
Relationship Details: profiles table holds the student_id foreign key.
Eloquent Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
class Student extends Model
{
protected $fillable = ['name'];
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Profile extends Model
{
protected $fillable = ['bio', 'avatar', 'student_id'];
public function student(): BelongsTo
{
return $this->belongsTo(Student::class);
}
}
Migration
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('bio')->nullable();
$table->string('avatar')->nullable();
$table->foreignId('student_id')->nullable()->constrained()->nullOnDelete();
$table->timestamps();
});
Creating Records
// Student üzerinden Profile ilişkisi kur
$student->profile()->save($profile);
// Profile üzerinden Student ilişkisi kur
$profile->student()->associate($student)->save();
Querying Records
// Student'ın profilini getir
$student->profile;
// Profile'ın öğrencisini getir
$profile->student;
2. One to Many Relationship
Scenario
2 models: Classroom (classroom) and Student (student), 2 tables: classrooms and students.
Business Rules:
A Classroom can have many Students.
A Student can belong to only one Classroom.
Relationship Details: students table holds the classroom_id foreign key.
Eloquent Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Classroom extends Model
{
protected $fillable = ['name', 'capacity'];
public function students(): HasMany
{
return $this->hasMany(Student::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Student extends Model
{
protected $fillable = ['name', 'classroom_id'];
public function classroom(): BelongsTo
{
return $this->belongsTo(Classroom::class);
}
}
Migration
Schema::create('classrooms', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('capacity');
$table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('classroom_id')->nullable()->constrained()->nullOnDelete();
$table->timestamps();
});
Creating Records
// Classroom'a birden fazla Student ekle
$classroom->students()->saveMany([$student1, $student2]);
// Tek bir Student ekle
$classroom->students()->save($student);
// Student'a Classroom ata
$student->classroom()->associate($classroom)->save();
Querying Records
// Classroom'daki tüm öğrencileri getir
$classroom->students;
// Student'ın sınıfını getir
$student->classroom;
3. Polymorphic One to Many Relationship
Scenario
3 models: Teacher (teacher), Principal (principal) and Announcement (announcement), 3 tables: teachers, principals, announcements.
Business Rules:
A Teacher can publish many Announcements.
A Principal can publish many Announcements.
An Announcement can be published by only one author (a Teacher or a Principal).
Relationship Details: announcements table holds the author_id and author_type columns. "author" (author) is the shared polymorphic name covering the Teacher and Principal models.
Eloquent Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Teacher extends Model
{
protected $fillable = ['name'];
public function announcements(): MorphMany
{
return $this->morphMany(Announcement::class, 'author');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Principal extends Model
{
protected $fillable = ['name'];
public function announcements(): MorphMany
{
return $this->morphMany(Announcement::class, 'author');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Announcement extends Model
{
protected $fillable = ['title', 'body'];
public function author(): MorphTo
{
return $this->morphTo();
}
}
Migration
Schema::create('teachers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('principals', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('announcements', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
// author_id (unsignedBigInteger) + author_type (string) sütunlarını otomatik oluşturur
$table->nullableMorphs('author');
$table->timestamps();
});
Creating Records
// Teacher veya Principal üzerinden Announcement ekle
$teacher->announcements()->saveMany([$announcement1, $announcement2]);
$principal->announcements()->saveMany([$announcement1, $announcement2]);
// Tek bir Announcement için
$teacher->announcements()->save($announcement);
$principal->announcements()->save($announcement);
// Announcement üzerinden yazar ilişkisi kur
$announcement1->author()->associate($teacher)->save();
$announcement2->author()->associate($principal)->save();
Querying Records
// Teacher veya Principal'ın duyurularını getir
$teacher->announcements;
$principal->announcements;
// Announcement'ın yazarını getir (Teacher veya Principal instance'ı döner)
$announcement->author;
4. Many to Many Relationship
Scenario
2 models: Student (student) and Course (course), 3 tables: students, courses and the pivot table course_student.
Business Rules:
A Student can enroll in many Courses.
A Course can have many Students enrolled.
Relationship Details: course_student pivot table holds the student_id and course_id columns.
Eloquent Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Student extends Model
{
protected $fillable = ['name'];
public function courses(): BelongsToMany
{
return $this->belongsToMany(Course::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Course extends Model
{
protected $fillable = ['title', 'description'];
public function students(): BelongsToMany
{
return $this->belongsToMany(Student::class);
}
}
Migration
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description')->nullable();
$table->timestamps();
});
Schema::create('course_student', function (Blueprint $table) {
$table->id();
$table->foreignId('course_id')->constrained()->cascadeOnDelete();
$table->foreignId('student_id')->constrained()->cascadeOnDelete();
});
Creating Records
// Student'ı birden fazla Course'a kaydet
$student->courses()->attach([$course1->id, $course2->id]);
// Mükerrer kayıtları önlemek için sync() kullan
$student->courses()->sync([$course1->id, $course2->id]);
// Course'a birden fazla Student ekle
$course->students()->attach([$student1->id, $student2->id]);
// Mükerrer kayıtları önlemek için sync() kullan
$course->students()->sync([$student1->id, $student2->id]);
Querying Records
// Student'ın kayıtlı olduğu tüm dersleri getir
$student->courses;
// Course'a kayıtlı tüm öğrencileri getir
$course->students;
5. Polymorphic Many to Many Relationship
Scenario
3 models: Student (student), Teacher (teacher) and Event (event), 4 tables: students, teachers, events and attendees.
Business Rules:
A Student can attend many Events.
A Teacher can attend many Events.
An Event can have many participants (Students and/or Teachers).
Relationship Details: attendees pivot table holds the participant_id, participant_type and event_id columns. "participant" (participant) is the shared polymorphic name covering the Student and Teacher models.
Eloquent Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
class Student extends Model
{
protected $fillable = ['name'];
public function events(): MorphToMany
{
return $this->morphToMany(Event::class, 'participant');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
class Teacher extends Model
{
protected $fillable = ['name'];
public function events(): MorphToMany
{
return $this->morphToMany(Event::class, 'participant');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphedByMany;
class Event extends Model
{
protected $fillable = ['title', 'date'];
public function students(): MorphedByMany
{
return $this->morphedByMany(Student::class, 'participant');
}
public function teachers(): MorphedByMany
{
return $this->morphedByMany(Teacher::class, 'participant');
}
}
Migration
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('teachers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('events', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->date('date');
$table->timestamps();
});
Schema::create('attendees', function (Blueprint $table) {
$table->id();
$table->morphs('participant'); // participant_id + participant_type
$table->foreignId('event_id')->constrained()->cascadeOnDelete();
});
Creating Records
// Student veya Teacher'ı Event'lere kaydet
$student->events()->saveMany([$event1, $event2]);
$teacher->events()->saveMany([$event1, $event2]);
// Tek bir Event için
$student->events()->save($event1);
$teacher->events()->save($event1);
// Event'e katılımcı ekle
$event->students()->attach([$student1->id, $student2->id]);
$event->teachers()->attach([$teacher1->id, $teacher2->id]);
// Mükerrer kayıtları önlemek için sync() kullan
$event->students()->sync([$student1->id, $student2->id]);
$event->teachers()->sync([$teacher1->id, $teacher2->id]);
Querying Records
// Student veya Teacher'ın katıldığı tüm etkinlikleri getir
$student->events;
$teacher->events;
// Event'in tüm katılımcılarını getir
$event->students;
$event->teachers;
Laravel 12 Syntax Changes — Summary
Old Syntax (Laravel 5.x) | New Syntax (Laravel 12) |
|---|---|
|
|
|
|
|
|
No return type: | With return type: |
Manual |
|
Bonus: Practical Tips
Eager Loading — Avoid the N+1 Problem
The N+1 problem occurs when a separate query runs for every record in a collection. With with(), all related data is loaded in a single query.
// İlişkiyi önceden yükle
$classrooms = Classroom::with('students')->get();
$students = Student::with(['classroom', 'courses'])->get();
Lazy Eager Loading
Used to load a relationship after the model has already been retrieved.
$student->loadMissing('courses');
Querying Based on Relationship Existence
// En az bir öğrencisi olan sınıfları getir
Classroom::has('students')->get();
// 10'dan fazla öğrencisi olan sınıfları getir
Classroom::has('students', '>=', 10)->get();
// İlişki koşuluna göre filtrele
Classroom::whereHas('students', function ($query) {
$query->where('name', 'Ali');
})->get();
Adding Extra Columns to the Pivot Table (Many to Many)
// Migration'da ek sütunlar tanımla
Schema::create('course_student', function (Blueprint $table) {
$table->id();
$table->foreignId('course_id')->constrained()->cascadeOnDelete();
$table->foreignId('student_id')->constrained()->cascadeOnDelete();
$table->decimal('grade', 4, 2)->nullable(); // not sütunu
$table->timestamp('enrolled_at')->nullable(); // kayıt tarihi
});
// Model'de withPivot() ile tanımla
public function courses(): BelongsToMany
{
return $this->belongsToMany(Course::class)
->withPivot('grade', 'enrolled_at')
->withTimestamps();
}
// Pivot verisine eriş
foreach ($student->courses as $course) {
echo $course->pivot->grade;
echo $course->pivot->enrolled_at;
}
Attaching Records with Pivot Data
// Ekstra pivot verisiyle ilişki kur
$student->courses()->attach($course->id, [
'grade' => 95.5,
'enrolled_at' => now(),
]);