Database & Eloquent Orm Interview Questions
Comprehensive database & eloquent orm interview questions and answers for Laravel. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is Eloquent ORM in Laravel?
Basic2. How do you create a model in Laravel?
Basic3. What are migrations in Laravel?
Basic4. What are the basic Eloquent operations?
Basic5. How do you define relationships in Eloquent?
Basic6. What is the purpose of seeders in Laravel?
Basic7. How do you perform basic queries using Eloquent?
Basic8. What are mass assignment and fillable attributes?
Basic9. How do you configure database connections in Laravel?
Basic10. What are model factories in Laravel?
Basic11. How do you implement eager loading in Eloquent?
Moderate12. What are model events and observers?
Moderate13. How do you implement soft deletes in Laravel?
Moderate14. What are query scopes and how are they implemented?
Moderate15. How do you implement polymorphic relationships?
Moderate16. What are accessors and mutators in Eloquent?
Moderate17. How do you implement database transactions?
Moderate18. What are pivot tables and how are they used?
Moderate19. How do you implement query caching?
Moderate20. What are subquery selects and joins?
Moderate21. How do you implement custom Eloquent collections?
Advanced22. How do you implement model replication and cloning?
Advanced23. How do you implement custom model binding resolvers?
Advanced24. How do you implement composite keys in Eloquent?
Advanced25. How do you implement custom query builders?
Advanced26. How do you implement model serialization customization?
Advanced27. How do you implement database sharding with Eloquent?
Advanced28. How do you implement real-time model observers?
Advanced29. How do you implement recursive relationships?
Advanced30. How do you implement custom model connection handling?
Advanced1. What is Eloquent ORM in Laravel?
BasicEloquent ORM (Object-Relational Mapping) is Laravel's built-in ORM that allows developers to interact with database tables using elegant object-oriented models. Each database table has a corresponding Model that is used for interacting with that table.
2. How do you create a model in Laravel?
BasicModels can be created using Artisan command: 'php artisan make:model ModelName'. Adding -m flag creates a migration file too. Models are placed in app/Models directory and extend Illuminate\Database\Eloquent\Model class.
3. What are migrations in Laravel?
BasicMigrations are like version control for databases, allowing you to define and modify database schema using PHP code. They enable team collaboration by maintaining consistent database structure across different development environments.
4. What are the basic Eloquent operations?
BasicBasic Eloquent operations include: Model::all() to retrieve all records, Model::find(id) to find by primary key, Model::create([]) to create new records, save() to update, and delete() to remove records.
5. How do you define relationships in Eloquent?
BasicRelationships are defined as methods in model classes. Common types include hasOne(), hasMany(), belongsTo(), belongsToMany(). These methods specify how models are related to each other in the database.
6. What is the purpose of seeders in Laravel?
BasicSeeders are used to populate database tables with sample or initial data. They are created using 'php artisan make:seeder' and can be run using 'php artisan db:seed'. Useful for testing and initial application setup.
7. How do you perform basic queries using Eloquent?
BasicEloquent provides methods like where(), orWhere(), whereBetween(), orderBy() for querying. Example: User::where('active', 1)->orderBy('name')->get(). Queries return collections of model instances.
8. What are mass assignment and fillable attributes?
BasicMass assignment allows setting multiple model attributes at once. $fillable property in models specifies which attributes can be mass assigned, while $guarded specifies which cannot. This prevents unintended attribute modifications.
9. How do you configure database connections in Laravel?
BasicDatabase connections are configured in config/database.php and .env file. Multiple connections can be defined for different databases. The default connection is specified in .env using DB_CONNECTION.
10. What are model factories in Laravel?
BasicModel factories generate fake data for testing and seeding. Created using 'php artisan make:factory'. They use Faker library to generate realistic test data. Factories can define states for different scenarios.
11. How do you implement eager loading in Eloquent?
ModerateEager loading reduces N+1 query problems by loading relationships in advance using with() method. Example: User::with('posts')->get(). Can eager load multiple or nested relationships: with(['posts', 'profile']).
12. What are model events and observers?
ModerateModel events are triggered during various stages of a model's lifecycle (creating, created, updating, etc.). Observers group event listeners for a model in a single class. Created using 'php artisan make:observer'.
13. How do you implement soft deletes in Laravel?
ModerateSoft deletes add deleted_at timestamp instead of actually deleting records. Use SoftDeletes trait in model and add deleted_at column in migration. Provides withTrashed(), onlyTrashed() scopes for querying.
14. What are query scopes and how are they implemented?
ModerateQuery scopes are reusable query constraints. Global scopes automatically apply to all queries. Local scopes are methods prefixed with 'scope' and can be chained. Example: public function scopeActive($query) { return $query->where('active', 1); }
15. How do you implement polymorphic relationships?
ModeratePolymorphic relationships allow a model to belong to multiple types of models. Uses morphTo(), morphMany(), morphToMany() methods. Requires type and ID columns in database. Common for comments, likes, tags scenarios.
16. What are accessors and mutators in Eloquent?
ModerateAccessors and mutators modify attribute values when retrieving or setting them. Defined using get{Attribute}Attribute and set{Attribute}Attribute methods. Useful for formatting dates, calculating values, or encoding data.
17. How do you implement database transactions?
ModerateTransactions ensure multiple database operations succeed or fail as a unit. Use DB::transaction() or beginTransaction(), commit(), rollback(). Can be nested. Important for maintaining data integrity.
18. What are pivot tables and how are they used?
ModeratePivot tables implement many-to-many relationships. Created using createPivotTable migration method. Can have additional columns accessed via withPivot(). Pivot model can be customized using using() method.
19. How do you implement query caching?
ModerateQuery results can be cached using remember() or rememberForever() methods. Cache duration and key can be specified. Useful for expensive queries. Example: User::remember(60)->get();
20. What are subquery selects and joins?
ModerateSubqueries can be used in selects and joins using addSelect() and joinSub(). Useful for complex queries involving aggregates or related data. Can improve performance over multiple queries.
21. How do you implement custom Eloquent collections?
AdvancedCustom collections extend Illuminate\Database\Eloquent\Collection. Override newCollection() in model to use custom collection. Add methods for specialized collection operations specific to model type.
22. How do you implement model replication and cloning?
AdvancedModels can be replicated using replicate() method. Specify which attributes to exclude. Handle relationships manually. Useful for creating similar records with slight modifications.
23. How do you implement custom model binding resolvers?
AdvancedCustom model binding resolvers modify how models are resolved from route parameters. Defined in RouteServiceProvider using Route::bind() or by overriding resolveRouteBinding() in model.
24. How do you implement composite keys in Eloquent?
AdvancedComposite keys require overriding getKeyName() and getIncrementing(). Additional configuration needed for relationships. Consider performance implications. May need custom query scopes.
25. How do you implement custom query builders?
AdvancedCustom query builders extend Illuminate\Database\Eloquent\Builder. Override newEloquentBuilder() in model. Add methods for specialized query operations. Useful for complex, reusable queries.
26. How do you implement model serialization customization?
AdvancedCustomize toArray() and toJson() methods. Use hidden and visible properties. Implement custom casts for complex attributes. Handle relationship serialization. Consider API resource classes.
27. How do you implement database sharding with Eloquent?
AdvancedSharding requires custom connection resolvers. Override getConnection() in models. Implement logic for determining shard. Consider transaction and relationship implications across shards.
28. How do you implement real-time model observers?
AdvancedReal-time observers can broadcast model changes using events. Implement ShouldBroadcast interface. Configure broadcast driver. Handle authentication and authorization for broadcasts.
29. How do you implement recursive relationships?
AdvancedRecursive relationships use self-referential associations. Implement methods for traversing tree structures. Consider performance with nested eager loading. Use closure table pattern for complex hierarchies.
30. How do you implement custom model connection handling?
AdvancedCustom connection handling requires extending Connection class. Implement custom query grammar and processor. Handle transaction management. Consider read/write splitting scenarios.