Skip to main content

Laravel Relationships Explained – A Beginner-Friendly Guide

Laravel Relationships Explained – Eloquent ORM Guide

Laravel's Eloquent ORM provides a beautiful, simple implementation for working with your database. One of its most powerful features is the ability to define relationships between different models. Understanding relationships allows you to link database tables through Eloquent and run complex queries with minimal effort.

📁 What is a Relationship?

A relationship in Laravel refers to the connection between two or more Eloquent models (database tables). Relationships allow us to access related data using simple methods instead of writing complex SQL joins.

💼 When Should You Use Relationships?

Use relationships when:

  • One model is logically related to another (e.g., a User has a Profile)
  • You want to avoid writing raw SQL JOIN queries
  • You want to access related records easily using model methods

1. hasOne

The hasOne relationship defines a one-to-one connection where one model owns another. For example, a User has one Profile.

// User.php
public function profile()
{
    return $this->hasOne(Profile::class);
}

This means: the users table is the parent, and each user has a related profile in the profiles table.

2. belongsTo

The belongsTo relationship is the inverse of hasOne or hasMany. It indicates that the current model belongs to another model.

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

This is defined in the child table (e.g., profiles) that holds the foreign key (user_id).

3. hasMany

The hasMany relationship is used when one model owns multiple records of another model. For example, a Post has many Comments.

// Post.php
public function comments()
{
    return $this->hasMany(Comment::class);
}

Each post can have many comments in the comments table with a post_id foreign key.

4. belongsToMany (Many-to-Many)

This relationship is used when both models can have many of each other. For example, Users can have many Roles, and Roles can be assigned to many Users.

// User.php
public function roles()
{
    return $this->belongsToMany(Role::class);
}
// Role.php
public function users()
{
    return $this->belongsToMany(User::class);
}

This requires a pivot table (usually role_user) with user_id and role_id columns.

5. hasOneThrough

This defines a one-to-one relationship that passes through an intermediate model. Example: A Country has one Leader, but the relation is through a Government model.

// Country.php
public function leader()
{
    return $this->hasOneThrough(Leader::class, Government::class);
}

6. Polymorphic Relationships

These are used when multiple models can own a single model type. Example: Both Posts and Videos can have Comments.

// Comment.php
public function commentable()
{
    return $this->morphTo();
}
// Post.php and Video.php
public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

✅ Conclusion

Laravel Eloquent relationships simplify how you handle related data in your database. With simple methods, you can retrieve associated records and build powerful applications efficiently.

Start with basic relationships like hasOne and hasMany, and gradually explore more advanced types like polymorphic and through relationships.

💬 Have you used these relationships in your Laravel apps? Let me know in the comments!

Comments

Popular posts from this blog

How to Display Flash Messages in EJS using Node.js and Express

Displaying Flash Messages in EJS with Node.js and Express Flash messages are a great way to give users quick feedback — like "Login successful!" or "Please enter all fields!" . In this guide, you’ll learn how to implement them using: express-session connect-flash EJS templating 📦 Step 1: Install Required Packages npm install express express-session connect-flash ejs ⚙️ Step 2: Setup Express App and Middleware const express = require('express'); const session = require('express-session'); const flash = require('connect-flash'); const app = express(); // Set view engine app.set('view engine', 'ejs'); // Middleware app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'yourSecretKey', resave: false, saveUninitialized: true })); app.use(flash()); // Make flash messages available to all views app.use((req, res, next) => { res.lo...

Laravel vs Node.js – Which One to Choose and Why?

Laravel vs Node.js – Which One to Choose and Why? Choosing the right backend technology is one of the most critical decisions in web development. Both Laravel and Node.js are widely adopted and loved by developers, but each comes with its unique strengths. In this post, I’ll compare both to help you decide which one suits your next project better. What is Laravel? Laravel is a PHP-based, open-source web application framework that follows the Model-View-Controller (MVC) architectural pattern. Known for its elegant syntax, Laravel simplifies development with features like authentication , routing , Eloquent ORM , and Blade templating . It’s ideal for developers looking for a structured and robust development experience. What is Node.js? Node.js is a JavaScript runtime built on Chrome’s V8 engine, allowing JavaScript to be used for server-side development. It uses a non-blocking, event-driven architecture, making it highly efficient and scalable ...

15 Must-Know Git Commands for Every Developer

15 Must-Know Git Commands for Every Developer (With Explanations) Whether you're working solo or with a team, Git is an essential tool for modern developers. These commands help manage your codebase effectively and are frequently asked in tech interviews. Below is a curated list of the 15 most useful Git commands every developer should know. Command Description git init Initializes a new Git repository in your project directory. git clone <url> Clones a remote repository to your local machine. git status Shows the status of changes (staged, unstaged, untracked) in the working directory. git add <file> Adds changes in the specified file(s) to the staging area. git commit -m "message" Records the staged changes with a descriptive message. git pull Fetches...