Laravel Eloquent One to Many Relationship Tutorial with Example
A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. This article last tested on Laravel 8.x.
In this article, I’ll show one to many and it’s reverse relationship. I’ll create a relation between Post and Comment models. Here’s the schema design:
Table of Contents
- Install Laravel and Basic Configurations
- Create Migration and Model
- Set One To Many Relationship
- Inverse Of The Relationship
- Usage
Install Laravel and Basic Configurations
Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.
Create Migration and Model
Let’s create post and command models with migration files:
# create post model & migration
php artisan make:model Post -m
# create comment model & migration
php artisan make:model Comment -m
Now open the posts migration file from database>migrations
directory and update up()
function:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('body');
$table->timestamps();
});
}
Like posts migration file, update comment migration’s up()
function:
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->string('comment');
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
}
We have set post_id as a foreign key. So the comment/s will be deleted if we delete the post.
Set One To Many Relationship
A blog post may have an infinite number of comments. We have to use hasMany
function to get comments. Open Post model and set relation like:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
/**
* Get the comments for the post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
// note: we can also include comment model like: 'App\Models\Comment'
}
}
Inverse Of The Relationship
We can access the Comment
model from our Post
. Now, let’s define a relationship on the Comment
model that will let us access the Post
that owns the comments. We can define the inverse of a hasMany
relationship using the belongsTo
method.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use HasFactory;
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
Usage
Now let’s have a look at some usage of this relationship.
Insert Records:
// insert 1 post
$post = new Post();
$post->title = "Test post";
$post->body = "Post body goes here";
$post->save();
// insert 2 comments
$comment = new Comment();
$comment->post_id = 1;
$comment->comment = "Comment text 1";
$comment->save();
$comment = new Comment();
$comment->post_id = 1;
$comment->comment = "Comment text 2";
$comment->save();
Retrive Records:
// get all comments of a post
$id = 1;
$post = Post::find($id);
$all_comments = $post->comments;
dd($all_comments);
// get the post of a comment
$id = 1;
$comment = Comment::find($id);
$post = $comment->post;
dd($post);
To get more details of one to one eloquent relationship, you can read Laravel’s official documentation.
The tutorial is over. Thanks for reading.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.