Laravel 9 One to Many Eloquent Relationship Tutorial

Hi Dev,

Here, I will show you laravel 9 one to many relationship examples. it’s a simple example of laravel 9 hasmany relationship examples. step by step explain has many relationship laravel 9. This tutorial will give you a simple example of laravel 9 one to many sync. Alright, let’s dive into the steps.

So in this tutorial, you can understand how to create migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, get all data, delete, update, and everything related to one to many relationships.

In this example, I will create a “posts” table and a “comments” table. both tables are connected with each other. now we will create one to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records, and then how to create records too. So you can also see the database table structure on the below screen.

Laravel 9 One to Many Eloquent Relationship Tutorial

.medrectangle-3-multi-157{border:none!important;display:block!important;float:none;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:250px;padding:0;text-align:center!important}

One to Many Relationship will use “hasMany()” and “belongsTo()” for relation.

Create Migrations:

Now we have to create migration of “posts” and “comments” table. we will also add foreign key with posts table. so let’s create like as below:

posts table migration:

<?php

use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->id();

$table->string("name");

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

};

comments table migration:

.medrectangle-4-multi-155{border:none!important;display:block!important;float:none;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

<?php

use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('comments', function (Blueprint $table) {

$table->id();

$table->foreignId('post_id')->constrained('posts');

$table->string("comment");

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('comments');

}

};

Create Models:

Here, we will create Post and Comment table model. we will also use “hasMany()” and “belongsTo()” for relationship of both model.

app/Models/Post.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

class Post extends Model

{

use HasFactory;

/**

* Get the comments for the blog post.

*

* Syntax: return $this->hasMany(Comment::class, 'foreign_key', 'local_key');

*

* Example: return $this->hasMany(Comment::class, 'post_id', 'id');

*

*/

public function comments()

{

return $this->hasMany(Comment::class);

}

}

app/Models/Comment.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

class Comment extends Model

{

use HasFactory;

/**

* Get the post that owns the comment.

*

* Syntax: return $this->belongsTo(Post::class, 'foreign_key', 'owner_key');

*

* Example: return $this->belongsTo(Post::class, 'post_id', 'id');

*

*/

public function post()

{

return $this->belongsTo(Post::class);

}

}

Retrieve Records:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$comments = Post::find(1)->comments;

dd($comments);

}

}

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsComment;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$post = Comment::find(1)->post;

dd($post);

}

}

Create Records:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

use AppModelsComment;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$post = Post::find(1);

$comment = new Comment;

$comment->comment = "Hi ItSolutionStuff.com";

$post = $post->comments()->save($comment);

}

}

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

use AppModelsComment;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$post = Post::find(1);

$comment1 = new Comment;

$comment1->comment = "Hi ItSolutionStuff.com Comment 1";

$comment2 = new Comment;

$comment2->comment = "Hi ItSolutionStuff.com Comment 2";

$post = $post->comments()->saveMany([$comment1, $comment2]);

}

}

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

use AppModelsComment;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$comment = Comment::find(1);

$post = Post::find(2);

$comment->post()->associate($post)->save();

}

}

I hope you understand of one to many relationship…

1 thought on “Laravel 9 One to Many Eloquent Relationship Tutorial”

Leave a Comment