May 27 2015

Disabling Eager Loading Eloquent Model Relations in Laravel 4 and 5

Category: Laravel,Laravel 5FractalizeR @ 1:12 pm

Since accidental lazy-loading almost always lead to performance problems, I was seeking a way to disable it. The solution is easy. Just define somewhere the following trait and use it in your model when you need to disable lazy loading:

* Class OnlyEagerLoadedModelTrait
 * @package FH\Stock\Model
trait EagerLoadOnlyTrait
     * @param string $method
    protected function getRelationshipFromMethod($method)
        $modelName = static::class;
        throw new LogicException(
            "EagerLoadedOnlyTrait: Attempting to lazy-load relation '$method' on model '$modelName'"


class CategoryUser extends Eloquent
    use EagerLoadOnlyTrait;

Tags: , , ,

Leave a Reply

You must be logged in to post a comment. Login now.