Skip to content

Instantly share code, notes, and snippets.

@seansch
Last active February 28, 2024 15:14
Show Gist options
  • Save seansch/05df7860d8518cba8d6de8aaa7658398 to your computer and use it in GitHub Desktop.
Save seansch/05df7860d8518cba8d6de8aaa7658398 to your computer and use it in GitHub Desktop.
Display all Laravel relationships
Route::get('relations', function () {
$modelList = [];
$path = app_path() . "/Models";
$results = scandir($path);
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
$filename = $result;
if (is_dir($filename)) {
$modelList = array_merge($modelList, getModels($filename));
}else{
$modelList[] = substr($filename,0,-4);
}
}
foreach($modelList as $model) {
$class = 'App\Models\\'.$model;
$reflector = new \ReflectionClass($class);
$relations = collect($reflector->getMethods())
->filter(
fn($method) => !empty($method->getReturnType()) &&
str_contains(
$method->getReturnType(),
'Illuminate\Database\Eloquent\Relations'
)
)
->all();
foreach($relations as $relation) {
echo class_basename($class).' ';
$method = explode("\\", $relation->getReturnType());
echo (end($method)).' ';
echo $relation->getName().'<br>';
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment