how to create One to Many Relationship in laravel?

In Laravel, One to Many relationship will use when one DB table related with multiple Database tables. For below example, a article may have multiple notifications.

Introducing One To Many Relationship in Laravel

So in this Article, you can Know how to create Database migration with a Primary key and foreign key schema for one to many relationships, use sync an array with a additional pivot table fields & morphone, Laravel CRUD – create records, get all records, delete, update and all about Information to one to many relationships Eloquent Model.

In this example, I will Make a “articles” DB table and “notifications” DB table. both Database tables are connected with each other. now I will create one to many relationships with each other by using the laravel Eloquent Model. I will first of all make database migration, then model, get all the rows after that how to create rows also. So you can also display database table structure on folowing Example.

#One To Many Relationship example

A one-to-many relationship Eloquent Model is used to define relationships Eloquent Model where a single model owns any amount of other models. For example, a website blog article may have an infinite number of notifications. Such as all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model:

Read Also:  PHP Whatsapp Rest API Send and Recieve WhatsApp Message

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

Create Migrations:

Now I have to create Database migration of “articles” and “notifications” Database table. I will also included foreign key with articles table. therefor let’s start to create like as folowing:

articles Database table migration:

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

notifications table migration:

Schema::create('notifications', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('article_id')->unsigned();
    $table->string("notification");
    $table->timestamps();
    $table->foreign('article_id')->references('id')->on('articles')
        ->onDelete('cascade');
});

Create Models:

Here, I will create Article and Notification Database table model. I will also use “hasMany()” and “belongsTo()” for Database relationship of both(Article and Notification) model.
Article Model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
    /**
     * Get the notifications for the Website Blogs article.
     */
    public function notifications()
    {
        return $this->hasMany(Notification::class);
    }
}

Notification Model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
    /**
     * Get the article that owns the notification.
     */
    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}

Retrieve Records:

Article Records

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

notification Records

$notification = Notification::find(1);
 
$article = $notification->article;
 
dd($article);

Create Records: laravel one to many relationship insert

insert article Records
laravel one to many relationship insert

$article = Article::find(1);
 
$notification = new Notification;
$notification->notification = "Welcome To Pakainfo.com";
 
$article = $article->notifications()->save($notification);

Insert notifications Data

$article = Article::find(1);
 
$notification1 = new Notification;
$notification1->notification = "Welcome To Pakainfo.com Notification 1";
 
$notification2 = new Notification;
$notification2->notification = "Welcome To Pakainfo.com Notification 2";
 
$article = $article->notifications()->saveMany([$notification1, $notification2]);

Final Save data

$notification = Notification::find(1);
$article = Article::find(2);
 
$notification->article()->associate($article)->save();

Defining Inverse One To Many Relationship in Laravel

As we have defined the hasMany relationship on Article model which return the Similar records of Notification model, we can define the inverse relationship on the Notification model.

Read Also:  Laravel Advanced Eloquent Tips and Tricks

Open your app/Notification.php model file and add a fresh method called article() in it which will return the Similar article of a notification.

Once you have included a fresh method article(), update it with the below source code snippet.

// Notification Model
namespace App;

use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    public function article()
    {
    	return $this->belongsTo(Article::class);
    }
}

As you can see, in article() method we are returning a belongs to relation which will return the Similar article of the notification.

Filtering One To Many Relationship

You might want to Advance filter the Similar rows as well as want them to sort when data fetching. You can chain the methods on your data fetching query.

$article = Article::find(1);
$notifications = $article->notifications()
			->where('valutasions', '>', '500')
			->orderBy('name', 'asc')
			->get();

In the above query, I am getting all notifications for a article where the valutasions of each notification should be greater than 500 as well as sorting the rows by name in ascending order.

Read Also:  Laravel 7 Create Seeder From Database Tutorial Example

Deleting a One To Many Relationship

Deleting one to many relationship is the same as I have created them. Firstly I get the parent object which is article and then use the notifications() method to delete all notifications. To delete all notifications for a particular article use below code example.

$article = Article::find(1);
$article->notifications()->delete();

Conclusion

We hope you know All about step by step of laravel one to many relationship with pivot table using Laravel 5/6/7… I have attempt my best to keep this Article as easy as practicable because Laravel Eloquent relationships are the most confuse part. I will recommend you to spend your valuable time on reading and Learning Laravel Official Relations Documentation.