Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Trying to get property of non-object, but the object is fine
  • I'm using a rather old version of FuelPHP (1.1), but still, this issue is pretty weird.

    Here's what I'm doing:
    controller:
    $all_cities = Model_City::find('all', array('order_by' => 'name', 'related' => array('country')));

    view:
    foreach ($all_cities as $city) {
    $country = $city->country->name;
    }

    error (on the line where I assign $country):

    ErrorException [ Notice ]: Trying to get property of non-object


    But var_dumping $city->country->name correctly returns 'USA'.
    Plus, $country is then available and working after that assignment.
    I'm not sure what's happening here...

    Thank you.
  • your returning an array but in your loop you are trying to access it as an object

  • That depends.

    find() returns an array of Model_City objects, so so far so good. The question is whether all city objects have a country?

    Try:

    $country = $city->country ? $city->country->name : 'Unknown';

    and see what happens?
  • Oops, you are correct, there was a city without an associated country :)

    Thank you!

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion