Laravel One to Many Eloquent Relationship Example

Today, We want to share with you Laravel One to Many Eloquent Relationship Example.
In this post we will show you laravel one to many relationship example, hear for one to many relationship laravel model we will give you demo and example for implement.
In this post, we will learn about one to many relationship laravel 5.6 with an example.

Laravel One to Many Eloquent Relationship Demo

Now, I will make new Article and some more Status table model. I shall also use “hasMany()” as well as “belongsTo()” for Laravel One to Many Eloquent Relationship of both model.

Article Model:

Create Migrations:

article table migration:
[php]
Schema::create(‘article’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(“name”);
$table->timestamps();
});
[/php]

READ :  php cURL Tutorial Send HTTP Requests Example

status table migration:
[php]
Schema::create(‘status’, function (Blueprint $table) {
$table->increments(‘id’);
$table->integer(‘article_id’)->unsigned();
$table->string(“status”);
$table->timestamps();
$table->foreign(‘article_id’)->references(‘id’)->on(‘article’)
->onDelete(‘cascade’);
});
[/php]

Make Models:

Now, I will make new Article and some more Status table model. I shall also use “hasMany()” as well as “belongsTo()” for Laravel One to Many Eloquent Relationship of both model.

Article Model:
[php]
hasMany(Status::class);
}
}
[/php]
Status Model:
[php]
belongsTo(Article::class);
}
}
[/php]

Retrieve Records:

[php]
$article = Article::find(1);
$status = $article->status;
dd($status);
[/php]

[php]
$status = Status::find(1);

$article = $status->article;

dd($article);
[/php]

Create Records:

[php]
$article = Article::find(1);
$status = new Status;
$status->status = “Hi ItSolutionStuff.com”;

$article = $article->status()->save($status);
[/php]
[php]
$article = Article::find(1);

$status1 = new Status;
$status1->status = “Hi ItSolutionStuff.com Status 1”;

$status2 = new Status;
$status2->status = “Hi ItSolutionStuff.com Status 2”;

READ :  Vuejs Custom Filters Dependent MultiSelect

$article = $article->status()->saveMany([$status1, $status2]);
[/php]
[php]
$status = Status::find(1);
$article = Article::find(2);

$status->article()->associate($article)->save();
[/php]

jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about create hasmany relationship laravel.
I would like to have feedback on my Infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Reply

Your email address will not be published.