Bird
Raised Fist0
Laravelframework~10 mins

One-to-one (hasOne, belongsTo) in Laravel - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - One-to-one (hasOne, belongsTo)
Define Model A
↓
Add hasOne relation in Model A
↓
Define Model B
↓
Add belongsTo relation in Model B
↓
Query Model A -> get related Model B
↓
Query Model B -> get related Model A
This flow shows how to set up and use one-to-one relations between two models using hasOne and belongsTo in Laravel.
Execution Sample
Laravel
class User extends Model {
  public function phone() {
    return $this->hasOne(Phone::class);
  }
}

class Phone extends Model {
  public function user() {
    return $this->belongsTo(User::class);
  }
}
Defines a one-to-one relation where a User has one Phone, and a Phone belongs to a User.
Execution Table
StepActionModelRelation Method CalledQuery GeneratedResult
1Call user->phone()UserhasOneSELECT * FROM phones WHERE user_id = ?Phone model instance or null
2Call phone->user()PhonebelongsToSELECT * FROM users WHERE id = ?User model instance or null
3Access phone property on userUserproperty accessUses cached relationPhone instance returned
4Access user property on phonePhoneproperty accessUses cached relationUser instance returned
5No related record foundUser or Phonerelation callQuery returns emptynull returned
💡 Queries stop after fetching related model or returning null if none found
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
userUser instanceUser instanceUser instanceUser instance with phone loadedUser instance with phone loaded
phonenullPhone instance or nullPhone instance or nullPhone instancePhone instance
phone->usernullnullUser instance or nullUser instanceUser instance
Key Moments - 3 Insights
Why does user->phone() return null sometimes?
Because the related phone record may not exist in the phones table for that user_id, as shown in execution_table step 5.
Why do we use hasOne in User and belongsTo in Phone?
hasOne defines the owning side with foreign key in the other table; belongsTo defines the inverse side with foreign key in this model, as shown in execution_sample.
Does accessing user->phone cache the result?
Yes, after the first query, Laravel caches the related model, so repeated access does not run new queries, as shown in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what query runs when calling phone->user()?
ASELECT * FROM phones WHERE user_id = ?
BSELECT * FROM users WHERE id = ?
CSELECT * FROM phones
DSELECT * FROM users
💡 Hint
Check execution_table row 2 under 'Query Generated'
At which step does Laravel return null if no related record exists?
AStep 5
BStep 1
CStep 3
DStep 4
💡 Hint
Look at execution_table row 5 'Result' column
If you remove belongsTo from Phone, what happens when calling phone->user()?
AIt returns the User instance anyway
BIt runs the hasOne query instead
CIt throws an error or returns null
DIt caches the phone relation
💡 Hint
belongsTo defines the inverse relation needed for phone->user(), see execution_sample
Concept Snapshot
One-to-one relations link two models where one owns the other.
Use hasOne in the owning model to define the relation.
Use belongsTo in the owned model to define the inverse.
Queries fetch related model by foreign key.
Accessing relation caches the result for reuse.
Full Transcript
In Laravel, one-to-one relations connect two models so each instance of one model relates to exactly one instance of another. We define hasOne in the model that owns the other, meaning it expects the foreign key in the related model's table. The related model uses belongsTo to point back. When you call the relation method, Laravel runs a query to find the related record by foreign key. If found, it returns the related model instance; if not, it returns null. Accessing the relation caches the result to avoid repeated queries. This setup helps keep data connected simply and clearly.

Practice

(1/5)
1. In Laravel, when defining a one-to-one relationship, which method should you use on the model that owns the other model?
easy
A. hasOne
B. belongsTo
C. hasMany
D. belongsToMany

Solution

  1. Step 1: Understand ownership in one-to-one

    The model that owns the other model is the one that does not have the foreign key.
  2. Step 2: Identify the correct method for ownership

    In Laravel, the owning model uses hasOne to define the relationship.
  3. Final Answer:

    hasOne -> Option A
  4. Quick Check:

    Owning model uses hasOne [OK]
Hint: Owning model uses hasOne, foreign key model uses belongsTo [OK]
Common Mistakes:
  • Using belongsTo on the owning model
  • Confusing hasOne with hasMany
  • Using belongsToMany for one-to-one
2. Which of the following is the correct syntax to define a belongsTo relationship in a Laravel model?
easy
A. public function user() { return $this->belongsTo(User::class); }
B. public function user() { return $this->belongsToMany(User::class); }
C. public function user() { return $this->hasMany(User::class); }
D. public function user() { return $this->hasOne(User::class); }

Solution

  1. Step 1: Recall belongsTo syntax

    The belongsTo method is used on the model with the foreign key and is called like return $this->belongsTo(Model::class);.
  2. Step 2: Match the correct syntax

    public function user() { return $this->belongsTo(User::class); } matches the correct belongsTo syntax exactly.
  3. Final Answer:

    public function user() { return $this->belongsTo(User::class); } -> Option A
  4. Quick Check:

    belongsTo syntax uses belongsTo(Model::class) [OK]
Hint: belongsTo uses return $this->belongsTo(Model::class) [OK]
Common Mistakes:
  • Using hasOne instead of belongsTo
  • Forgetting parentheses after belongsTo
  • Using belongsToMany for one-to-one
3. Given these two Laravel models:
class User extends Model {
  public function profile() {
    return $this->hasOne(Profile::class);
  }
}

class Profile extends Model {
  public function user() {
    return $this->belongsTo(User::class);
  }
}

What will $user->profile->phone return if the user has a profile with phone number '123-456-7890'?
medium
A. An array of profiles
B. null
C. An error because profile() is not defined
D. '123-456-7890'

Solution

  1. Step 1: Understand the relationship

    User has one Profile, so $user->profile returns the related Profile model instance.
  2. Step 2: Access the phone attribute

    Accessing $user->profile->phone returns the phone value from the Profile model, which is '123-456-7890'.
  3. Final Answer:

    '123-456-7890' -> Option D
  4. Quick Check:

    hasOne returns single related model [OK]
Hint: hasOne returns single model, access attributes directly [OK]
Common Mistakes:
  • Expecting an array instead of a single model
  • Confusing belongsTo and hasOne roles
  • Assuming null when profile exists
4. You have these models:
class Author extends Model {
  public function biography() {
    return $this->hasOne(Biography::class);
  }
}

class Biography extends Model {
  public function author() {
    return $this->belongsTo(Author::class);
  }
}

But when you try $author->biography, it returns null even though the biography exists in the database. What is the most likely cause?
medium
A. The Biography model is missing the hasOne method.
B. The Author model should use belongsTo instead of hasOne.
C. The Biography model's foreign key column name doesn't match Laravel's default 'author_id'.
D. The database table for Biography is missing entirely.

Solution

  1. Step 1: Check foreign key conventions

    Laravel expects the foreign key in Biography table to be 'author_id' by default for belongsTo.
  2. Step 2: Identify mismatch causes null

    If the foreign key column is named differently, Laravel cannot find the related record, so $author->biography returns null.
  3. Final Answer:

    The Biography model's foreign key column name doesn't match Laravel's default 'author_id'. -> Option C
  4. Quick Check:

    Foreign key name mismatch causes null relation [OK]
Hint: Check foreign key column names match Laravel defaults [OK]
Common Mistakes:
  • Switching hasOne and belongsTo methods incorrectly
  • Assuming missing method causes null instead of key mismatch
  • Ignoring database schema foreign key names
5. You want to create a one-to-one relationship between Car and Engine models where each car has exactly one engine. The engines table has a foreign key car_id. Which is the correct way to define the relationship in both models?
hard
A. In Car model: public function engine() { return $this->belongsTo(Engine::class); }
In Engine model: public function car() { return $this->hasOne(Car::class); }
B. In Car model: public function engine() { return $this->hasOne(Engine::class); }
In Engine model: public function car() { return $this->belongsTo(Car::class); }
C. In Car model: public function engine() { return $this->hasMany(Engine::class); }
In Engine model: public function car() { return $this->belongsTo(Car::class); }
D. In Car model: public function engine() { return $this->belongsToMany(Engine::class); }
In Engine model: public function car() { return $this->belongsToMany(Car::class); }

Solution

  1. Step 1: Identify foreign key location

    The foreign key car_id is in the engines table, so Engine belongs to Car.
  2. Step 2: Define relationships accordingly

    Car has one Engine (hasOne), Engine belongs to Car (belongsTo).
  3. Final Answer:

    Car uses hasOne, Engine uses belongsTo -> Option B
  4. Quick Check:

    Foreign key in engines means Engine belongsTo Car [OK]
Hint: Foreign key in table means that model belongsTo owner [OK]
Common Mistakes:
  • Reversing hasOne and belongsTo roles
  • Using hasMany for one-to-one
  • Using belongsToMany for one-to-one
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard