Skip to content

Instantly share code, notes, and snippets.

@vbalagovic
Last active September 20, 2019 13:31
Show Gist options
  • Save vbalagovic/56e0485a7af20d16550eae08fa07395c to your computer and use it in GitHub Desktop.
Save vbalagovic/56e0485a7af20d16550eae08fa07395c to your computer and use it in GitHub Desktop.
Laravel trait for selective eager loading relations with custom columns
<?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);
}
}
@vbalagovic
Copy link
Author

vbalagovic commented Sep 20, 2019

How to use it:

  1. Import Trait to selected model

  2. Use it in a model query as PreselectedEagerLoads (it's recursive so you can use it on as many relation levels as you want)

$projects = Project::whereStatus('active')
                    ->PreselectedEagerLoads(
                    [
                        'members'=> [['id'], ['user' => [['id', 'first_name', 'last_name', 'profile_img'], []]]],
                    ])
                    ->orderBy('created_at', 'desc')->get();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment