Reputation: 3
We have following models -
Post
----------------------------------------------
| id | title | text | creator | status | etc |
----------------------------------------------
| | | | | | |
----------------------------------------------
creator -> belongsTo User
group -> belongsTo group
User
posts -> hasMany Posts
avatar -> hasOne Media
Media
user -> belongsTo User
Group
post - belongsTo Post
When I fetch posts using eloquent I can use transform function to transform post attributes but unable to transform relations in the Post collections.
$posts = Post::where('status', 'active')
->with(['creator.avatar','group'])
->get();
$posts->transform(function($post) {
$post->title = 'Transformed'; // works
$post->creator->avatar = ['path'=>'/avatar/','file_name'=>'a.png']; // does not work
});
Upvotes: 0
Views: 2294
Reputation: 383
When you call $post->creator
, you're essentially calling $post->getRelation('creator')
via a "magic method".
This is important because it means that you're setting a property on the object returned by the getRelation
method, you are not updating the creator relationship by reference - so when you call getRelation('creator')
again, the original relationship value is returned.
Therefore, to achieve what you want to accomplish, you need to overwrite the creator
relation value:
$posts->transform(function ($post) {
$post->title = 'Transformed';
$creator = $post->creator;
$creator->avatar = [
'path' => '/avatar/',
'file_name' => 'a.png'
];
$post->setRelation('creator', $creator); // or $post->creator = $creator;
});
Upvotes: 6