phplaravellaravel-5

Prevent DB query if relation was not loaded


I have 2 models, for example, Country and City with relations one-to-many.

When I run this code

$countries = Country::query()->with('cities')->get();

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($city->country);
    }
}

, on the each $city->country call I have a query to DB

select * from `countries` where `countries`.`id` = ? limit 1 

If relation (in my case cities.country) was not loaded with eager loading, is there a possibility to prevent making DB query on the each $city->county call?

I no need the $country variable. I need to get null if relation cities.country was not loaded in the main query.


Solution

  • Thanks to

    https://laracasts.com/discuss/channels/laravel/how-to-check-if-an-relationship-has-been-eager-loaded-or-not

    In my case

    //...
    if ($city->relationLoaded('country')) {
        dump($city->country);
    } else {
        dump(null);
    }
    //...