1
votes

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

  • object(Category)#169 (20) { ["fillable":protected]=> array(1) { [0]=> string(4) "name" } ["connection":protected]=> NULL ["table":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(4) { ["id"]=> string(1) "1" ["name"]=> string(3) "foo1" ["created_at"]=> string(19) "2014-11-08 14:29:30" ["updated_at"]=> string(19) "2014-11-08 14:29:30" } ["original":protected]=> array(4) { ["id"]=> string(1) "1" ["name"]=> string(3) "foo1" ["created_at"]=> string(19) "2014-11-08 14:29:30" ["updated_at"]=> string(19) "2014-11-08 14:29:30" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) }

  • string(3) "foo1"

  • string(11) "foo2"

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

2

2 Answers

3
votes

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>
0
votes

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;
    }