1

I realized something I can't figure out by myself.

I get a different result when I loop through first in a Controller and pass then the result to my view. Versus loop straight in my view.

For instance: I have this in my Controller:

  public function index()
{
    $subscribers = Subscriber::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->get();

    foreach ($subscribers as $key => $subscriber) {
      $var = $subscriber->name;
    }

    return view('backend.newsletter.contacts.index')->withSubscribers($subscribers)
                                                    ->withVar($var);
}

by using {{$var}} in my view I get only "John" as a result.

But when I use the foreach loop in my view instead of in the Controller:

@foreach($subscribers as $key => $subscriber)
 {{$subscriber->name}}
@endforeach

I get two results, "John" and "Dan". This makes totaly sense as I have two entries in my DB.

So how does it come that I get two different results here ?

3 Answers 3

5

When you're doing this:

foreach ($subscribers as $key => $subscriber) {
    $var = $subscriber->name;
}

With each iteration you overwrite $var so you always get the last value. For example, if you have ['Dan', 'John, 'Alice', 'Alan'], you'll get Alan.

Good practice is too pass data to a view and iterate it with @foreach.

Sign up to request clarification or add additional context in comments.

Comments

0

Because only the last loop iteration is stored in $var.

You need to

$var = [];
foreach ($subscribers as $key => $subscriber) {
     $var[] = $subscriber->name;
}

Comments

0

You are overriding $var in the loop.

Try this:

$var = []; foreach ($subscribers as $key => $subscriber) { $var[] = $subscriber->name; // Appends name to array }

Comments

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.