• Post
  • Category
  • Tags
  • About Us
  • Contact Us
Quick Links

Laravel 10 one to one Relationship Example

Jul-24-2023 | Laravel PHP

In the dynamic world of web development, building scalable and efficient applications often involves managing complex data relationships. As a Laravel developer, I have come to appreciate the power of this PHP framework, which excels in managing databases and their relationships. Among the various types of relationships supported by Laravel, I find the one-to-one relationship particularly intriguing.

In this article, I would like to share my exploration of the one-to-one relationship in Laravel 10 through a practical and illustrative example.

Understanding this relationship type is essential for creating a well-structured database schema and optimizing data retrieval operations. By leveraging one-to-one relationships, we can efficiently connect and organize data between different database tables, enhancing the overall performance of our applications.

For this journey, we will focus on a scenario involving users and profiles. Together, we will demonstrate how to establish and utilize a one-to-one relationship, ensuring that each user has a unique phone, and each profile is associated with only one user.

Throughout this article, I will guide you through the process of setting up the Laravel project, creating the necessary database migrations, generating models, and defining the one-to-one relationship between the "users" and "phones" tables.

For one to one relationships use hasOne and belongsTo the method in the model for access to each other model.

Whether you are new to Laravel or an experienced developer seeking to enhance your database management skills, I am excited to share this knowledge with you.

Together, we will master the art of managing one-to-one relationships in Laravel 10, empowering you to create robust and efficient applications.

So, let's dive into this enlightening journey and unlock the potential of one-to-one relationships in Laravel 10

We will create a User and Phone table. User model might be associated with one Phone model. To define this relationship, we will place a phone method on the User model. The phone method should call the hasOne method and return its result.

one-to-one-relationship-laravel-10

 

Create Migration

In this step, we have to create migration for users and phones table. we will also add a foreign key to the user's table.

Create Migration of Users Table

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

    $table->increments('id');

    $table->string('name');

    $table->string('email')->unique();

    $table->timestamps();

});

Create Migration of Phones Table with Foreign Key

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

    $table->increments('id');

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

    $table->string('phone_no');

    $table->timestamps();    

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

});

 

Create Model and Add Relationship on Both Model

In the user model, we can create a phone() function and add the relation of the phone model using the hasOne method.

User Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone associated with the user.
     */
    public function phone()
    {
        return $this->hasOne(Phone::class);
    }
}

 

Read Also: How to Send Email with PDF Attachment in Laravel 10

 

Phone Model:

we can access the Phone model from our User model. Next, let's define a relationship on the Phone model that will let us access the user that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

If the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method.

public function user()
{
    return $this->belongsTo(User::class, 'foreign_key');
}

 

Retrieve Records using Model:

Once the relationship is defined, you may retrieve the related record using Eloquent's dynamic properties. So, here we can use the User model with a phone function.

$phone = User::find(1)->phone;
$user = Phone::find(1)->user;

 

Create Records using Model 

Now, we will add records to the phone table using the user model.

$user = User::find(1);
 
$phone = new Phone;
$phone->phone_no = '1234567890';
 
$user->phone()->save($phone);

 

$phone = Phone::find(1);
 
$user = User::find(1);
 
$phone->user()->associate($user)->save();

 

Conclusion:

In this article, we explored the one-to-one relationship in Laravel 10 through a practical example of users and profiles. Understanding how to set up and utilize one-to-one relationships in your Laravel applications allows for efficient and structured data management.

 


You might also like:

  • Read Also: Laravel 10 Send Mail Using Queue
  • Read Also: How To Export CSV File In Laravel 10 Example
  • Read Also: Laravel 10 Import and Export CSV and Excel Files
  • Read Also: Laravel 10 AJAX CRUD Operations With Popup Modal


Laravel
PHP
Laravel 10

RECOMMENDED ARTICLES

Reading articles is highly recommended for skill improvement and knowledge acquisition.

  • Laravel 10 Many To Many Polymorphic Relationship
  • PHP vs Python: Which is Best for Web Development (2023)
  • Laravel 10 AJAX CRUD Operations With Popup Modal
  • Laravel 10 React Auth Scaffolding Example
  • Laravel 10 one to many Relationship Example
  • 10 Digit Mobile Number Validation in Angular 17
  • Google Two-Factor Authentication (2FA) in Laravel 10
  • Difference between Single Quotes and Double Quotes in PHP
  • How To Export CSV File In Laravel 10 Example
  • How To Integrate Paypal Payment Gateway In Laravel 10

CATEGORIES

Web development languages can be categorized into different categories.

Laravel
PHP
jQuery
MySQL
CSS
HTML
Bootstrap
Vue JS
Node.js
Other
Python
React JS
Angular
React Native

TAGS

These tags can be used to categorize and organize content related to web development.

Git
File Upload
Angular
NPM
SEO
HTML
PDF
Carbon
Authentication
MySQL

RECENT ARTICLES

The recent article focuses on the latest developments to gain new knowledge.

  • 10 Digit Mobile Number Validation i...
  • How to Create Autocomplete Search i...
  • How to Create Autocomplete Search i...
  • How to Add Soft Delete in Laravel 1...
  • How to Delete Relationship Records...
  • How to Send SMS using Twilio in Lar...
  • How to Create Multiple Authenticati...
  • Laravel 10 React Auth Scaffolding E...
  • PHP vs Python: Which is Best for We...
  • How to use Unique Validation on Upd...
Vidvatek
Post
Category
Tags
About Us
Contact Us
Quick Links

Copyright © Vidvatek 2023
Privacy Policy · Terms & Conditions · Disclaimer