Register reusable query methods directly on the Builder so every model gains access without repeating logic.
Laravel's Macroable trait lets you add methods to the Builder at runtime. Register them in a service provider's boot() method and they become available on any query.
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
// In AppServiceProvider::boot()
Builder::macro('useIndex', function (string $table, string $index) {
return $this->from(DB::raw("{$table} WITH (INDEX({$index}))"));
});
Now any model can hint a specific index:
use App\Models\Order;
$orders = Order::query()
->useIndex('orders', 'orders_status_created_index')
->where('status', 'pending')
->get();
- Register on
Illuminate\Database\Eloquent\Builderfor Eloquent-level macros - The closure receives
$thisbound to the current builder instance - Useful for performance hints that aren't covered by the default query builder API
- Note: The
WITH (INDEX(...))syntax used above is specific to Microsoft SQL Server (T-SQL). MySQL usesFORCE INDEX(...)and PostgreSQL relies on the query planner (no direct index hints). Adjust the macro body to match your database engine.
Related Tips
View all tips →Reusable whereLike Macro with Relationship and Expression Support
Simplify multi-column wildcard searches across model columns, relationships, and raw SQL expressions using a powerful whereLike macro on the Eloquent Builder.
Refresh and Pessimistically Lock Models with refreshForUpdate() in Laravel 13.27
Laravel 13.27 adds refreshForUpdate(), reloading an existing model instance in-place with fresh database attributes while acquiring an exclusive FOR UPDATE row lock.