jwong
jwong

Reputation: 358

Laravel 4 weird first result in the foreach loop

This is something in my getIndex() function in the controller

public function getIndex() {

    $categories = Category::all();

    foreach ($categories as $category) {
        $categories[$category->id] = $category->name;
    }
......
}

So I expected to get all the category names from the loop.

However, for example, if I want to get the result by doing this in the view

        @foreach ($categories as $name) 
            <ul>
                <li>{{var_dump($name)}}</li>
            </ul>
        @endforeach

The result is like

Where does the first result come from and how do I get rid of it? Thanks!

Upvotes: 1

Views: 268

Answers (2)

The Alpha
The Alpha

Reputation: 146269

You may try this:

// Get an associative array
$categories = Category::lists('name', 'id');

Then pass it to the view do the loop:

<ul>
    @foreach ($categories as $id => $name) 
        <li>{{$name}}</li>
    @endforeach
</ul>

Upvotes: 4

D&#225;vid Horv&#225;th
D&#225;vid Horv&#225;th

Reputation: 4320

The first item remains from the first $categories array. Its id field's value is 1, but the key in the array is zero, of course. No item exists with a zero id, so it will be not overritten.

It is better to write something like this:

public function getIndex() {

    $categoryList = Category::all();

    foreach ($categoryList as $oCategory) {
        $categories[$oCategory->id] = $oCategory->name;
    }

    // ......
}

Or simply:

    foreach (Category::getAll as $category) {
        $categories[$category->id] = $category->name;
    }

Upvotes: 0

Related Questions