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

princeoo7's avatar

How to refactor below query ?

I am having so difficult time in developing an optimized query for the below code:

$categories = Category::with(['videos' => function($q) {
                return $q->active();
            } , 'videos.translations'])->latest('id')->limit(config('app.latest_limit'))->where('status_id', Status::Active)->get();

in my category and videos table i have below code:

public function scopeActive($q)
    {
        return $q->where('status_id', Status::Active);
    }

    public function getActive()
    {
        return $this->active()->get();
    }

but if i do this,

$categories = Category::with(['videos' => function($q) {
                return $q->active();
            } , 'videos.translations'])->latest('id')->limit(config('app.latest_limit'))->getActive();

I get the below error,

Call to undefined method Illuminate\Database\Eloquent\Builder::getActive()

what worked for me as of now is:

$categories = Category::with(['videos' => function($q) {
                return $q->active();
            } , 'videos.translations' => function($q) {
                return $q->active();
            } ])->latest('id')->limit(config('app.latest_limit'))->active()->get();

also want to know how to optimize this more further if possible ...

0 likes
2 replies
MichalOravec's avatar
Level 75

What is it wrong with this?

$categories = Category::with(['videos' => function ($query) {
    $query->with('translations')->active();
}])->active()->latest('id')->limit(config('app.latest_limit'))->get();

By the way why do you name columns as status_id when it's not a foreign key? Better will be just status for that.

princeoo7's avatar

status_id is not a foreign key but I am using ENUMS so need it.

Please or to participate in this conversation.