Created
August 16, 2019 10:08
-
-
Save sebastiaanluca/aafc90c1b25a70b499a319631171b260 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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