Laravel One to Many Relationship Example

In this tutorial you will learn about the Laravel One to Many Relationship Example and its application with practical example.

In this Laravel one to many relationship example tutorial I’ll show you how to implement one to many relationship in laravel eloquent model. You will also learn how to use create, and retrieve records from database tables using one to many relationship.

Laravel One to Many Relationship Example

In this step by step tutorial I’ll guide you through to create many to many relationship and learn how to use this relationship. In this example we will use one to many relationship, and 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 suppose we have  tables name posts and authors. Using laravel migration, you can create both tables with the following fields:

Author table migration:

Post table migration:

Define One To Many Relationship

Now we will define One To Many Relationship for the model we have created. In One to many relationships means a relationship where one single model can owns the number of the other model. As per the example model we created, a single author can have written many post articles. Let’s take an example of one to many relationships.

Now, we can access the collection of post articles by using the post() method as.

Defining Inverse One To Many Relationship in Laravel

As of now we can access all the post articles of an author, now suppose if we want to allow a post model to access its 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. The inverse of the one to many relationship can be defined using the belongsTo method. Thus we can define in example mode as following:

Now we can get the author details by using posts in one to many relationship as following:

Retrieving Data In One to many relationship

In one to many relationship you can retrieve data from model as following:

You can get all posts of a particular author:

Similarly, you can retrieve the inverse related model.

Inserting Data In One to Many relationship

To Insert data in one to many relationship between two models, we can first create a child object and then save it using the parent object as following:

Filtering Data In one to many relationship

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

Deleting Data In One to Many relationship

Deleting of records in one to many relationship is performed same as we have created them. To delete all posts for a particular author use below code example.

In this tutorial we have learn about the Laravel One to Many Relationship Example and its application with practical example. I hope you will like this tutorial.