
Eloquent Relationships
One-to-One, One-to-Many, Many-to-Many, Has Many Through, polymorphic relations, eager loading, lazy loading
1What is a hasOne relationship in Eloquent?
What is a hasOne relationship in Eloquent?
Answer
hasOne() defines a One-to-One relationship where the current model owns a single related record in another table. This relationship is useful for associations like User and Profile, where each user has a single profile. The inverse of this relationship is defined with belongsTo() on the related model.
2How to define a hasMany relationship in an Eloquent model?
How to define a hasMany relationship in an Eloquent model?
Answer
The hasMany() method is used in the parent model to declare that it owns multiple records of another model. It takes as parameters the related model class, and optionally the foreign key and local key. This relationship is ideal for cases like an author who owns multiple articles.
3Which method to use to define the inverse relationship of hasOne or hasMany?
Which method to use to define the inverse relationship of hasOne or hasMany?
Answer
belongsTo() defines the inverse relationship on the child side when the parent model uses hasOne() or hasMany(). This method indicates that the current model belongs to another model and uses a foreign key to establish the connection. It is essential for navigating a relationship in both directions.
How to create a Many-to-Many relationship in Eloquent?
What is the naming convention for a pivot table in a Many-to-Many relationship?
+22 interview questions
Other Laravel interview topics
PHP Basics
PHP OOP Essentials
Composer & Autoloading
Laravel Fundamentals
Laravel Routing
Blade Templates
Request & Response
Eloquent ORM Basics
Migrations & Schema Builder
Validation & Forms
Authentication
Authorization & Policies
API Resources & Authentication
Middleware
Service Container & DI
Queues & Jobs
Events & Listeners
Notifications & Mail
File Storage
Testing & PHPUnit
Caching
Livewire & Inertia
Eloquent Advanced
Repository Pattern
Laravel Packages
Performance Optimization
Security Best Practices
Laravel Octane
Laravel Distributed Systems
Observability & Monitoring
Deployment & DevOps
Master Laravel for your next interview
Access all questions, flashcards, technical tests, code review exercises and interview simulators.
Start for free