To detect N + 1 query, override getRelationshipFromMethod method in Eloquent

/**
 * 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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Powered by VuePress
Copyright 2010-2024 Thai Nguyen Hung all rights reserved.