Mastering Eloquent ORM: The Complete Guide
A complete guide to mastering Eloquent ORM, Laravel's database management tool
InSkillCoach
Mastering Eloquent ORM: The Complete Guide
Eloquent ORM is one of Laravel’s most powerful components. It greatly simplifies interacting with the database by letting you work with data as PHP objects.
Eloquent Basics
Creating a Model
php artisan make:model User -m
Structure of a Basic Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password'];
}
Relationships with Eloquent
One-to-One
public function profile()
{
return $this->hasOne(Profile::class);
}
One-to-Many
public function posts()
{
return $this->hasMany(Post::class);
}
Many-to-Many
public function roles()
{
return $this->belongsToMany(Role::class);
}
Advanced Queries
Filtering Data
// Simple search
User::where('active', true)->get();
// Complex queries
User::where('age', '>', 18)
->whereHas('posts', function($query) {
$query->where('published', true);
})
->get();
Aggregations
// Count
User::count();
// Sum
Order::sum('total');
// Average
Rating::avg('score');
Best Practices
1. Using Scopes
public function scopeActive($query)
{
return $query->where('active', true);
}
// Usage
User::active()->get();
2. Accessors and Mutators
// Accessor
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
// Mutator
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
3. Collections
$users = User::all()->filter(function ($user) {
return $user->posts_count > 3;
})->map(function ($user) {
return $user->only(['id', 'name', 'email']);
});
Performance Optimization
1. Eager Loading
// Without Eager Loading (N+1 problem)
$books = Book::all();
foreach ($books as $book) {
echo $book->author->name;
}
// With Eager Loading
$books = Book::with('author')->get();
2. Chunking for Large Datasets
User::chunk(100, function ($users) {
foreach ($users as $user) {
// Batch processing
}
});
Conclusion
Eloquent ORM is a powerful tool that greatly simplifies database management in Laravel. By mastering its features, you can build applications that are more performant and maintainable.
Additional Resources
About InSkillCoach
Training and technology expert
Coach specializing in advanced technologies and AI, backed by GNeurone Inc.
Certifications:
- AWS Certified Solutions Architect – Professional
- Google Cloud certifications
- Microsoft Certified: DevOps Engineer Expert
- Certified Kubernetes Administrator (CKA)
- CompTIA Security+
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion