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:
- What is a One-to-Many Relationship?
- Setting Up a One-to-Many Relationship
- Creating Migrations & Models
- Defining Relationships in Eloquent
- Inserting & Retrieving Data
- Eager Loading (Optimizing Queries)
- 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:
userstable →id,namepoststable →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:
- One-to-Many Relationship → One model owns multiple instances of another model.
hasMany()&belongsTo()→ Define the relationship in models.- Eager Loading (
with()) → Optimizes database queries. - 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! 👇
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.