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.

Similar Posts