Laravel One to One Relationship Example

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

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

Laravel One to One Relationship Example

The one to one relationship is a very common relationship in laravel model. In this example we will learn to implement and use one to one relationship in laravel. We will also show you how to  insert, retrieve, update, and delete data with the eloquent model from the database table in laravel.

Laravel Eloquent One to One Relationship Example

Let suppose we have two tables posts and contents in our example tutorial. In laravel we can create both tables using migration as following:

Post table migration:

Contents table migration:

In this example, the Post model is closely associated with a Content model in one to one relationship. In one to one relationship we will create a post_content() method within the Post model and there is hasOne() method to relate it with Content model as following.

The Eloquent model adds a foreign key based on the model name and should have a matching id value in it. In this relationship the post_id is the foreign_key for Content model,

Inverse of One to One Relationship Example

For now we can have the access to the content from the post model. Now we create an inverse relationship in the content model. For this we will use the belongsTo method for getting the post data from the content model as following.

We can now access the post content using the relation method as following:

Laravel Insert record in one to one relationship

You can insert record in post and content table using one to one relationship as following:

Now, if you want to retrieve data from both post and content table, you can use one to one relationship as following:

Laravel Delete record in One to One relationship

Now, to delete record from both tables posts and contents in one to one relationship, you can do it as following:

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