Laravel 12 One-to-Many Relationship: A Complete Guide with Examples

Laravel 12 One-to-Many Relationship: A Complete Guide with Examples

In Laravel 12, one-to-many (1:N) relationships are used when a single model owns multiple instances of another model.

Real-World Examples

  • A User has many Posts.
  • A Category has many Products.

In this blog, we’ll cover:

  1. What is a One-to-Many Relationship?
  2. Setting Up a One-to-Many Relationship
  3. Creating Migrations & Models
  4. Defining Relationships in Eloquent
  5. Inserting & Retrieving Data
  6. Eager Loading (Optimizing Queries)
  7. Practical Example: Blog Post System

1. What is a One-to-Many Relationship?

A one-to-many (1:N) relationship means:

  • One record in Table A can have multiple related records in Table B.
  • Example:
    • users table → id, name
    • posts table → id, user_id, title, content

Here, one user can have many posts, but each post belongs to only one user.


2. Setting Up a One-to-Many Relationship

Step 1: Create Laravel Project (Skip if Already Done)

composer create-project laravel/laravel one-to-many-demo
cd one-to-many-demo

Step 2: Configure Database

Edit .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_one_to_many
DB_USERNAME=root
DB_PASSWORD=

3. Creating Migrations & Models

A. Create users Table (Default in Laravel)

Laravel already provides a users migration.

B. Create posts Table

Run:

php artisan make:migration create_posts_table

Edit the migration:

// database/migrations/xxxx_create_posts_table.php
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id'); // Foreign key
    $table->string('title');
    $table->text('content');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Run migrations:

php artisan migrate

C. Create Models

Laravel already has a User model (app/Models/User.php).

Now, create a Post model:

php artisan make:model Post
// app/Models/Post.php
protected $fillable = ['user_id', 'title', 'content'];

4. Defining the One-to-Many Relationship

A. User → Has Many Posts

In User.php:

public function posts()
{
    return $this->hasMany(Post::class);
}
  • hasMany() defines the 1:N relationship.

B. Post → Belongs To User

In Post.php:

public function user()
{
    return $this->belongsTo(User::class);
}
  • belongsTo() defines the inverse relationship.

5. Inserting & Retrieving Data

A. Create a User with Multiple Posts

use App\Models\User;
use App\Models\Post;

// Create a User
$user = User::create([
    'name' => 'Jane Doe',
    'email' => 'jane@example.com',
    'password' => bcrypt('password'),
]);

// Create Posts for the User
$user->posts()->createMany([
    ['title' => 'First Post', 'content' => 'This is my first post.'],
    ['title' => 'Second Post', 'content' => 'This is my second post.'],
]);

B. Retrieve User’s Posts

$user = User::find(1);
$posts = $user->posts; // Gets all posts
foreach ($posts as $post) {
    echo $post->title; // Output: "First Post", "Second Post"
}

C. Retrieve Post’s User

$post = Post::find(1);
$user = $post->user; // Gets the user
echo $user->name; // Output: "Jane Doe"

6. Eager Loading (Optimizing Queries)

Avoid the N+1 problem when fetching multiple users and their posts:

// Without Eager Loading (Runs N+1 queries)
$users = User::all();
foreach ($users as $user) {
    foreach ($user->posts as $post) {
        echo $post->title; // Runs a query for each user
    }
}

// With Eager Loading (Runs 2 queries only)
$users = User::with('posts')->get();
foreach ($users as $user) {
    foreach ($user->posts as $post) {
        echo $post->title; // No extra queries
    }
}

7. Practical Example: Blog Post System

Step 1: Create Routes

// routes/web.php
Route::get('/user-posts', function () {
    $user = User::with('posts')->first();
    return view('user-posts', compact('user'));
});

Step 2: Create a Blade View

<!-- resources/views/user-posts.blade.php -->
<h1>{{ $user->name }}'s Posts</h1>
<ul>
    @foreach ($user->posts as $post)
        <li>
            <strong>{{ $post->title }}</strong>
            <p>{{ $post->content }}</p>
        </li>
    @endforeach
</ul>

Step 3: Test in Browser

Run:

php artisan serve

Visit:

http://127.0.0.1:8000/user-posts

You’ll see the user’s posts!


Conclusion

✅ Key Takeaways:

  1. One-to-Many Relationship → One model owns multiple instances of another model.
  2. hasMany() & belongsTo() → Define the relationship in models.
  3. Eager Loading (with()) → Optimizes database queries.
  4. Practical Use Case → Blog post system.

Next Steps:

  • Try many-to-many (e.g., Posts & Tags).
  • Explore polymorphic relationships.

🚀 Happy Coding!

📌 Need help? Drop your questions below! 👇

Discussion

Comments

No comments yet. Be the first to comment.

Browse the project library

Projects to explore next

Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.

All projects