Simple Eloquent Laravel One to One Relationship

Today, We want to share with you Simple Eloquent Laravel One to One Relationship.In this post we will show you Laravel One to One Eloquent Relationship Tutorial, hear for Laravel 5.7 Retrieving data using a one-to-one relationship we will give you demo and example for implement.In this post, we will learn about Laravel 5.7 Saving(Store in Database) data using a one-to-one relationship with an example.

Simple Eloquent Laravel One to One Relationship

There are the Following The simple About Simple Eloquent Laravel One to One Relationship Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel 5.7 One To One Eloquent Relationships Tutorial, so the laravel hasmanythrough pivot for this example is following below.

Example Information:

In this Example we have 2 models (Member and Mobile), and 2 tables (members and mobiles).

Business Rules:

  • The Member can own one Mobile.
  • The Mobile can be owned by one Member.

Relationship Details:

The mobiles table should store the Member ID.

Eloquent Models:

class Member
{
    public function mobile()
    {
       return $this->hasOne(Mobile::class);
    }
}
class Mobile
{
    public function member()
    {
        return $this->belongsTo(Member::class);
    }
}

Database Migrations:

Schema::create('members', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});
Schema::create('mobiles', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->integer('member_id')->unsigned()->index()->nullable();
    $table->foreign('member_id')->references('id')->on('members');
});

Store Records:

Saving Data using one to one relation in Laravel 5.7

// Create relation between Member and Mobile.
$member->mobile()->save($mobile);

// Create relation between Mobile and Member.
$mobile->member()->associate($member)->save();

Retrieve Records:

Laravel 5.7 Retrieving data using a one-to-one relationship

// Get Member Mobile
$member->mobile;

// Get Mobile Member
$mobile->member;
Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Simple Eloquent Laravel One to One Relationship.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment