Use EXPLAIN to see how your query uses any available indexes. It might indicate where indexes are needed.
Aside, this
->where('report_status', '!=', 3)
->where('report_status', '!=', 1)
can be replaced with
->whereNotIn('report_status', [1, 3])
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey!
We have a lot of data in the database and I noticed this query is loading so slow. Could you please help me and convert this into a DB query builder code which is fully optimized?
Reviews::with('website', 'user')->where('report_status', '!=', 3)->where('report_status', '!=', 1)->latest()->take(5)->get(),

I tried with
DB::table('reviews')
->where('report_status', '!=', 3)
->where('report_status', '!=', 1)
->join('websites', 'websites.id', '=', 'reviews.website_id')
->join('users', 'users.id', '=', 'reviews.user_id')
->selectRaw('reviews.*, websites.web_seo_url as website_web_seo_url, users.name as user_name, users.profile_photo_path as user_profile_photo_path')
->orderBy('created_at', 'desc')
->limit(5)
->get()
but it's even more slower
@Laralex you can alter the table in a separate migration like this
Schema::table('reviews', function (Blueprint $table) {
$table->index('created_at');
});
Be aware that a compound index ($table->index(['website_id', 'review_stars', 'report_status', 'created_at']); ) might not be at all appropriate for the query optimisation you are attempting!
Please or to participate in this conversation.