mercredi 19 juillet 2017

Laravel - Undefined variable when no data exists in database

I am having a struggle with an error I am getting: Undefined variable: orbitdata. I have looked at some answers and I know this happens when there is no data in the database that matches the filter that I have in the controller. If there is data there is no problem.

The controller I am using is this:

$satellite = DB::table('satellites')->where('norad_cat_id', $norad_cat_id)->get(); 
$data = DB::table('satellites')->where('norad_cat_id', $norad_cat_id)->get();
$orbitalelements = DB::table('tle')->where('norad_cat_id', $norad_cat_id)->get();
return view('pages/satellite', compact($data, 'data', $orbitalelements, 'orbitalelements'));

The logic behind the controller is to filter the database by norad_cat_id and return the row which has the same norad_cat_id.

The 'tle' table might not have any data for the filtered norad_cat_id, so $orbitalelements returns no data. When it does not I get this error.

My blade file contains this foreach statement for the $orbitalelements variable:

@foreach($orbitalelements as $orbitdata)
@endforeach

I have tried adding an isset statement (which did not work):

@if(isset($orbitalelements))
    @foreach($orbitalelements as $orbitdata)
    @endforeach
@endif 

How do you make it so that I don't get an Undefined variable error when there is no data from the database to return?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2uzNMFI
via IFTTT

Aucun commentaire:

Enregistrer un commentaire