Laravel 9 One to One Relationship Example

In this example, we will create a one-to-one relationship between two Eloquent models: User and Phone.

First, we will create the User model.

hasOne(‘App\Phone’);
}
}

Next, we will create the Phone model.

belongsTo(‘App\User’);
}
}

Finally, we will create the migration for the phones table.

id();
$table->unsignedBigInteger(‘user_id’);
$table->string(‘number’);
$table->timestamps();
});
}

public function down()
{
Schema::dropIfExists(‘phones’);
}
}

Now, we can create a new user and assign a phone to it.

$user = User::create([
‘name’ => ‘John Doe’,
]);

$user->phone()->create([
‘number’ => ‘1234567890’,
]);

We can also retrieve the phone associated with a user.

$phone = $user->phone;

Laravel 9 one to one relationship example; In this tutorial, you will learn what is one to one relationship and how to use one to one relationships in laravel with examples.

A one-to-one relationship is a very basic relation. And using one to one relationship, you can insert, retrieve, update, and delete data with the eloquent model from the database table in laravel.

Laravel Eloquent One to One Relationship Example

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

Post table migration:

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

    $table->increments('id');

    $table->string('title');

    $table->text('short_desc');

    $table->timestamps();

});

Contents table migration:

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

    $table->increments('id');

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

    $table->text('description');

    $table->timestamps();


    $table->foreign('post_id')->references('id')->on('posts')

        ->onDelete('cascade');

});

One to one relationship is one of the basic relationships. For example, a Post model would be associated with a Content model. To illustrate this relationship, we can create a post_content() method within the Post model and call the hasOne() method to relate the Content model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function post_content()
    {
        return $this->hasOne('App\Content');
    }
}

It is important to note that Eloquent establishes a foreign key based on the model name and should have a matching value id. Here post_id is the foreign_key of Content, So in order to create the relation.

The inverse of One to One Relationship Example

So far, we can access the content from the post. Let us now create an inverse relationship on the content model so that the post can access the model from it. To do this, we can use the belongsTo method for getting the post data on the content model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

We can now access the post content using the relation method like this:

$content = Post::find(10)->post_content;

You can insert record from post and content table using one to one relationship

   public function addPost()
    {
        $post = new Post;
        $post->title= "Hello world";
        $post->short_desc= "Hello world";
        $post->save();

        $content = new Content;
        $content->description= 'helllo world post description';
        $content->post_content()->save($content);
    }

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

public function index()
{
    // get post and content from Post Model
    $post = Post::find(1);
    var_dump($post->title);
    var_dump($post->post_content->description);

    // get post data from PostContent model
    $post= Content::find(1)->post;
    dd($post);

}

If you want to delete data from both tables posts and contents, you can use one to one relationship as follow:

public function delete()
{
    $post = Post::find(1);
    $post->delete();
}

Conclusion

In this laravel one to one relationship example, you have learned how to implement one to one relationship in laravel. And as well as how to use this relationship.

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?