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:

Schema::create('article', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $table->timestamps();
});

status table migration:

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');
});

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.

READ :  Angular ng-repeat reverse Example - reverse filter

Article Model:

hasMany(Status::class);
    }
}

Status Model:
belongsTo(Article::class);
    }
}

Retrieve Records:

$article = Article::find(1);
$status = $article->status;
dd($status);

$status = Status::find(1);
 
$article = $status->article;
 
dd($article);

Create Records:

$article = Article::find(1);
$status = new Status;
$status->status = "Hi ItSolutionStuff.com";
 
$article = $article->status()->save($status);

$article = Article::find(1);
 
$status1 = new Status;
$status1->status = "Hi ItSolutionStuff.com Status 1";
 
$status2 = new Status;
$status2->status = "Hi ItSolutionStuff.com Status 2";
 
$article = $article->status()->saveMany([$status1, $status2]);

$status = Status::find(1);
$article = Article::find(2);
 
$status->article()->associate($article)->save();

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.

READ :  Angular get Dynamic Templates

Leave a Reply

Your email address will not be published. Required fields are marked *