Currently, my application uses quite a few foreach loops, to iterate through an array pulled through the database.
In order for the user to access the page, whether they have 0,1 or 100 results, I have to use three IF statements, to stop the foreach loop from breaking. This check is solely for 0 and 1 results, anything greater works fine.
I imagine I'll have several more pages to iterate through certain database results, and surely using 3 IF statements isn't the most efficient way?
An example:
Controller:
public function getArchived()
{
$alert = Alert::with('location')->where('user_id', '=', Auth::user()->id)
->onlyTrashed()
->first();
$this->layout->content = View::make('agents.alert.archived',
array('alert' => $alert));
}
View (shortened):
@if((count($alert) > 1)
@foreach($alert->alerts as $alert)
{{ $alert->id }}
@endforeach
@elseif ((count($alert) > 0)
{{ $alert->id }}
@else
<p>You have no results</p>
@endif
Is there a check one can do on the controller prior to sending the array to the view? Any guidance would be appreciated
first()-Function. You always get only one result, didnt you? Please show more code!