Laravel foreach循环返回的结果多于正确的结果

时间:2022-10-26 09:16:15

My foreach loop should only return 1 result, however, it returns three, of the same!

我的foreach循环应该只返回1个结果,但是,它返回三个,相同!

I'm using Blade for the template -

我正在使用Blade作为模板 -

{{count($alerts)}}

returns '1'. But the foreach loop below:

返回'1'。但是下面的foreach循环:

@foreach($alerts as $alert)
    <tr>
        <td>{{ $alerts->id }}</td>
    </tr>
@endforeach

The controller function passing the array of data is:

传递数据数组的控制器函数是:

public function getIndex()
{

    $id     = Auth::user()->id;    
    $alert = Alert::find($id);      
    $this->layout->content = View::make('index', array('alerts' => $alert));

}

A DD($alert) also returns just 1 result.

DD($ alert)也只返回1个结果。

Any help would be hugely appreciated.

任何帮助将非常感激。

1 个解决方案

#1


0  

To properly answer your question, I will post solution here:

为了正确回答您的问题,我将在此处发布解决方案:

$alert = Alert::find($id);

Will return only 1 object which has a unique identifier e.g. id. It should never turn more than 1 object.

将只返回一个具有唯一标识符的对象,例如ID。它永远不应该超过1个对象。

So, since your view has a foreach loop, it expects an array objects. Thus if you know that you received only one object, just encase it in array:

因此,由于您的视图具有foreach循环,因此它需要一个数组对象。因此,如果您知道您只收到一个对象,只需将其包含在数组中:

View::make('index', array('alerts' => array($alert)));

However, some other methods like Alert::all() or others may already return an array of objects, because you request many of them. In this case, you do not need to encase it in arrays.

但是,其他一些方法(如Alert :: all()或其他方法)可能已经返回了一个对象数组,因为您请求了许多对象。在这种情况下,您不需要将其包含在数组中。

#1


0  

To properly answer your question, I will post solution here:

为了正确回答您的问题,我将在此处发布解决方案:

$alert = Alert::find($id);

Will return only 1 object which has a unique identifier e.g. id. It should never turn more than 1 object.

将只返回一个具有唯一标识符的对象,例如ID。它永远不应该超过1个对象。

So, since your view has a foreach loop, it expects an array objects. Thus if you know that you received only one object, just encase it in array:

因此,由于您的视图具有foreach循环,因此它需要一个数组对象。因此,如果您知道您只收到一个对象,只需将其包含在数组中:

View::make('index', array('alerts' => array($alert)));

However, some other methods like Alert::all() or others may already return an array of objects, because you request many of them. In this case, you do not need to encase it in arrays.

但是,其他一些方法(如Alert :: all()或其他方法)可能已经返回了一个对象数组,因为您请求了许多对象。在这种情况下,您不需要将其包含在数组中。