🚀 10 Laravel Eloquent Tricks You Didn’t Know (But Will Love!)
Arafat Hossain Ar

Arafat Hossain Ar @arafatweb

About: Fullstack Developer with the ability of Design and Develop rich Web & Desktop Applications.

Location:
Dhaka, Bangladesh
Joined:
Aug 29, 2021

🚀 10 Laravel Eloquent Tricks You Didn’t Know (But Will Love!)

Publish Date: Apr 21
8 0

Laravel’s Eloquent ORM is one of the most powerful tools in the PHP ecosystem. But let’s be honest, most developers stick to get(), where(), and find(). Eloquent actually has many hidden features that can help you write cleaner, faster, and more maintainable code.

In this blog, you’ll discover 10 lesser-known Eloquent methods and techniques that will level up your Laravel skills.

Table of Contents

  1. withWhereHas() – Filter and Eager Load in One Query
  2. cursorPaginate() – Paginate Large Datasets Efficiently
  3. sole() – Ensure Only One Record Exists
  4. upsert() – Insert or Update Multiple Rows at Once
  5. lazy() – Loop Through Big Data Without Memory Issues
  6. findMany() – Fetch Multiple Records Easily
  7. whereBelongsTo() – Query Using a Model Instance
  8. is() – Compare Models Safely
  9. firstOrCreate() and updateOrCreate() – Atomic Record Handling
  10. tap() – Inspect Queries in the Middle of a Chain

1. withWhereHas() – Filter and Eager Load in One Query

$posts = Post::withWhereHas('comments', function ($query) {
    $query->where('approved', true);
})->get();
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Avoids multiple queries
  • Reduces memory usage
  • Keeps your code concise

2. cursorPaginate() – Paginate Large Datasets Efficiently

$users = User::orderBy('id')->cursorPaginate(50);
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Great for infinite scroll or continuous loading
  • Handles large datasets without slowing down

3. sole() – Ensure Only One Record Exists

$user = User::where('email', 'admin@example.com')->sole();
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Eliminates silent bugs
  • Ensures data uniqueness and consistency

4. upsert() – Insert or Update Multiple Rows at Once

User::upsert(
    [
        ['email' => 'one@test.com', 'name' => 'User One'],
        ['email' => 'two@test.com', 'name' => 'User Two'],
    ],
    ['email'], // Unique column
    ['name']   // Columns to update
);
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Prevents duplicates
  • Minimizes database load

5. lazy() – Loop Through Big Data Without Memory Issues

User::where('active', true)->lazy()->each(function ($user) {
    // Process user
});
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Keeps memory usage low
  • Perfect for batch jobs, exports, and reporting

6. findMany() – Fetch Multiple Records Easily

$users = User::findMany([1, 3, 5]);
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Cleaner syntax
  • More efficient than multiple queries

7. whereBelongsTo() – Query Using a Model Instance

Post::whereBelongsTo($user)->get();
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • More readable and expressive
  • Helps when working directly with models

8. is() – Compare Models Safely

if ($post->author->is($currentUser)) {
    // Perform action
}
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Safer than manual comparisons
  • Works with unsaved models too

9. firstOrCreate() and updateOrCreate() – Atomic Record Handling

$user = User::updateOrCreate(
    ['email' => 'someone@example.com'],
    ['name' => 'Someone New']
);
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Avoids duplicate records
  • Clean and readable

10. tap() – Inspect Queries in the Middle of a Chain

User::where('active', true)
    ->tap(function ($query) {
        logger($query->toSql());
    })
    ->get();
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:

  • Great for debugging
  • Keeps the method chain intact

Final Thoughts

Laravel Eloquent is packed with powerful features that go beyond the basics. By using these lesser-known methods, you can write code that is not only more efficient but also easier to maintain and scale.

Whether you're building APIs, admin panels, or full-blown applications, these tips will give your Laravel skills an extra edge.

Useful Links

Comments 0 total

    Add comment