Performance: One-to-one (hasOne, belongsTo)
This affects database query performance and page load speed by controlling how related data is fetched and rendered.
$users = User::with('profile')->get(); foreach ($users as $user) { echo $user->profile->bio; }
foreach ($users as $user) {
echo $user->profile->bio;
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Lazy loading one-to-one relation | Minimal DOM nodes | Multiple reflows due to delayed data | Higher paint cost due to slower data | [X] Bad |
| Eager loading one-to-one relation | Minimal DOM nodes | Single reflow after data ready | Lower paint cost with faster data | [OK] Good |
hasOne to define the relationship.return $this->belongsTo(Model::class);.class User extends Model {
public function profile() {
return $this->hasOne(Profile::class);
}
}
class Profile extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}$user->profile->phone return if the user has a profile with phone number '123-456-7890'?$user->profile returns the related Profile model instance.$user->profile->phone returns the phone value from the Profile model, which is '123-456-7890'.class Author extends Model {
public function biography() {
return $this->hasOne(Biography::class);
}
}
class Biography extends Model {
public function author() {
return $this->belongsTo(Author::class);
}
}$author->biography, it returns null even though the biography exists in the database. What is the most likely cause?$author->biography returns null.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?car_id is in the engines table, so Engine belongs to Car.hasOne), Engine belongs to Car (belongsTo).Pass the test and this pattern moves unknown