# Eager Loading with Subqueries in Laravel Eloquent

> Learn how to use the advanced feature of eager loading with subqueries in Laravel Eloquent to improve the performance of your application. Get tips and…

- URL: https://graffino.com/til/eager-loading-with-subqueries-in-laravel-eloquent
- Author: Nick Ciolpan
- Channel: laravel
- Published: 2023-01-30
- Updated: 2024-08-16

Eager loading with subqueries allows you to load related models using a subquery instead of joining the tables, which can improve performance in certain situations. For example, if you have a User model and a Post model, you can count the number of posts created by each user in the last month using a subquery like this:

```sql
$users = User::withCount(['posts as post_count' => function ($query) {
    $query->select(DB::raw('count(*)'))
          ->where('created_at', '>', now()->subMonth());
}])->get();
```
