phpforeachlaravellaravel-blade

Laravel foreach loop returning more results than correct


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

I'm using Blade for the template -

{{count($alerts)}}

returns '1'. But the foreach loop below:

@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.

Any help would be hugely appreciated.


Solution

  • 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.

    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:

    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.