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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️