Business vector created by fullvector —

Tips to speed up database query in Laravel

Hafiq Iqmal
8 min readFeb 23, 2021

Have you ever been wondering why your application slow even tough you already fix your application code?

Performance of the application is not depend on application itself. Application and database need to be tune together. For example, imagine 100 customers enter very big fancy restaurant (application) and there is only 2 waiter available (database). How can 2 waiter serve all the customer without keeping the customer in queue for long period? End up, the customer left the restaurant and never visit again.

Here is my 2 cents of tips to speed up database query based on my experience.

Table Indexing

Indexes is the most important part in Database. Indexing allow data retrieval efficiently faster. Indexes are used to quickly retrieve data without having to search every row in a table every time a database table is accessed. Small database wont be noticed but once it grows, the query getting time consuming.

How to use? All you need is to identify which column you want to take advantage from. For example, you have 1.3 million rows of users and you want to grab an email.

Without index, the process will be from top to bottom of the user data until it the email is found. Here is some comparison between with index and without it.

Without index — 750ms

With index — 2ms (400x faster)

In Laravel, the easy way is create a migration file to alter your desire table

Or if you currently on fresh project just add index to column you want to

Hafiq Iqmal

Tech Lead Developer | Software Engineer | Laravel Enthusiasts | CTF Newbie | Medium writer | UiTM Alumni | Husband | Proud father of a beautiful daughter

Recommended from Medium


See more recommendations