Introduction
Every modern web application interacts with a database. In traditional PHP, developers often use raw SQL queries or PDO to handle database operations. While powerful, this approach can quickly become repetitive and hard to maintain.
Laravel introduces Eloquent ORM (Object-Relational Mapper)—a powerful tool that allows you to interact with your database using models and expressive syntax instead of raw SQL. Eloquent is one of the most interviewed topics in Laravel, as it demonstrates how well you understand Laravel’s data layer.
What is Eloquent ORM?
Eloquent ORM maps database tables to PHP classes (models). Each model represents a table, and each instance of the model represents a row in that table.
👉 Instead of writing SQL like:
SELECT * FROM users WHERE active = 1 ORDER BY created_at DESC;
You can use Eloquent:
$users = User::where('active', 1)->orderBy('created_at', 'desc')->get();
Advantages of Eloquent ORM
1. Readable and Expressive Syntax
Eloquent uses a fluent, chainable syntax that makes queries more intuitive.
$users = User::where('status', 'active')->get();
👉 Much easier than writing raw SQL.
2. Relationships Made Easy
Most applications have related tables (users, posts, comments). Eloquent makes relationships simple.
One-to-Many Example (User → Posts):
class User extends Model { public function posts() { return $this->hasMany(Post::class); } } $user = User::find(1); foreach ($user->posts as $post) { echo $post->title; }
👉 No need to manually join tables—Eloquent handles it.
3. Security (Prevents SQL Injection)
Bad (raw SQL, insecure):
$result = DB::select("SELECT * FROM users WHERE email = '$email'");
Good (Eloquent, secure):
$user = User::where('email', $email)->first();
4. Mass Assignment & Fillable Attributes
// app/Models/User.php protected $fillable = ['name', 'email', 'password']; // Creating a user User::create([ 'name' => 'Karthick', 'email' => '[email protected]', 'password' => bcrypt('secret') ]);
👉 Prevents unauthorized fields from being mass-assigned.
5. Convenience Features
// Pagination $users = User::paginate(10); // Soft Deletes // Records marked as deleted instead of permanently removing // Timestamps // created_at and updated_at handled automatically // Query Scopes public function scopeActive($query) { return $query->where('active', 1); } $activeUsers = User::active()->get();
Eloquent vs Raw SQL / Query Builder
Feature | Raw SQL | Query Builder (DB::table) |
Eloquent ORM |
---|---|---|---|
Readability | Low | Medium | High (fluent syntax) |
Relationships | Manual joins | Manual joins | Built-in methods |
Security | Manual handling | Automatic binding | Automatic binding |
Best Use Case | Complex queries | Flexible, lighter than ORM | Everyday CRUD & relationships |
Common Beginner Mistakes
- Forgetting to define $fillable or $guarded → causes mass assignment errors.
- Using Eloquent for heavy loops instead of optimized queries.
- Not eager loading relationships (with()) → leads to N+1 query problem.
Example of fixing N+1 issue:
// Bad: multiple queries $posts = Post::all(); foreach ($posts as $post) { echo $post->user->name; } // Good: eager loading $posts = Post::with('user')->get();
Sample Interview Questions & Answers
Q: What is Eloquent ORM in Laravel?
A: Eloquent is Laravel’s ORM that maps database tables to PHP classes, making database interaction more expressive and object-oriented.
Q: How does Eloquent prevent SQL injection?
A: By using prepared statements and parameter binding under the hood.
Q: Difference between first() and get() in Eloquent?
A: first() returns a single model instance, while get() returns a collection of results.
Q: What is the N+1 query problem in Eloquent? How do you solve it?
A: It happens when related models trigger multiple queries inside a loop. Solution: use eager loading (with()).
Q: Can you disable timestamps in Eloquent?
A: Yes, set public $timestamps = false;
in the model.
Q: What’s the difference between soft delete and hard delete in Eloquent?
A: Soft delete marks a record as deleted (deleted_at
), while hard delete permanently removes it from the DB.
Mini Project Idea
👉 Build a Blog Application with Eloquent ORM:
- Models: User, Post, Comment.
- Relationships: One-to-many (User → Posts, Post → Comments).
- Use Eloquent scopes for filtering published posts.
- Add pagination with paginate(10).
Closing Note
Eloquent ORM is one of Laravel’s biggest strengths. It eliminates boilerplate SQL, makes relationships easy, and ensures security against injection attacks. For beginners, mastering Eloquent is a crucial step in becoming a professional Laravel web developer.
Laravel Framework Mastery
Why Choose Laravel?
→ Discover why Laravel dominates modern PHP development
Laravel MVC Architecture
→ Build scalable apps using Models, Views, and Controllers
Laravel Routing & Middleware
→ Control application flow with routes and middleware layers
Laravel Artisan & Productivity Tools
→ Supercharge your workflow with Artisan commands and dev tools
0 Comments