Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 35 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Introduction to Database Relationships in Laravel

Learn how to define hasMany and belongsTo relationships in Laravel. Master Eloquent database relationships to link models and access related data with ease.

LaravelEloquentDatabaseRelationshipsPHPWeb Developmentbackend

Previously in this course, we covered performing basic CRUD operations in Laravel with Eloquent and displaying real database records in our views. So far, our Task Manager has treated tasks as isolated records. In the real world, data is rarely isolated; tasks belong to projects, users have profiles, and authors write posts.

In this lesson, we’ll move beyond single-table operations by learning how to link our models together using Eloquent relationships.

Understanding Database Relationships

At their core, database relationships allow us to define how different tables in our database interact. When we use Eloquent, we represent these interactions as methods on our model classes.

The most common relationship is the "One-to-Many" association. Think of our Task Manager: one Category (like "Work" or "Personal") can contain many Tasks. Conversely, each individual task belongs to exactly one category.

The hasMany Relationship

The hasMany relationship defines the "one" side of the association. It tells Laravel that a model "owns" a collection of other records.

In our Category model, we define it like this:

PHP
#6A9955">// app/Models/Category.php
public function tasks()
{
    return $this->hasMany(Task::class);
}

By convention, Laravel assumes that the tasks table has a category_id column that points back to the categories table.

The belongsTo Relationship

The belongsTo relationship defines the "many" side of the association. It tells Laravel that a model is "owned by" another model.

In our Task model, we define it like this:

PHP
#6A9955">// app/Models/Task.php
public function category()
{
    return $this->belongsTo(Category::class);
}

This tells Eloquent, "Look for a category_id on the tasks table to find the associated Category record."

Accessing Related Data

Once these relationships are defined, accessing related data becomes incredibly intuitive. You treat the relationship method as a property, and Eloquent handles the underlying SQL query for you.

If you have a task and want to find its category, you simply call:

PHP
$task = Task::find(1);
echo $task->category->name;

If you have a category and want to list all tasks within it:

PHP
$category = Category::find(1);
foreach ($category->tasks as $task) {
    echo $task->title;
}

Hands-on Exercise: Link Tasks to Categories

Let’s advance our Task Manager project. We want to categorize our tasks.

  1. Create the Migration: Create a categories table with a name column.
  2. Add Foreign Key: In your tasks migration, add a foreignId column: $table->foreignId('category_id')->constrained();.
  3. Define Relationships: Add the tasks() method to the Category model and the category() method to the Task model as shown above.
  4. Test in Tinker: Run php artisan tinker and try:
    PHP
    $category = \App\Models\Category::create(['name' => 'Work']);
    $task = \App\Models\Task::find(1);
    $task->category()->associate($category);
    $task->save();

Common Pitfalls

  • Missing Foreign Keys: If your database table is named tasks, Laravel expects the foreign key to be category_id. If you use a different naming convention, you must explicitly pass the column name as the second argument to the relationship method.
  • Accessing as a Method vs. Property: Remember: $task->category (property) executes the relationship and returns the result (the category object), while $task->category() (method) returns the query builder, allowing you to chain further constraints like where('active', true).
  • The N+1 Problem: If you loop through 50 tasks and call $task->category->name for each, Laravel will run 51 database queries. We will solve this in the next lesson using Eager Loading.

Recap

We’ve moved beyond flat database structures by defining hasMany and belongsTo associations. These Eloquent tools allow us to traverse our data graph naturally. By linking our tasks to categories, we’ve made our data structure more robust and ready for more complex features.

Up next: Querying Related Data to optimize performance and master complex filtering.

Previous lessonTask Manager: Completing CRUD FunctionalityNext lesson Querying Related Data
Back to Blog

Similar Posts

LaravelJune 25, 20264 min read

Querying Related Data: Mastering Eager Loading in Laravel

Stop the N+1 query problem in its tracks. Learn how to use eager loading in Laravel to keep your application fast and efficient as your data grows.

Read more
LaravelJune 25, 20263 min read

Introduction to Route Model Binding in Laravel

Stop manually querying the database in your controllers. Learn how route model binding automatically injects Eloquent models into your routes.

Part of the course

Laravel Fundamentals: From Zero to Your First App

beginner · Lesson 35 of 52

  1. 1

    Setting Up the Local Development Environment

    4 min
  2. 2

    Installing Laravel and Exploring Directory Structure

    3 min
  3. 3

    Understanding the .env File and Configuration

    3 min
Read more
LaravelJune 25, 20263 min read

Performing Basic CRUD Operations in Laravel with Eloquent

Master database operations with our guide to CRUD in Laravel. Learn how to save, fetch, update, and delete records using the powerful Eloquent ORM.

Read more
  • 4

    The Laravel Application Lifecycle

    4 min
  • 5

    Initializing the Task Manager Project

    3 min
  • 6

    Defining Basic Web Routes

    4 min
  • 7

    Using Route Parameters

    3 min
  • 8

    Creating Your First Controller

    3 min
  • 9

    Returning Responses and Redirects

    3 min
  • 10

    Task Manager: Implementing the Task List Route

    3 min
  • 11

    Introduction to Blade Templating

    3 min
  • 12

    Using Blade Layouts and Sections

    3 min
  • 13

    Implementing Blade Partials

    4 min
  • 14

    Mastering Blade Directives for Loops and Conditionals

    3 min
  • 15

    Task Manager: Building the User Interface

    3 min
  • 16

    Understanding Database Migrations

    3 min
  • 17

    Working with Eloquent Models

    3 min
  • 18

    Performing Basic CRUD Operations

    3 min
  • 19

    Seeding the Database

    3 min
  • 20

    Task Manager: Displaying Real Database Records

    3 min
  • 21

    Capturing User Input from Forms

    4 min
  • 22

    Introduction to Laravel Validation

    3 min
  • 23

    Customizing Validation Error Messages

    3 min
  • 24

    Using Form Requests for Validation

    3 min
  • 25

    Introduction to Authentication

    4 min
  • 26

    Protecting Routes with Middleware

    3 min
  • 27

    Understanding CSRF Protection

    3 min
  • 28

    Preventing Mass Assignment

    3 min
  • 29

    Task Manager: Securing the Application

    3 min
  • 30

    Introduction to Route Model Binding

    3 min
  • 31

    Updating Existing Records

    3 min
  • 32

    Deleting Records

    3 min
  • 33

    Using Named Routes

    3 min
  • 34

    Task Manager: Completing CRUD Functionality

    3 min
  • 35

    Introduction to Database Relationships

    3 min
  • 36

    Querying Related Data

    4 min
  • 37

    Handling File Uploads

    3 min
  • 38

    Using Flash Messages for User Feedback

    3 min
  • 39

    Task Manager: Adding Status and Priorities

    3 min
  • 40

    Introduction to Artisan Commands

    3 min
  • 41

    Debugging with Laravel Tinker

    Coming soon
  • 42

    Understanding Service Providers

    Coming soon
  • 43

    Using View Composers

    Coming soon
  • 44

    Task Manager: Refactoring for Clean Code

    Coming soon
  • 45

    Introduction to Testing

    Coming soon
  • 46

    Testing Forms and Validation

    Coming soon
  • 47

    Using Database Transactions

    Coming soon
  • 48

    Handling Global Exceptions

    Coming soon
  • 49

    Preparing for Production

    Coming soon
  • 50

    Environment Security Best Practices

    Coming soon
  • 51

    Managing Assets in Production

    Coming soon
  • 52

    Task Manager: Deployment Preparation

    Coming soon
  • View full course