Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Foreach loop update object by reference

When i tried following loop with reference, i got error.

foreach($category->posts as &$post)
{
    $post->custom = value;
}

Error

Fatal error: An iterator cannot be used with foreach by reference in

How can i modify the object with keep it and without creating new array?

Thanks

$category->posts is not an array.



9.1k
Accepted
answer

I solved with afterFetch method on model like following:

public function afterFetch()
{       
    $this->custom = "Hello World";
}