Performance: Why relationships model real data
This concept affects how efficiently the application queries and renders related data, impacting page load and interaction speed.
$users = User::with('profile')->get(); foreach ($users as $user) { echo $user->profile->bio; }
$users = User::all();
foreach ($users as $user) {
echo $user->profile->bio;
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Lazy loading relationships (N+1 queries) | Minimal DOM nodes | Multiple reflows due to slow data | High paint cost due to delayed data | [X] Bad |
| Eager loading relationships | Minimal DOM nodes | Single reflow after data ready | Lower paint cost with fast data | [OK] Good |
echo $post->user->name; output if the post belongs to a user named 'Alice'?
class Post extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}class User extends Model {
public function posts() {
return $this->hasMany(Post);
}
}public function tags() { return $this->belongsToMany(Tag::class); } and in Tag model: public function posts() { return $this->belongsToMany(Post::class); } correctly uses belongsToMany in both Post and Tag models.Pass the test and this pattern moves unknown