Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jinsonjose's avatar

Query too slow when operating with 1 million data on table

How to optimize the query? any idea?

How to speed up this query ??

$members = DB::table('users') ->where('users.type', 'member') ->join('user_profiles', 'users.id', '=', 'user_profiles.user_id') ->where('user_profiles.profile_status', 'approved') ->select('users.name', 'users.email', 'users.location', 'users.type', 'users.ip', 'users.last_login', 'users.created_at', 'users.id', 'user_profiles.profile_status') ->skip(($page - 1) * $this->perPage) ->limit($this->perPage) ->get();

0 likes
11 replies
automica's avatar
automica
Best Answer
Level 54

@jinsonjose if you use eloquent and have a relationship with your User hasMany UserProfile set up then you can with

$user = User::where('users.type', 'member')->with('userProfiles')->whereHas(
    'userProfiles', function ($query) {
        $query->where('profile_status', 'approved');
    }
)->select('users.name', 'users.email',
    'users.location', 'users.type', 'users.ip', 'users.last_login', 'users.created_at', 'users.id',
    'user_profiles.profile_status')->skip(($page - 1) * $this->perPage)->limit($this->perPage)->get();

not sure what

when operating with 10 lakhs data

means though. Can you explain?

1 like
SilenceBringer's avatar

@jinsonjose be sure all columns used for joining and filtering (users.type, user_profiles.user_id and user_profile.profile_status) are indexes

jinsonjose's avatar

@automica in user table have 10 lakhs data its take around 15 seconds for that query to result

MichalOravec's avatar

Do you have a problem to write that you have a million rows in the table? Lakhs uses in your country not here...

DirkZz's avatar

Can you do ->toSql() instead of ->get() and run the query manually with the word "EXPLAIN " in front of it?

jinsonjose's avatar

@automica


$user = User::where('users.type', 'member')->with('userProfiles')->whereHas(
    'userProfiles', function ($query) {
        $query->where('profile_status', 'approved');
    }
)->select('users.name', 'users.email',
    'users.location', 'users.type', 'users.ip', 'users.last_login', 'users.created_at', 'users.id',
    'user_profiles.profile_status')->skip(($page - 1) * $this->perPage)->limit($this->perPage)->get();

this query returns error:

    "message": "Call to undefined method App\User::userProfiles()",
    "exception": "BadMethodCallException",
automica's avatar

@jinsonjose that’s throwing an error as you don’t have that eloquent relationship set up in your User model.

User hasMany UserProfile

// User model 

public function userProfiles() {

return $this->hasMany(UserProfile::class);
}

Please or to participate in this conversation.