DEV Community

Thai Nguyen Hung
Thai Nguyen Hung

Posted on

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