Challenge - 5 Problems
One-to-One Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2: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;
Attempts:
2 left
💡 Hint
Remember that hasOne returns the related model instance if it exists.
✗ Incorrect
The hasOne relation returns the related Profile model. Accessing ->bio on it returns the stored bio string.
❓ state_output
intermediate2: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;
Attempts:
2 left
💡 Hint
Think about what happens if the related user does not exist.
✗ Incorrect
If the related user is missing, $profile->user returns null. Accessing ->name on null causes an error.
📝 Syntax
advanced2: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.
Attempts:
2 left
💡 Hint
belongsTo is used on the child model to point to the parent.
✗ Incorrect
belongsTo defines the inverse of hasOne. It requires the related class name as a class reference.
🔧 Debug
advanced2: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?Attempts:
2 left
💡 Hint
Check the foreign key column names in the database and relation definition.
✗ Incorrect
If the foreign key column in Profile does not match the User primary key, Laravel cannot link the models, so profile is null.
🧠 Conceptual
expert2: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?Attempts:
2 left
💡 Hint
Laravel uses the parent model name in snake_case plus _id.
✗ Incorrect
By default, Laravel expects the foreign key to be the snake_case of the parent model name plus _id, so 'user_id' in profiles table.