Home
Jobs

Database & Eloquent Orm Interview Questions

Comprehensive database & eloquent orm interview questions and answers for Laravel. Prepare for your next job interview with expert guidance.

30 Questions Available

Questions Overview

1. What is Eloquent ORM in Laravel?

Basic

2. How do you create a model in Laravel?

Basic

3. What are migrations in Laravel?

Basic

4. What are the basic Eloquent operations?

Basic

5. How do you define relationships in Eloquent?

Basic

6. What is the purpose of seeders in Laravel?

Basic

7. How do you perform basic queries using Eloquent?

Basic

8. What are mass assignment and fillable attributes?

Basic

9. How do you configure database connections in Laravel?

Basic

10. What are model factories in Laravel?

Basic

11. How do you implement eager loading in Eloquent?

Moderate

12. What are model events and observers?

Moderate

13. How do you implement soft deletes in Laravel?

Moderate

14. What are query scopes and how are they implemented?

Moderate

15. How do you implement polymorphic relationships?

Moderate

16. What are accessors and mutators in Eloquent?

Moderate

17. How do you implement database transactions?

Moderate

18. What are pivot tables and how are they used?

Moderate

19. How do you implement query caching?

Moderate

20. What are subquery selects and joins?

Moderate

21. How do you implement custom Eloquent collections?

Advanced

22. How do you implement model replication and cloning?

Advanced

23. How do you implement custom model binding resolvers?

Advanced

24. How do you implement composite keys in Eloquent?

Advanced

25. How do you implement custom query builders?

Advanced

26. How do you implement model serialization customization?

Advanced

27. How do you implement database sharding with Eloquent?

Advanced

28. How do you implement real-time model observers?

Advanced

29. How do you implement recursive relationships?

Advanced

30. How do you implement custom model connection handling?

Advanced

1. What is Eloquent ORM in Laravel?

Basic

Eloquent 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?

Basic

Models 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?

Basic

Migrations 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?

Basic

Basic 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?

Basic

Relationships 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?

Basic

Seeders 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?

Basic

Eloquent 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?

Basic

Mass 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?

Basic

Database 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?

Basic

Model 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?

Moderate

Eager 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?

Moderate

Model 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?

Moderate

Soft 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?

Moderate

Query 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?

Moderate

Polymorphic 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?

Moderate

Accessors 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?

Moderate

Transactions 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?

Moderate

Pivot 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?

Moderate

Query 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?

Moderate

Subqueries 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?

Advanced

Custom 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?

Advanced

Models 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?

Advanced

Custom 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?

Advanced

Composite 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?

Advanced

Custom 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?

Advanced

Customize 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?

Advanced

Sharding 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?

Advanced

Real-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?

Advanced

Recursive 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?

Advanced

Custom connection handling requires extending Connection class. Implement custom query grammar and processor. Handle transaction management. Consider read/write splitting scenarios.

Database & Eloquent Orm Interview Questions Faq

What types of interview questions are available?

Explore a wide range of interview questions for freshers and professionals, covering technical, business, HR, and management skills, designed to help you succeed in your job interview.

Are these questions suitable for beginners?

Yes, the questions include beginner-friendly content for freshers, alongside advanced topics for experienced professionals, catering to all career levels.

How can I prepare for technical interviews?

Access categorized technical questions with detailed answers, covering coding, algorithms, and system design to boost your preparation.

Are there resources for business and HR interviews?

Find tailored questions for business roles (e.g., finance, marketing) and HR roles (e.g., recruitment, leadership), perfect for diverse career paths.

Can I prepare for specific roles like consulting or management?

Yes, the platform offers role-specific questions, including case studies for consulting and strategic questions for management positions.

How often are the interview questions updated?

Questions are regularly updated to align with current industry trends and hiring practices, ensuring relevance.

Are there free resources for interview preparation?

Free access is available to a variety of questions, with optional premium resources for deeper insights.

How does this platform help with interview success?

Get expert-crafted questions, detailed answers, and tips, organized by category, to build confidence and perform effectively in interviews.