How to get through model relationships in laravel with dot syntax

I am trying to get through the complex eloquent relationships / attributes of a model, and I would like to use a simple point structure to iterate it, similar to how you can move arrays using Arr::get()

Example:

 $data = [ 'foo' => [ 'bar' => [ 'key' => 'value' ] ] ]; $value = Arr::get($data, 'foo.bar.key'); // returns 'value' 

I tried using

 $value = Arr::get($model, 'relation.subrelation.attribute') 

However, this fails, and aways returns null, although the eloquent models support ArrayAccess.

Does laravel have an easy way to do this?

+6
source share
2 answers

For everyone who wondered, I managed to figure out a solution by changing 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; } 
+3
source

Eloquent Models returns a Collection that does not match Array in PHP. You can convert it to an array using the toArray() function

 $my_model->toArray(); 

Then you will get an array. But remember that it converts all nested models inside the main model into an array.

-1
source

All Articles