Skip to content

Laravel Relationships Interview Questions with Examples

24 people viewed this

Laravel Relationships Interview Questions with Examples

Laravel Relationships Interview Questions with Examples

Laravel relationships are one of the most important topics for a Laravel developer. If you are preparing for a Laravel interview, questions about Eloquent relationships are very common.

In real-world applications, data is rarely stored in a single table. For example, a user can have many posts, a post can have many comments, and a post can belong to multiple categories.

Laravel Eloquent makes these relationships easy to define and work with using relationship methods inside your models.

In this article, we will cover the most commonly asked Laravel relationship interview questions with practical examples.

What Are Relationships in Laravel?

Relationships in Laravel define how two or more database tables are connected to each other.

Laravel uses Eloquent ORM to work with these relationships using model methods.

For example, suppose we have these tables:

  • users
  • posts
  • comments
  • categories

A user can have many posts, while a post belongs to one user.

User
  |
  | hasMany
  ↓
Posts
  |
  | hasMany
  ↓
Comments

1. What Are the Types of Relationships in Laravel?

Laravel Eloquent supports several types of relationships.

  • One To One
  • One To Many
  • Many To Many
  • Has One Through
  • Has Many Through
  • Polymorphic One To One
  • Polymorphic One To Many
  • Polymorphic Many To Many

The relationships most frequently used in Laravel applications are hasOne, hasMany, belongsTo, and belongsToMany.

2. What Is a One-to-One Relationship in Laravel?

A one-to-one relationship means one record in a table is associated with exactly one record in another table.

For example, one user can have one profile.

User Model

public function profile()
{
    return $this->hasOne(Profile::class);
}

Profile Model

public function user()
{
    return $this->belongsTo(User::class);
}

Now we can access the user's profile:

$user = User::find(1);

$profile = $user->profile;

The profiles table normally contains a user_id foreign key.

3. What Is a One-to-Many Relationship?

A one-to-many relationship means one record can have multiple related records.

For example, one user can create many posts.

User Model

public function posts()
{
    return $this->hasMany(Post::class);
}

Post Model

public function user()
{
    return $this->belongsTo(User::class);
}

Retrieve all posts of a user:

$user = User::find(1);

$posts = $user->posts;

4. What Is the Difference Between hasMany() and belongsTo()?

This is a very common Laravel interview question.

The easiest way to understand the difference is to identify where the foreign key exists.

hasMany()

The parent model uses hasMany().

// User.php

public function posts()
{
    return $this->hasMany(Post::class);
}

belongsTo()

The child model uses belongsTo().

// Post.php

public function user()
{
    return $this->belongsTo(User::class);
}

In this example, posts.user_id is the foreign key. Therefore, the Post model belongs to the User model.

5. What Is a Many-to-Many Relationship?

A many-to-many relationship occurs when multiple records from one table can be related to multiple records in another table.

A common example is users and roles.

One user can have multiple roles, and one role can belong to multiple users.

This requires a pivot table.

For example:

users
roles
role_user

The pivot table may contain:

user_id
role_id

6. How Do You Define a Many-to-Many Relationship?

In the User model:

public function roles()
{
    return $this->belongsToMany(Role::class);
}

In the Role model:

public function users()
{
    return $this->belongsToMany(User::class);
}

Retrieve roles for a user:

$user = User::find(1);

$roles = $user->roles;

7. What Is a Pivot Table in Laravel?

A pivot table is an intermediate table used to connect two tables in a many-to-many relationship.

For example, consider users and roles.

users
  |
  |
role_user
  |
  |
roles

The role_user table is the pivot table.

Laravel automatically understands conventional pivot table naming in many common cases.

8. How Do You Attach and Detach Many-to-Many Relationships?

Laravel provides methods such as attach(), detach(), and sync().

Attach

$user->roles()->attach($roleId);

Detach

$user->roles()->detach($roleId);

Sync

$user->roles()->sync([1, 2, 3]);

sync() is useful when you want the relationship to match an exact set of IDs.

9. What Is Eager Loading in Laravel?

Eager loading is used to load relationships together with the main query instead of querying the relationship separately for every record.

Laravel provides the with() method for eager loading.

$users = User::with('posts')->get();

This is especially important when working with large datasets because it can prevent unnecessary database queries.

10. What Is the N+1 Query Problem?

The N+1 query problem occurs when an application executes one query to retrieve the main records and then executes an additional query for each related record.

For example:

$users = User::all();

foreach ($users as $user) {
    echo $user->posts->count();
}

If there are 100 users, this can result in one query for users plus additional queries for their posts.

A common solution is eager loading:

$users = User::with('posts')->get();

This is one of the most important relationship and performance topics to understand for Laravel interviews.

11. What Is Lazy Loading?

Lazy loading means the relationship data is loaded only when the relationship property is accessed.

$user = User::find(1);

$posts = $user->posts;

The posts relationship is loaded when $user->posts is accessed.

Lazy loading is convenient, but careless use inside loops can lead to N+1 query problems.

12. What Is the Difference Between Lazy Loading and Eager Loading?

Lazy Loading Eager Loading
Loads relationship when accessed Loads relationship with the main query
Uses relationship property Usually uses with()
Can cause N+1 queries Can reduce unnecessary queries
Useful when relationship may not be required Useful when relationship data is known to be required

13. What Is hasOneThrough()?

hasOneThrough() is used when you need to access a related model through an intermediate model.

For example:

Mechanic
    |
    | hasOneThrough
    ↓
Car
    |
    ↓
Owner

It allows you to access the final related model through another model.

Example:

public function carOwner()
{
    return $this->hasOneThrough(
        Owner::class,
        Car::class
    );
}

14. What Is hasManyThrough()?

hasManyThrough() is similar to hasOneThrough(), but it returns multiple related records.

For example, a country may have many posts through users.

Country
   |
   ↓
Users
   |
   ↓
Posts

Example:

public function posts()
{
    return $this->hasManyThrough(
        Post::class,
        User::class
    );
}

15. What Are Polymorphic Relationships?

A polymorphic relationship allows one model to belong to multiple different types of models using the same relationship.

A common example is comments.

A comment could belong to a:

  • Post
  • Video
  • Product

Instead of creating separate comment tables, a polymorphic relationship can be used.

The comments table can contain:

commentable_id
commentable_type

16. How Do You Define a Polymorphic Relationship?

In the Comment model:

public function commentable()
{
    return $this->morphTo();
}

In the Post model:

public function comments()
{
    return $this->morphMany(
        Comment::class,
        'commentable'
    );
}

The same relationship can also be defined on other models such as Video or Product.

17. What Is the Difference Between a Relationship Method and a Relationship Property?

This is another useful interview question.

Relationship Property

$user->posts;

This accesses the relationship results.

Relationship Method

$user->posts();

This returns the relationship query builder.

Therefore, you can add query conditions:

$user->posts()
    ->where('status', 'published')
    ->get();

18. How Do You Add Conditions to Relationships?

You can define conditions directly inside a relationship method.

public function publishedPosts()
{
    return $this->hasMany(Post::class)
                ->where('status', 'published');
}

Now you can use:

$user->publishedPosts;

19. How Do You Check Whether a Relationship Exists?

Laravel provides methods such as has() and whereHas().

Using has()

$users = User::has('posts')->get();

This retrieves users who have at least one post.

Using whereHas()

$users = User::whereHas('posts', function ($query) {
    $query->where('status', 'published');
})->get();

20. What Is withCount() in Laravel?

withCount() allows you to retrieve the count of related records without loading the entire relationship collection.

$users = User::withCount('posts')->get();

You can then access:

$user->posts_count;

This is useful when you only need the number of related records.

21. What Is the Difference Between with() and withCount()?

Method Purpose
with() Loads relationship records
withCount() Loads the count of relationship records

If you need the actual posts, use with(). If you only need the number of posts, withCount() can be more appropriate.

22. How Do You Create a Related Record Using a Relationship?

Laravel allows you to create related records through relationship methods.

$user = User::find(1);

$user->posts()->create([
    'title' => 'Laravel Relationships',
    'content' => 'Learning Eloquent relationships'
]);

Laravel automatically associates the new post with the user through the relationship.

23. How Do You Load a Relationship After Retrieving a Model?

Laravel provides the load() method.

$user = User::find(1);

$user->load('posts');

You can also load multiple relationships:

$user->load([
    'posts',
    'profile'
]);

24. What Is loadMissing()?

loadMissing() loads a relationship only when it has not already been loaded.

$user->loadMissing('posts');

This can be useful when working with models where some relationships may already have been loaded earlier in the application flow.

25. How Do You Avoid N+1 Problems in Laravel?

One of the most common solutions is eager loading.

$posts = Post::with('user')->get();

Instead of:

$posts = Post::all();

foreach ($posts as $post) {
    echo $post->user->name;
}

Use:

$posts = Post::with('user')->get();

foreach ($posts as $post) {
    echo $post->user->name;
}

When preparing for a Laravel interview, make sure you understand why eager loading helps, not just the syntax.

Real-World Interview Scenario

Suppose an interviewer asks:

"You have 5 lakh users and every user has multiple orders. You need to display users with their order count. How would you optimize the query?"

If you only need the number of orders, loading every order is unnecessary.

You can use:

$users = User::withCount('orders')->get();

Then:

foreach ($users as $user) {
    echo $user->orders_count;
}

This demonstrates that you understand both Laravel relationships and query optimization.

Laravel Relationships Quick Revision

Relationship Example Laravel Method
One to One User → Profile hasOne()
One to Many User → Posts hasMany()
Inverse Relationship Post → User belongsTo()
Many to Many User ↔ Role belongsToMany()
Has One Through Model → Model → Model hasOneThrough()
Has Many Through Model → Model → Models hasManyThrough()
Polymorphic Comment → Post/Video morphTo()

Conclusion

Laravel Eloquent relationships make it easier to work with connected database tables using clean and expressive PHP code.

For Laravel interviews, you should be comfortable explaining hasOne(), hasMany(), belongsTo(), belongsToMany(), pivot tables, eager loading, lazy loading, N+1 queries, withCount(), and polymorphic relationships.

More importantly, try to understand when to use each relationship and how relationships affect database queries and application performance.

If you are preparing for a Laravel developer interview, these concepts are worth practicing with real database examples rather than only memorizing the syntax.

Frequently Asked Laravel Relationship Interview Questions

  1. What are Laravel Eloquent relationships?
  2. What is the difference between hasOne() and belongsTo()?
  3. What is a hasMany() relationship?
  4. What is a belongsToMany() relationship?
  5. What is a pivot table?
  6. What is eager loading?
  7. What is lazy loading?
  8. What is the N+1 query problem?
  9. How can you solve the N+1 problem?
  10. What is withCount()?
  11. What is the difference between with() and withCount()?
  12. What is whereHas()?
  13. What is load()?
  14. What is loadMissing()?
  15. What are polymorphic relationships?
  16. What is hasOneThrough()?
  17. What is hasManyThrough()?
  18. How do attach(), detach(), and sync() work?
  19. How do you create a related model using Eloquent relationships?
  20. How do relationships affect Laravel query performance?

```

Was this useful?

No ratings yet — yours can be the first.

Discussion

Notes from readers. Comments appear after a short review.

No comments yet. Start the thread below.