Jorge Anzola Jorge Anzola - 4 months ago 7
PHP Question

Laravel check if related model (A better solution?)

I'm working on a app that shows flights. In the fligh selection workflow the user should first pick a destination. In my "pick a destination view" I display all the Countries in my database. Some of them haven't flights. I'm attempting to show just the countries with flights, to accomplish that, I've written this method:

public function getDestinationsWithFlights()
{
$destinations = Destination::all();
$destinationsWithFlights = [];

for ($i = 0; $i < count($destinations) ; $i++)
{
if ($destinations[$i]->hasMany(Flight::class)->count() != 0)
{
$destinationsWithFlights[$i] = $destinations[$i];
}
}

return $destinationsWithFlights;
}


the response is

{
"0": {
"id": 1,
"country": "argentina",
"created_at": "2016-08-03 13:56:36",
"updated_at": "2016-08-03 13:56:36"
},
"2": {
"id": 3,
"country": "spain",
"created_at": "2016-08-03 13:56:36",
"updated_at": "2016-08-03 13:56:36"
}
}


I don't know where these keys, "0" and "2", came from. And I think there most be a better solution to that. And, also, I'd prefer the response to be something like this:

{
"id": 1,
"country": "argentina",
"created_at": "2016-08-03 13:56:36",
"updated_at": "2016-08-03 13:56:36"
},
{
"id": 3,
"country": "spain",
"created_at": "2016-08-03 13:56:36",
"updated_at": "2016-08-03 13:56:36"
}


You guys have any idea? Or you think it's fine the way I did it?

Answer

Add flights relationship to your Destination model:

public function flights()
{
    return $this->hasMany(Flight::class);
}

Then query only destinations with flights like:

$destinations = Destination::has('flights')->get();

Your getDestinationsWithFlights function should look something like:

public function getDestinationsWithFlights()
{
    return Destination::has('flights')->get()->toArray();
}