Laravel 9 One To Many Relationship Example

Websolutionstuff | Apr-02-2022 | Categories : Laravel PHP

In this article, we will see laravel 9 one to many relationship example. Also, you can use one to many relationships in laravel 6 and laravel 7, and laravel 8. One to many relationships is used to define relationships where a single model is a parent to one or more child models. For one to many relationship use hasMany and belongsTo method in the model for access to each other model.

So, let's see one to many relationship in laravel 9, laravel 9 eloquent relationships example, laravel 9 hasMany example, laravel 9 belongsto relationship example

Also, we will create migration with a foreign key, retrieve records using the model, insert new records, sync with a pivot table, etc.

Now, We will create Articles and Comments tables and connect both table with each other and create one to many relationships with each other by using the laravel model. To define this relationship, we will place a comments functions on the Article model. The comments the function should call the hasMany method and return its result.

laravel_9_one_to_many_relationship

 

 

Create Migration

In this step, we have to create migration for articles and comments table. we will also add a foreign key to the articles table.

Create Migration of Articles Table

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

    $table->increments('id');

    $table->string('name');

    $table->string('slug');

    $table->timestamps();

});

Create Migration of Comments Table with Foreign Key

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

    $table->increments('id');

    $table->integer('article_id')->unsigned();

    $table->text('comments');

    $table->timestamps();


    $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');

});

 

 

Create Model and Add Relationship on Both Model

In the Article model, we can create comments() function and add relation of Comment model using hasMany method.

Article Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    /**
     * Get the comments for the article.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

Comment Model :

Now that we can access all of an article's comments, let's define a relationship to allow a comment to access its parent article. To define the inverse of a hasMany relationship, define a relationship method on the child model which calls the belongsTo method.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the article that owns the comment.
     */
    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}

In the above example, Eloquent will attempt to find a Article model that has an id which matches the article_id column on the Comment model. So, in this example, Eloquent will assume the Article model's foreign key on the comments table is article_id.

 

 

If the foreign key on the Comments model is not article_id, you may pass a custom key name as the second argument to the belongsTo method.

/**
 * Get the article that owns the comment.
 */
public function article()
{
    return $this->hasMany(Comment::class, 'foreign_key');
 
    return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
}

 

Retrieve Records using Model :

Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. So, here we can use the Article model with the comments function.

$comments = Article::find(5)->comments;
 
foreach ($comments as $comment) {
    //
}
$comment = Comment::find(7);
 
$article = $comment->article->name;

 

Create Records using Model

 Now, we will add records in the comment table using the article.

$article = Article::find(1);
 
$comment = new Comment;
$comment->comments = "One To Many Exmaple";
 
$article->comments()->save($comment);

 

 

One To Many Relationship with Query

In all relationships, you can use conditions to query with the model.

$comment = Article::find(1)->comments()
                    ->where('name', 'websolutionstuff')
                    ->first();

 


You might also like :

Recommended Post
Featured Post
Introduction of Node.js Modules
Introduction of Node.js Module...

In this tutorial I will give you information about Introduction of Node.js Modules. Node.js modules provide a way t...

Read More

Sep-10-2021

Laravel Datatables Example
Laravel Datatables Example

In this example, I will show you how to implement/install data tables in laravel. Datatables provides users with many fu...

Read More

May-16-2020

Target Class Does Not Exist In Laravel 8
Target Class Does Not Exist In...

In this article, we will see target class does not exist in laravel 8 and how to fix target class not found in...

Read More

Sep-23-2020

How To Validate Upload File Type Using Javascript
How To Validate Upload File Ty...

This article will show us how to validate upload file type using javascript. Using this post we can easily check the sel...

Read More

Aug-03-2020