Skip to content

Instantly share code, notes, and snippets.

@sebastiaanluca
Created August 16, 2019 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastiaanluca/aafc90c1b25a70b499a319631171b260 to your computer and use it in GitHub Desktop.
Save sebastiaanluca/aafc90c1b25a70b499a319631171b260 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\Relation;
use RuntimeException;
trait PreventsLazyLoading
{
/**
* Get a relationship value from a method.
*
* @param string $method
*
* @return mixed
*
* @throws \RuntimeException
*/
protected function getRelationshipFromMethod($method)
{
$relation = $this->$method();
if ($this->shouldPreventLazyLoadingRelation($relation)) {
throw new RuntimeException(sprintf(
'Unable to lazy load relation %s in model %s',
$method,
static::class,
));
}
return parent::getRelationshipFromMethod($method);
}
/**
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation
*
* @return bool
*/
protected function shouldPreventLazyLoadingRelation(Relation $relation) : bool
{
return $this->exists
&& config('database.prevent_lazy_loading_relations')
&& static::isLazyLoadedRelation($relation);
}
/**
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation
*
* @return bool
*/
private static function isLazyLoadedRelation(Relation $relation) : bool
{
return ! in_array(
get_class($relation),
static::lazyLoadedRelations(),
true
);
}
/**
* @return array
*/
private static function lazyLoadedRelations() : array
{
return [
BelongsTo::class,
HasOne::class,
HasOneThrough::class,
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment