2

I am writing code to sort eloquent relationship instance in the parent.

$categories = CategoryMain::with('subs')->get();
    foreach($categories as &$category){
        $category->sub = $category->subs->sortBy('name');
    }

I get the correct arrangement inside the foreach loop, which i verify by doing die(var_dump());,

However, once it is outside, it seems like it is not changed at all. Why is it happening?

5
  • please show mode code with the $categories. Commented Jun 15, 2017 at 3:42
  • those are the only code.. What i want to achieve is sorting the subs, which is already correct in the foreach, but after it finishes, it does not modify the value @KrisRoofe Commented Jun 15, 2017 at 3:43
  • You aren't saving the models, so nothing will change Commented Jun 15, 2017 at 3:47
  • $category->save() Commented Jun 15, 2017 at 3:47
  • 1
    sub vs subs. Are you sure you've spelled these correctly? Commented Jun 15, 2017 at 4:25

1 Answer 1

2

Try something like this and see what is the output:

$categories = CategoryMain::with('subs')->get();

$counter = 0;
foreach($categories as $category) {
    $categories[$counter]->sub = $category->subs->sortBy('name');
    $counter++
}
//output the data of catgories
dd($categories);
Sign up to request clarification or add additional context in comments.

2 Comments

this way will work i think.. but why we cannot directly change it using the iterator on for loop?
The reason for using an iterator with foreach loop is to save the new values that are generated inside the loop to the original Collection object. The $category variable is just a local variable which has scope limited to the loop itself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.