loading...

Laravel N + 1 queries detector

hungthai1401 profile image Thai Nguyen Hung ・1 min read

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:

Discussion

pic
Editor guide
Collapse
hieu3108 profile image
hieu3108

It's amazing :O

Collapse
hungthai1401 profile image
Thai Nguyen Hung Author

Please try to avoid N+1 queries