user860511
user860511

Reputation:

Laravel - Undefined variable if query returns no results

If a query does not have any results, which is possible, the variable the query is assigned to returns the error 'undefined variable $alerts' on the line if(!$alerts).

foreach($locations as $location)
    {
        $alerts = Alert::where('location_id', '=', $location)
        ->lists('id');
    }

if(!$alerts){
        return Redirect::to('/users/')->with('message-warning', 
                                      'No matches have been found yet.');
    }

The $alerts variable is not anywhere else within the controller.

Even if the query returns no results, it should still be able to check it through if(!$alerts)?

Thank you for your help.

Upvotes: 0

Views: 1330

Answers (3)

Khan Shahrukh
Khan Shahrukh

Reputation: 6361

First of all don't execute query into a loop, even if you do that make sure you store the results in a array instead of a variable because then your result will always be the last row of the query. You should declare $alert variable/array before going into the foreach loop, so that if your query doesn't returns any result your variable/array will still be there, in your case if your query doesn't return any result you don't have $alert variable at all.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

You may try this:

$alerts = Alert::whereIn('location_id', $locations)->lists('id');

if(!$alerts) {

    return Redirect::to('/users/')->with('message-warning', 'Your message!');
}

It's better, only one query will be executed.

Upvotes: 1

Damien Pirsy
Damien Pirsy

Reputation: 25435

When $locations is empty, the foreach won't loop, and $alerts won't be initialized. I suggest initializing the variable before the loop:

$alerts = null;

foreach ($locations as $location) { }

if(!$alerts) { }

Upvotes: 0

Related Questions