Laravel one to many eloquent relationship example; Through this tutorial, i am going to show you what is one to many eloquent and how to use one to many eloquent relationship in laravel apps.
A one-to-many relationship is a very basic type of database relationship. When one table refers to many rows in another table that is called a one-to-many relationship.
Laravel One to Many Eloquent Relationship Example Tutorial
- Create Migrations
- posts table migration
- comments table migration
- Create Models
- Post Model
- Comment Model
- Retrieve Records
- Create Records
Create Migrations
To create migration of “posts” and “comments” table. And add foreign key with posts table:
posts table migration
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});
comments table migration
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string("comment");
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
});
Create Models
To create Post and Comment table model. And use “hasMany()” and “belongsTo()” for relationship of both model.
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
Retrieve Records
To fetch data using one to many eloquent relationship in laravel apps; as follows:
$post = Post::find(1); $comments = $post->comments; dd($comments);
$comment = Comment::find(1); $post = $comment->post; dd($post);
Create Records
To create data using one to many eloquent relationship in laravel apps; as follows:
$post = Post::find(1); $comment = new Comment; $comment->comment = "Hi Laratutorials.com"; $post = $post->comments()->save($comment);
$post = Post::find(1); $comment1 = new Comment; $comment1->comment = "Hi Laratutorials.com Comment 1"; $comment2 = new Comment; $comment2->comment = "Hi Laratutorials.com Comment 2"; $post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1); $post = Post::find(2); $comment->post()->associate($post)->save();