DEV Community

Mahmoud Adel
Mahmoud Adel

Posted on • Originally published at laravelspa.site on

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
Enter fullscreen mode Exit fullscreen mode
  • 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();
});
Enter fullscreen mode Exit fullscreen mode
  • We modify the Post.php file.
protected $fillable = [
  'user_id',
  'title',
  'body',
];
Enter fullscreen mode Exit fullscreen mode
  • We execute this command to update the database and add the Posts table.
php artisan migrate
Enter fullscreen mode Exit fullscreen mode
  • We go to the User.php file and set the hasMany relationship.
public function posts() {
    return $this->hasMany(Post::class);
}
Enter fullscreen mode Exit fullscreen mode

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
);
Enter fullscreen mode Exit fullscreen mode
  • We go to the file Post.php and set the inverse relationship belongsTo.
public function user() {
    return $this->belongsTo(User::class);
}
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)