Laravel use or force index on a query

hungthai1401 profile image Thai Nguyen Hung ・1 min read

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.


markdown guide