0
0
Laravelframework~20 mins

One-to-one (hasOne, belongsTo) in Laravel - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
One-to-One Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of accessing a related model using hasOne?
Consider a Laravel User model with a hasOne relation to Profile. If you run $user->profile->bio and the user has a profile with bio 'Loves coding', what will be the output?
Laravel
<?php
class User extends Model {
  public function profile() {
    return $this->hasOne(Profile::class);
  }
}

$user = User::find(1);
echo $user->profile->bio;
ALoves coding
Bnull
CError: Undefined property
DEmpty string
Attempts:
2 left
💡 Hint
Remember that hasOne returns the related model instance if it exists.
state_output
intermediate
2:00remaining
What happens if belongsTo relation is accessed but related model is missing?
Given a Profile model with a belongsTo relation to User, what is the result of $profile->user->name if the user record was deleted?
Laravel
<?php
class Profile extends Model {
  public function user() {
    return $this->belongsTo(User::class);
  }
}

$profile = Profile::find(1);
echo $profile->user->name;
Anull
BError: Trying to get property 'name' of non-object
CEmpty string
DUser name string
Attempts:
2 left
💡 Hint
Think about what happens if the related user does not exist.
📝 Syntax
advanced
2:00remaining
Which code correctly defines a one-to-one inverse relation using belongsTo?
Choose the correct belongsTo relation definition inside the Profile model pointing to User.
Apublic function user() { return $this->hasOne(User::class); }
Bpublic function user() { return $this->hasMany(User::class); }
Cpublic function user() { return $this->belongsTo('User'); }
Dpublic function user() { return $this->belongsTo(User::class); }
Attempts:
2 left
💡 Hint
belongsTo is used on the child model to point to the parent.
🔧 Debug
advanced
2:00remaining
Why does eager loading a hasOne relation return an empty collection?
You run $users = User::with('profile')->get(); but $users[0]->profile is null even though the profile exists. What is the most likely cause?
AThe profile table is empty
BThe hasOne relation is defined with belongsTo instead
CThe foreign key in Profile does not match the User primary key
DEager loading does not work with hasOne relations
Attempts:
2 left
💡 Hint
Check the foreign key column names in the database and relation definition.
🧠 Conceptual
expert
2:00remaining
How does Laravel determine the foreign key name in a hasOne relation by default?
When defining public function profile() { return $this->hasOne(Profile::class); } in User, what foreign key column does Laravel expect in the profiles table by default?
Auser_id
Bprofile_id
Cid
DuserId
Attempts:
2 left
💡 Hint
Laravel uses the parent model name in snake_case plus _id.