How to create a One-To-Many relationship in Laravel?

How to create a One-To-Many relationship in Laravel?

After we learned about the types of relationships within Laravel in the previous part. We discussed the first type of these relationships, which is the One-To-One relationship.

Today we continue the series we started learning about Laravel Eloquent Relationships.

We are talking about the second type, which is called One-To-Many or hasMany.

laravel one to many relationship

How to create a One-To-Many relationship in Laravel?#

How to create a One-To-Many relationship in Laravel?


The One-To-Many relationship is one of the most important types of relationships inside Laravel Eloquent. We also learned in the previous lesson that it is the connection of a row from the first table to more than one row from the second table.

And as a continuation of the practical application (content management system), which we started in the previous lesson. We create a One-To-One relationship between the user and the personal profile.

Today we are going to create One-To-Many relationship between user and post. Each user can own one or more publications.

  • We create Post Model with its own table.

php artisan make:model Post -m        

  • We go to this path database/migrations and modify the publications table by adding some columns as follows:

Schema::create('posts', function (Blueprint $table) {
  $table->id();
  $table->string('title');
  $table->text('body');
  $table->foreignId('user_id')->constrained();
  $table->timestamps();
});        

  • We modify the Post.php file.

protected $fillable = [
  'user_id',
  'title',
  'body',
];        

  • We execute this command to update the database and add the Posts table.

php artisan migrate        

  • We go to the User.php file and set the hasMany relationship.

public function posts() {
    return $this->hasMany(Post::class);
}        
Let’s learn how hasMany works
$this->hasMany(Post::class,
  'user_id' // foreignKey By Default Parent Model + Promary Key
  'id' // localKey => Primary Key In Parent Table By Default is Id
);        

  • We go to the file Post.php and set the inverse relationship belongsTo.

public function user() {
    return $this->belongsTo(User::class);
}        
We have explained belongsTo in this part of the previous article and we are explaining the One-To-One relationship.

  • You can find the repo of this series on github here

要查看或添加评论,请登录

Mahmoud Adel的更多文章

社区洞察

其他会员也浏览了