Shehzad
Shehzad

Reputation: 347

Laravel - foreach local variable is overwriting the global variable

Today i have faced a very strange issue. I have a controller from where i am sending three variables to the view sections thread and threads. In my view i am looping through all the sections with foreach loop like this:

@foreach($sections as $i => $section)

and for each section i am creating a div and giving that id like this:

id="{{ $thread->slug }}-{{ $section->slug }}

now in this div i am looping through all the threads like this:

@foreach($threads as $thread)

and creating div for each thread. Now the problem is that when the loop for threads completes the last item in the threads which is store in local variable thread, overwrites the thread variable sent from the view. Now, i know that to resolve this i can rename the local variable in foreach loop to something else but my question is why is this happening? why is this local variable overwriting my global variable ?

Here is my controller:

    public function show($slug)
    {
        return view('thread.show')
            ->with('sections', Section::all())
            ->with('threads', Thread::all())
            ->with('thread', Thread::where('slug', $slug)->first());
    }

View:

@foreach($sections as $i => $section)
 <div class="tab-pane fade" id="{{ $thread->slug }}-{{ $section->slug }}">
  @foreach($threads as $thread)
   <div class="card mb-3">
    {{--/// Some Html--}}
   </div
  @endforeach
 </div>
@endforeach

Now here is the screenshot of the rendered html:

Rendered Html

The thread name is page-172 the id for the first div is rendered fine but look at he id of other two divs section-341 which is the last item in the threads

Upvotes: 4

Views: 968

Answers (1)

Stratadox
Stratadox

Reputation: 1311

but my question is why is this happening? why is this local variable overwriting my global variable

Because php cannot differentiate between $thread and $thread.

While you could expect the variable $thread in the context of foreach($threads as $thread) to live only within the foreach body, in php this is not the case.

The local variable $thread exists within the scope of your view, not your loop body. Since php does not differentiate, the original is overwritten.

Upvotes: 6

Related Questions