7 Laravel Eloquent Tricks That Will Clean Up Your Code

I've been writing Laravel code for years, and these are the Eloquent patterns I reach for in every project. None of them are groundbreaking on their own, but together they keep your codebase clean and your queries fast.

1. Query Scopes Over Repeated Where Clauses

If you're writing the same where clause in multiple places, extract it into a scope:

PHP

Now your queries read like English:

PHP

This is the foundation that Form Request patterns and action classes build on — your business vocabulary shows up in the code.

2. Limit Eager Loaded Records (Laravel 12)

This used to require a package. In Laravel 12, you can limit eagerly loaded records natively:

PHP

Each user gets their 5 most recent posts. No packages, no subquery hacks.

3. withWhereHas() — Filter and Eager Load in One Call

This is one of the most underused Eloquent methods. If you're doing a whereHas + with on the same relationship, you're writing the constraint twice:

PHP

withWhereHas combines both:

PHP

It filters the parent models (only users with published posts) and eager loads only the matching related records. One method, one constraint, zero duplication.

4. upsert() for Bulk Insert-or-Update

When importing data — translation files, CSV uploads, API syncs — you often need to insert new records or update existing ones. Don't loop:

PHP

Use upsert instead:

PHP

One query. Works with thousands of records. The uniqueBy parameter defines the conflict key, and update specifies which columns to update when a match is found.

5. Prevent N+1 with preventLazyLoading()

In your AppServiceProvider, add this for local development:

PHP

This throws an exception whenever a relationship is lazy-loaded instead of eager-loaded. It catches N+1 problems before they hit production. I wrote about how I test these patterns to make sure they stay fixed.

6. Subquery Selects for Computed Columns

Instead of loading entire relationships just to get a single value, use subquery selects:

PHP

Each user now has a latest_login_at attribute and an orders_count — all in a single query with no N+1. You can sort and filter by these computed columns too, which you can't do with accessors.

7. Cast Everything in the casts() Method

In Laravel 12, prefer the casts() method over the $casts property:

PHP

This gives you proper type coercion everywhere — in Blade, in API responses, in tests. No more checking if $order->is_gift is "1" or true or 1. Combined with PHP 8.4 property hooks, your models become even more expressive.

The Compound Effect

None of these tricks are complex. But when you use all of them consistently, you end up with a codebase that's readable, performant, and hard to break. That's the goal.

Related articles