Kritim Yantra
Apr 06, 2025
In Laravel 12, one-to-many (1:N) relationships are used when a single model owns multiple instances of another model.
In this blog, we’ll cover:
A one-to-many (1:N) relationship means:
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.
composer create-project laravel/laravel one-to-many-demo
cd one-to-many-demo
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=
users
Table (Default in Laravel)Laravel already provides a users
migration.
posts
TableRun:
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
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'];
In User.php
:
public function posts()
{
return $this->hasMany(Post::class);
}
hasMany()
defines the 1:N relationship.In Post.php
:
public function user()
{
return $this->belongsTo(User::class);
}
belongsTo()
defines the inverse relationship.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.'],
]);
$user = User::find(1);
$posts = $user->posts; // Gets all posts
foreach ($posts as $post) {
echo $post->title; // Output: "First Post", "Second Post"
}
$post = Post::find(1);
$user = $post->user; // Gets the user
echo $user->name; // Output: "Jane Doe"
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
}
}
// routes/web.php
Route::get('/user-posts', function () {
$user = User::with('posts')->first();
return view('user-posts', compact('user'));
});
<!-- 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>
Run:
php artisan serve
Visit:
http://127.0.0.1:8000/user-posts
You’ll see the user’s posts!
✅ Key Takeaways:
hasMany()
& belongsTo()
→ Define the relationship in models. with()
) → Optimizes database queries. 🚀 Happy Coding!
📌 Need help? Drop your questions below! 👇
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google