Example of a One-to-Many Relationship in Laravel 9 ,2024

In this article, we will explore the concept of a one-to-many relationship in Laravel 9 with practical examples. The one-to-many relationship is a fundamental concept in database design, where a single record in one table (the parent) can be associated with multiple documents in another table (the child).

The one-to-many relationship is also applicable in previous versions of Laravel, including Laravel 6, Laravel 7, and Laravel 8.

To establish a one-to-many relationship, we utilize the hasMany and belongsTo methods in the Laravel model, allowing easy access to related records in both directions.

Let’s dive into a step-by-step Laravel 9 example that illustrates the one-to-many relationship. We will create two tables, namely Articles and Comments, and establish a connection between them using Laravel models to demonstrate the one-to-many relationship.

  1. Set up the Database Tables: First, create the necessary migration files to generate the Articles and Comments tables in the database. The Comments table will have a foreign key column to associate comments with the corresponding article.
  2. Define Eloquent Models: Next, create Eloquent models for both Article and Comment. In the Article model, we will define a comments() method that will make use of the hasMany relationship, indicating that an article can have multiple comments. In the Comment model, we can define the inverse relationship using the belongsTo method, indicating that a comment belongs to a specific article.
  3. Establish the Relationships: With the models in place, we can now establish the one-to-many relationship between Articles and Comments. By calling the comments() method on an instance of the Article model, we can easily retrieve all the comments associated with that particular article.
  4. Querying and Manipulating Data: We will explore various operations, such as querying articles with their comments, adding new comments, associating comments with articles, and working with pivot tables for more complex relationships.

By following this tutorial, you will gain a solid understanding of the one-to-many relationship in Laravel 9 and insights into using eloquent relationships effectively.

So, let’s delve into the Laravel 9 one-to-many relationship example, understanding the hasMany and belongsTo methods, querying related data, inserting new records, and dealing with pivot tables for advanced relationships. This article aims to provide you with a comprehensive guide to mastering one-to-many relationships in Laravel 9.

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 Models

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

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

Now that we have the ability to access all of an article’s comments, let’s establish a relationship to enable a comment to access its parent article. To create the inverse of a hasMany relationship, we need to define a relationship method on the child model, which in turn calls the belongsTo method.

By doing so, we establish a link between the comment and its corresponding article, allowing us to navigate back and forth between the two. This relationship setup enhances the data structure and makes it easier to retrieve information about the comment’s parent article when needed.

In summary, we are creating a two-way association between articles and comments to facilitate efficient data access and retrieval.

<?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 assumes that the foreign key on the Comment model is named article_id, and it automatically searches for an Article model with a matching id in the article_id column to establish the relationship between articles and comments.

However, if the foreign key in the Comment model has a different name, for instance, post_id, we can customize the relationship definition by passing the custom key name as the second argument to the belongsTo method:

class Comment extends Model {
    // Assuming the foreign key for the Article model is post_id
    public function article() {
        return $this->belongsTo(Article::class, 'post_id');
    }
}

By providing the custom key name 'post_id' to the belongsTo method, Eloquent will correctly search for an Article model with an id that matches the post_id column in the comments table. This flexibility allows us to adapt the relationship setup to match the specific database schema and naming conventions we are using.

Retrieve Records using Model:

Once the relationship is defined, we can easily retrieve the related record using Eloquent’s dynamic properties. In this scenario, we can utilize the Article model’s comments function to access all the associated comments for a specific article.

Here’s how we can achieve this:

// Assuming we have an Article model and a Comment model with the appropriate relationships defined

// Retrieve a specific article
$article = Article::find(1);

// Access all comments related to the article using the 'comments' dynamic property
$articleComments = $article->comments;

In the above code, we first retrieve a specific article using the find method on the Article model, passing the article’s ID (in this case, ID 1) as the argument. Then, we can use the dynamic property comments on the $article object to access all the associated comments related to that article.

By setting up the relationship between Article and Comment models correctly, Eloquent handles the behind-the-scenes magic, allowing us to access related data with ease using these dynamic properties.

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading