What is Eloquent in Laravel?
Eloquent is Laravel’s built-in Object-Relational Mapping (ORM) system. It provides a simple, elegant, and expressive syntax for interacting with your database, allowing developers to work with database records using PHP objects rather than raw SQL queries.
Why Eloquent Matters
Before Eloquent, developers often had to write repetitive SQL queries, manually map results to objects, and handle relationships using complex joins. Eloquent abstracts all of that, making database interactions more intuitive, maintainable, and secure. It fully embraces Laravel’s philosophy of “developer happiness”.
Traditional SQL vs Eloquent (Why It Exists)
Goal: Fetch published blog posts with their author names.
❌ Without Eloquent (Raw SQL)
$sql = "SELECT posts.title, users.name
FROM posts
JOIN users ON posts.user_id = users.id
WHERE posts.published = 1";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . ' : ' . $row['title'];
}✅ With Eloquent (Laravel Way)
// Post.php
public function user()
{
return $this->belongsTo(User::class);
}
$posts = Post::with('user')->where('published', true)->get();
foreach ($posts as $post) {
echo $post->user->name . ' : ' . $post->title;
}Core Features of Eloquent
- Active Record Implementation: Each database table has a corresponding “Model” in Eloquent, and each model instance represents a row in the table.
- Relationships: Easily define one-to-one, one-to-many, many-to-many, polymorphic, and more relationships between models.
- Query Builder Integration: Eloquent uses a fluent, chainable syntax for building complex queries while keeping code readable.
- Mass Assignment & Factories: Protect against mass-assignment vulnerabilities and easily generate fake data for testing.
- Mutators & Accessors: Transform attributes automatically when retrieving or saving data.
- Events & Observers: Trigger actions automatically on model events like creating, updating, deleting.
Basic Example: Fetching Data
use App\Models\User;
// Retrieve all users
$users = User::all();
// Retrieve a user by primary key
$user = User::find(1);
// Retrieve users with a condition
$admins = User::where('role', 'admin')->get();Example: Creating & Updating Records
use App\Models\Post;
// Create a new post
$post = new Post;
$post->title = 'My First Blog Post';
$post->body = 'This is the content of the blog post.';
$post->save();
// Mass assignment (requires $fillable in the model)
Post::create([
'title' => 'Second Post',
'body' => 'Another blog post example.'
]);
// Update an existing post
$post = Post::find(1);
$post->title = 'Updated Title';
$post->save();Defining Relationships
Eloquent makes defining relationships simple:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Usage
$user = User::find(1);
foreach ($user->posts as $post) {
echo $post->title;
}Advanced Features
- Query Scopes: Define reusable query fragments to keep your models DRY.
- Attribute Casting: Automatically cast JSON, dates, or custom objects.
- Lazy & Eager Loading: Optimize performance by controlling when relationships are loaded.
- Soft Deletes: Mark records as deleted without actually removing them from the database.
- Factory & Seeding Enhancements: Generate test data efficiently with modern factories using closures and Faker integration.
Real-World Example: Blog Application
$posts = Post::with('user')
->where('published', true)
->orderBy('created_at', 'desc')
->take(10)
->get();
foreach ($posts as $post) {
echo $post->user->name . ': ' . $post->title . "\n";
}Conclusion:
Eloquent is much more than a database abstraction; it’s a full-featured ORM that makes working with databases in Laravel expressive, elegant, and powerful. From simple CRUD operations to complex relationships and performance optimization, Eloquent allows developers to focus on business logic rather than repetitive SQL boilerplate.
Related Answers
Still need help?
Talk to our Laravel experts
We've handled GDPR/CCPA compliance for dozens of EU & US Laravel.
