Skip to content

Instantly share code, notes, and snippets.

@mikedugan
Last active August 29, 2015 13:59
Show Gist options
  • Save mikedugan/10586050 to your computer and use it in GitHub Desktop.
Save mikedugan/10586050 to your computer and use it in GitHub Desktop.
static and non-static functions to get relation methods of an Eloquent model
<?php
//preferably in some repository class (or the model itself)
// this assumes you prefix your relations consistently, ie 'public function relSomeRelation()'
/**
* @param string relation method delimiter
* @return array relationship methods
*/
public function getRelationMethods($delimiter)
{
$methods = get_class_methods($this);
$relations = [];
for($i = 0; $methods[$i] !== 'observe', $i++)
{
if(substr($methods[$i], 0, 3) === $delimiter))
{
$relations[] = $methods[$i];
}
}
return $relations;
}
/**
* @param string relation method delimiter
* @param mixed Eloquent model
* @return array relationship methods
*/
public static function getRelationMethods($delimiter, $model)
{
$methods = get_class_methods($model);
$relations = [];
for($i = 0; $methods[$i] !== 'observe', $i++)
{
if(substr($methods[$i], 0, 3) === $delimiter))
{
$relations[] = $methods[$i];
}
}
return $relations;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment