Laravel 10 One to One Relationship Tutorial

In Laravel, a one-to-one relationship is a type of database relationship where one record in a table is associated with exactly one record in another table. Laravel provides a convenient way to define and work with one-to-one relationships using Eloquent, its object-relational mapping (ORM) system.

Step 1 :Install Laravel App:

composer create-project laravel/laravel example-one_to_one_relationship

Step 2: Database Configuration

.env 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name
DB_USERNAME=database username
DB_PASSWORD=database password

Step 3 : Model Setup:

// User.php model
    class User extends Model
    {
        public function profile()
        {
            return $this->hasOne(Profile::class);
        }
    }
    
    // Profile.php model
    class Profile extends Model
    {
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }

Step 4: Accessing the Relationship

$user = User::find(1);
$profile = $user->profile; // Access the profile
    
// You can also access the user from the profile side
$profile = Profile::find(1);
$user = $profile->user; // Access the user

Step 5: Creating Related Records

To create related records, you can use the create() method provided by the relationship methods. For example, to create a profile for a user: 

$user = User::find(1);
$profile = $user->profile()->create([
'bio' => 'Lorem ipsum',
'location' => 'New York',
]);