Laravel 9 One to Many Relationship Example

In this example, we will create a one-to-many relationship between a User and a Post model.

First, we will create the User model.

php artisan make:model User

Next, we will create the Post model.

php artisan make:model Post

Now, we will add the relationship between the two models. In the User model, we will add the following code:

public function posts()
{
return $this->hasMany(‘App\Post’);
}

And in the Post model, we will add the following code:

public function user()
{
return $this->belongsTo(‘App\User’);
}

Now, we will create the database tables for the two models.

php artisan make:migration create_users_table

And in the migration file, we will add the following code:

public function up()
{
Schema::create(‘users’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->timestamps();
});
}

And for the Post model, we will add the following code:

public function up()
{
Schema::create(‘posts’, function (Blueprint $table) {
$table->id();
$table->string(‘title’);
$table->text(‘body’);
$table->unsignedBigInteger(‘user_id’);
$table->foreign(‘user_id’)->references(‘id’)->on(‘users’);
$table->timestamps();
});
}

Finally, we will run the migrations to create the tables in the database.

php artisan migrate

And that’s it! We have now created a one-to-many relationship between the User and Post models.

Laravel one to many relationship example; In this tutorial, you will learn one to many relationship with examples in laravel.

Using one to many relationship, you can perform crud (create, read, update, delete) operation with the eloquent model from the database table in laravel.

Laravel Eloquent One to Many Relationship Example

Let you have two tables name posts and authors. Using laravel migration, you can create both tables with the following fields:

Author table migration:

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

    $table->increments('id');

    $table->string('name');

    $table->timestamps();

});

Post table migration:

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

    $table->increments('id');

    $table->string('title');

    $table->text('description');

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

    $table->timestamps();


    $table->foreign('author_id')->references('id')->on('authors')

        ->onDelete('cascade');

});

Define One To Many Relationship

One to many relationships determines a relationship where one single model owns the number of the other model. For example, a blog author may have many posts.

A single author can have written many post articles. Let’s take an example of one to many relationships.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    ...
    public function post()
    {
        return $this->hasMany('App\Post');
    }
}

We can then access the collection of post articles by using the post() method as.

Using this, we get all the posts of a single author. Here we need to get the author details of a single post, for each post there a single author, within the Post model includes belongsTo relation.

$posts = App\Author::find(10)->post()->get();

 foreach ($posts as $post) {
     //do something
 }

Defining Inverse One To Many Relationship in Laravel

Since we can now access all the post articles of an author, it is time to allow a post article to access its parent model (Author model) or access author details by using the post model. The inverse relationship of both One to One and One to Many works the same way. Both use the belongsTo method to define the inverse relation. Thus we can define one as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

Using this, Here we need to get the author details by using posts, for each post there a single author, within the Post model includes belongsTo relation.

$post->author->name;

Retrieving Data

Once you have defined the relationship on models, you can retrieve data from the DB table using the eloquent model.

In this example, you can get all posts of a particular author: 

 $posts = Author::find(10)->post()->get();

 foreach ($posts as $post) {
     //do something
 } 

Similarly, you can retrieve the inverse related model.

 $posts = Post::find(10)->author()->get();

 foreach ($posts as $post) {
     //do something
 } 

Inserting Data

To create a relationship between two models or associating them, we can first create a child object and then save it using the parent object.

$author = Author::find(1);

$post= new Post();
$post->title = 'iPhone X';
$post->description = 'Some description';

// Saving related model
$author->post()->save($post);

You can also use the saveMany() method instead of save() to associate multiple records.

Filtering Data

You might want to filter the related records and want them to sort when retrieving. You can chain the methods on your retrieving query.

$author = Author::find(1); 
$post = $author->post() 
 ->orderBy('name', 'asc') 
 ->get(); 

Deleting Data

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

$author = Author::find(1);
$author->post()->delete();

Conclusion

In this tutorial, you have learned how to define one to many relationship and using this relationship how to perform crud operation with an eloquent model from database tables.

Recommended Laravel Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?