DEV Community

Thai Nguyen Hung
Thai Nguyen Hung

Posted on

2 1

Laravel N + 1 queries detector

Problem:

My working has many many performance problems. All most of case is N + 1 queries. I have to spent a lot time to find them ...and just feel angry and tired.
There is a packages helpful with you: https://github.com/beyondcode/laravel-query-detector
A thank you to an author for a good package.
But as a developer, I want to make a simple solution by me.

Solution:

After reading Laravel source code, I have found a way to detect N + 1 queries in some lines of code.

class LazyLoadingException extends \Exception
{

}
trait LazyLoadingDetector
{
    /**
     * Get a relationship value from a method.
     *
     * @param  string $method
     *
     * @return mixed
     *
     * @throws \LogicException
     * @throws \LazyLoadingException
     */
    protected function getRelationshipFromMethod($method)
    {
        $modelName = static::class;
        $exception = new LazyLoadingException("Attempting to lazy-load relation '$method' on model '$modelName'");
        if (! app()->isLocal()) {
            logger()->warning($exception->getTraceAsString());
            goto next;
        }

        report($exception);

        next:
        return parent::getRelationshipFromMethod($method);
    }
}

Usage:

class User extends Authenticatable
{
    use LazyLoadingDetector;
}

You will see the report in logs file if attempt N + 1 queries.

P/s:

I am wondering I would publish a simple package.
Please tell me your opinions and give me a star.

Refs:

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (2)

Collapse
 
hieu3108 profile image
hieu3108

It's amazing :O

Collapse
 
hungthai1401 profile image
Thai Nguyen Hung

Please try to avoid N+1 queries

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay