Mastering Laravel Eloquent: Advanced Tricks for Efficient Querying

ArjunAmrutiya
4 min readNov 16, 2023

1. Lazy Loading Relationships:

Lazy loading relationships can significantly improve performance by loading related data only when it’s needed. To enable lazy loading, you can use the with method.

$user = User::find(1);

// Lazy load the user's posts when needed
$posts = $user->posts;

2. Eager Loading Specific Columns:

When eager loading relationships, you can specify the columns you need, reducing the amount of data retrieved from the database.

$users = User::with(['posts' => function ($query) {
$query->select('id', 'title');
}])->get();

3. Global Scopes:

Global scopes allow you to define constraints that are automatically applied to all queries for a given model.

// Define a global scope for soft-deleted records
protected static function boot()
{
parent::boot();

static::addGlobalScope('softDeleted', function ($builder) {
$builder->where('deleted', 0);
});
}

4. Subquery in Select:

Use subqueries in the select method for complex queries without resorting to raw SQL.

$latestPosts =…

--

--

ArjunAmrutiya
ArjunAmrutiya

Written by ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!