Last active
September 20, 2019 13:31
-
-
Save vbalagovic/56e0485a7af20d16550eae08fa07395c to your computer and use it in GitHub Desktop.
Laravel trait for selective eager loading relations with custom columns
This file contains 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 | |
namespace App\Traits; | |
use Laravel\Scout\Searchable; | |
trait EagerLoadScopes | |
{ | |
public function scopeNoEagerLoads($query) | |
{ | |
return $query->setEagerLoads([]); | |
} | |
public function scopeSelectedEagerLoads($query, $selected) | |
{ | |
return $query->setEagerLoads($selected); | |
} | |
public function scopePreselectedEagerLoads($query, $selected) | |
{ | |
$values = []; | |
foreach ($selected as $key => $value) { | |
$values[$key] = function ($query) use($value) { | |
if (count($value[0]) > 1) { | |
$query->NoEagerLoads()->select($value[0]); | |
} | |
else { | |
$query->PreselectedEagerLoads($value[1]); | |
} | |
}; | |
} | |
return $query->setEagerLoads($values); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use it:
Import Trait to selected model
Use it in a model query as PreselectedEagerLoads (it's recursive so you can use it on as many relation levels as you want)