0
0
Laravelframework~5 mins

One-to-one (hasOne, belongsTo) in Laravel - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the hasOne relationship represent in Laravel?
The hasOne relationship means one model owns exactly one related model. For example, a User has one Profile.
Click to reveal answer
beginner
What is the purpose of the belongsTo relationship in Laravel?
The belongsTo relationship means a model belongs to another model. For example, a Profile belongs to a User.
Click to reveal answer
beginner
How do you define a one-to-one relationship from User to Profile using hasOne?
In the User model, add a method:<br><pre>public function profile() {<br>  return $this->hasOne(Profile::class);<br>}</pre>
Click to reveal answer
beginner
How do you define the inverse one-to-one relationship from Profile to User using belongsTo?
In the Profile model, add a method:<br><pre>public function user() {<br>  return $this->belongsTo(User::class);<br>}</pre>
Click to reveal answer
intermediate
Why is it important to use hasOne and belongsTo correctly in Laravel?
Using these correctly helps Laravel know how to join tables and fetch related data easily. It keeps your code clean and your database queries efficient.
Click to reveal answer
Which Laravel method defines the model that owns the relationship in a one-to-one setup?
AhasOne
BbelongsTo
ChasMany
DmorphOne
In a one-to-one relationship, which method should be used in the child model to link back to the parent?
AhasOne
BbelongsToMany
CbelongsTo
DhasMany
If a User has one Profile, where should the foreign key be stored?
AIn the users table
BIn the profiles table
CIn a pivot table
DNo foreign key needed
Which of these is NOT a valid Laravel relationship method?
AhasTwo
BbelongsTo
ChasOne
DbelongsToMany
What does the belongsTo method return in Laravel?
AA boolean value
BA collection of models
CThe related model instance
DA query builder for the related model
Explain how to set up a one-to-one relationship between two Laravel models using hasOne and belongsTo.
Think about which model owns the other and where the foreign key lives.
You got /4 concepts.
    Describe why using one-to-one relationships properly improves your Laravel application's code and database queries.
    Consider how Laravel uses these relationships behind the scenes.
    You got /4 concepts.