Laravel use mysql indexing
Alright!! Let's do it.
First of all, I highly recommend using barryvdh/laravel-debugbar
(GitHub). This will tell you exactly how many queries were fired and how much time each one took.
Now, let's talk about optimisation.
- Use
select()
whenever possible. If a table has 20 columns and about 1000 rows and all your are doing is count() or sum() then fetching all the data doesn't make sense. - Your
\App\Models\Drivers
is being used multiple times. Here's what I recommend:- Query 1 ->
\App\Models\Drivers::where('is_approved', 1)->count();
- Query 2 ->
\App\Models\Drivers::where('is_approved', 0)->count();
- Solution ->
$drivers = \App\Models\Drivers::whereIn('is_approved', [0, 1])->get();
Here you can take adcantage of Laravel Collection$drivers->where('is_approved', 1)->count()
$drivers->where('is_approved', 0)->count()
Before your query was running twice and now with collect() only once.
- Query 1 ->
-
Indexing
is another solution. Check out this stack overflow discussion. - Use
caching
if you can. (docs) - Another thing to consider is how you are displaying this data. As you said the page is taking too long. Perhaps, you are using nested loops. (Can't say much since I don't see your blade file).
- Another thing that many developers miss is data type missmatch. If your
is_approved
column in sql is not an integer then while querying withwhere(string, int)
will result in load time. It's better to have same data type i.e.where(int, int)
Hope this helps. Cheers!