Laravel Eloquent ORM is an Active Record implementation that abstracts SQL operations into expressive PHP syntax using models. Behind every Eloquent call, Laravel translates your methods into raw SQL using a layered structure of classes.
🔁 Eloquent Internal Workflow
When you call an Eloquent method (e.g., User::where(...)->first()), Laravel processes it through these core steps:
1. Model Instantiation:
Laravel bootstraps your model (e.g., User extends Model) and applies traits (like HasAttributes, HasRelationships, etc.).
2. Query Builder Initialization:
The newQuery() method returns an instance of Illuminate\Database\Eloquent\Builder, which wraps the core Illuminate\Database\Query\Builder.
3. SQL Compilation:
Query Builder methods like ->where() or ->with() are chained and eventually converted into raw SQL by the toSql() method.
4. Database Connection & Execution:
Laravel uses DB::connection() and PDO to execute the query.
5. Hydration into Models:
The raw database rows are converted (hydrated) into fully functional Eloquent model instances.
6. Model Events & Mutators:
Laravel triggers lifecycle events like retrieved, saving, etc., and applies accessors/mutators if defined.
🧪 Example 1: Query Builder
$user = User::where('email', 'jane@example.com')->first();
💡 Behind the scenes:
SELECT * FROM users WHERE email = 'jane@example.com' LIMIT 1;
Laravel executes this, then hydrates the result into a User object.
🧪 Example 2: hasOne Relationship
// app/Models/User.php
public function profile()
{
return $this->hasOne(Profile::class);
}
// On Controller
$user = User::find(1);
$profile = $user->profile; // Auto-fetches from DB
🔍 Internally:
SELECT * FROM profiles WHERE user_id = 1 LIMIT 1;
Laravel hydrates the result into a Profile model and attaches it to the $user object.
🧪 Example 3: belongsTo Relationship
// app/Models/Profile.php
public function user()
{
return $this->belongsTo(User::class);
}
// On controller
$profile = Profile::find(10);
$user = $profile->user;
🔍 Internally:
SELECT * FROM users WHERE id = [profile.user_id] LIMIT 1;
Again, Laravel hydrates the User result and associates it with the Profile instance.
✅ Key Takeaways:
- Eloquent sits on top of Laravel's Query Builder and PDO.
- Relationships like hasOne and belongsTo internally generate foreign key–based queries.
- Eloquent uses hydration, events, and casting to make model objects fully interactive.
- Under the hood, it’s still structured SQL, just with expressive syntax and clean abstraction.
Top comments (0)