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 Use L5-Swagger for API Documentation in Laravel

Integrating Swagger in Laravel: Annotations, JSON, and YAML What is Swagger? Swagger (OpenAPI) is a powerful tool for generating interactive API documentation. It helps developers understand and test your API easily. ✅ Step-by-Step Guide to Setup L5-Swagger 1. Install L5-Swagger Package composer require "darkaonline/l5-swagger" 2. Publish Config & View Files This command publishes the config file to config/l5-swagger.php : php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 3. Configure Swagger (Optional) Edit the file config/l5-swagger.php to update: API Title Base Path Directories to scan for annotations 4. Add Swagger Annotations Add these before your controller class: /** * @OA\Info( * version="1.0.0", * title="Your API Title", * description=...

How to Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. ๐Ÿงพ Prerequisites Node.js installed Basic knowledge of Express.js Internet connection ๐Ÿ“ Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js ๐Ÿ“ฆ Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon ๐Ÿ” Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } ๐Ÿ” Step 2: Create a .env File Create a .env file a...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. ๐Ÿš€ Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup ๐Ÿ“ Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs ๐Ÿง  How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...