Downloads
Stars
Version
Log (or disable) Eloquent lazy-loaded relationships in Laravel 5 to speed up your application.
Eloquent's lazy-loading is great. You can do Group::find($id)
in your controller, and then loop through
$group->users
in your template without needing to worry about the database queries that run under-the-hood.
The problem comes when you try and loop through $group->users->addresses
, or some other relation. You may
inadvertently be running an SQL query for each iteration of that loop. If you are running a site that gets
millions of hits a day, this might not be a good thing!
By logging where your script is lazy-loading relationships, you may be able to optimize your application to avoid unnecessary database calls. At the very least you can see where the bottlenecks are. And, if you want, you can disable lazy-loading entirely and only allow explicitly loaded relations from being accessed.
Install the package via composer:
$ composer require cviebrock/eloquent-log-lazy-loading
That's it!
Your models should use the LogLazyLoading
trait:
use Cviebrock\EloquentLogLazyLoading\LogLazyLoading;
class MyModel extends Eloquent
{
use LogLazyLoading;
}
When you attempt to lazy load a relationship, the package will report a LazyLoadingException
exception and continue
normally (i.e. it will load the relationship). This is a great way to check where your application is doing
lazy-loading and allows you to refactor, possibly reducing the number of database queries that are called.
However, if you really want to go hard core and halt your application when a relation is lazy-loaded, then just
set the disableLazyLoading
property on your model to true
. The exception will be thrown, and not just reported.
use Cviebrock\EloquentLogLazyLoading\LogLazyLoading;
class MyModel extends Eloquent
{
use LogLazyLoading;
protected $disableLazyLoading = true;
}
Thanks to everyone who has contributed to this project.
Please use Github for reporting bugs, and making comments or suggestions.
See CONTRIBUTING.md for how to contribute changes.
eloquent-taggable was written by Colin Viebrock and is released under the MIT License.
Copyright (c) 2017 Colin Viebrock