Laravel Eloquent Relationships

Eloquent ORM makes working with database relationships easy. It allows you to define relationships in models and access related data without writing complex SQL joins.


Why Are Relationships Used?

Imagine a blog system:

  • Each User writes many Posts
  • Each Post can have many Comments
  • Each Comment belongs to one User

You could:

  • Query data more easily
  • Automatically fetch related data
  • Update/delete linked records using cascade
  • Represent complex business logic in a clean object-oriented way

Benefits of Using Relationships

Feature

Purpose

Data Integrity

Keeps your foreign keys valid.

Easier Queries

Easily fetch related data with joins or lazy loading.

Object-Oriented Access

Work with objects instead of manual foreign key logic.

Cascade Operations

Save/delete related records automatically.


Relationship Types

Relationship Type

Description

Tables Involved

Example Table Design

One To One (hasOne, belongsTo)

Each employee has one profile.

profiles,employees

profiles.id

employees.profile_id

One To Many (hasMany)

A post can have many comments.

posts,comments

comments.post_id

Many To One (belongsTo)

A comment belongs to a post (reverse of OneToMany).

comments,posts

comments.post_id

Many To Many (belongsToMany)

Students can enroll in many courses, and courses can have many students.

students, courses, course_student

course_student.student_id, course_student.course_id

Has One Through

A manager has one profile through employee.

managers,employees,

profiles

employees.manager_id,

profiles.employee_id

Has Many Through

A manager has many projects through employees.

managers,employees,

projects

employees.manager_id, projects.employee_id

Polymorphic One To One

A profile can have one image; same table can store images for other models too.

images, profiles

images.imageable_id, images.imageable_type

Polymorphic One To Many

A post or video can have many comments (shared table).

comments, posts & videos

comments.commentable_id, comments.commentable_type

Polymorphic Many To Many

A tag can belong to many posts or videos, and posts/videos can have many tags.

tags, posts, videos, taggables

taggables.tag_id, taggables.taggable_id, taggables.taggable_type


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.