I'm trying to traverse through complex eloquent model relationships/attributes, and I'd like to use a simple dot structure to iterate through this, similar to how you can traverse arrays with Arr::get()
Example:
$data = [
'foo' => [
'bar' => [
'key' => 'value'
]
]
];
$value = Arr::get($data, 'foo.bar.key'); // returns 'value'
I've tried using
$value = Arr::get($model, 'relation.subrelation.attribute')
However this fails and aways returns null, even though eloquent models support ArrayAccess.
Does laravel have a simple way to accomplish this?
For all those wondering, I've managed to figure out a solution by modifying the arr::pull() function to work specifically with models:
public static function traverse($model, $key, $default = null)
{
if (is_array($model)) {
return Arr::get($model, $key, $default);
}
if (is_null($key)) {
return $model;
}
if (isset($model[$key])) {
return $model[$key];
}
foreach (explode('.', $key) as $segment) {
try {
$model = $model->$segment;
} catch (\Exception $e) {
return value($default);
}
}
return $model;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments