DEV Community

Thai Nguyen Hung
Thai Nguyen Hung

Posted on

2 1

Laravel use or force index on a query

When you want to use or force index with Query Builder in Laravel, you can do it

$query = SomeModel::query()->getModel()
$query->setTable(DB::raw($query->getTable() . ' USE INDEX(index_name)'))
$results = $query->get();

In complex queries with with() previous solution doesn't work. Better to overwrite base query 'from' value instead:

$query = SomeModel::with('some_relations')...->orderBy();
$query->getQuery()->from(DB::raw($query->getQuery()->from . ' USE INDEX (index_name)'));
// or just
$query->getQuery()->from(DB::raw('`table` USE INDEX (index_name)'));
$results = $query->get();

Hope it will helpful with you.

Top comments (2)

Collapse
 
frikishaan profile image
Ishaan Sheikh

Is it not possible with Eloquent?

Collapse
 
hungthai1401 profile image
Thai Nguyen Hung

no, it's possiable

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay