Skip to content

Instantly share code, notes, and snippets.

@KristianI
Created September 30, 2017 01:22
Show Gist options
  • Save KristianI/9c98093dd803e5c8f3f033b0c6af5fe8 to your computer and use it in GitHub Desktop.
Save KristianI/9c98093dd803e5c8f3f033b0c6af5fe8 to your computer and use it in GitHub Desktop.
Eager loading (result caching) of Laravel eloquent model queries. Could be used to batch load a bunch of rows from the database, and later on same execution being retrieved by Modelname::findEagerLoaded($id); instead of Modelname::find($id). This trait will reduce number of database queries, but for my test case the overall load time was the sam…
<?php
namespace App\Traits;
trait EagerLoad
{
protected static $eagerLoaded = [];
/**
* Eager load a items in model.
*
* @param array $ids The ids to eager load.
* @return void
*/
public static function eagerLoad($ids)
{
self::addItems( self::whereIn('id', $ids)->get() );
}
/**
* Remove items from list of eager loaded items.
*
* @param array $ids The ids to remove.
* @return void
*/
public static function removeEagerLoaded($ids)
{
self::$eagerLoaded = array_diff_key(self::$eagerLoaded, array_flip($ids));
}
/**
* Find eager loaded or find from database.
*
* @param int $id The ID to find.
* @return object
*/
public static function findEagerLoaded($id)
{
if (isset(self::$eagerLoaded[$id])) {
return self::$eagerLoaded[$id];
}
$item = self::find($id);
self::addItem($id, $item);
return $item;
}
private static function addItems($items)
{
if (empty($items)) {
return false;
}
foreach($items as $item) {
self::$eagerLoaded[$item->id] = $item;
}
}
private static function addItem($id, $item)
{
if ($item) {
self::$eagerLoaded[$id] = $item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment