0
votes

My Child Class

class Child extends Eloquent { ... public function campaign() { return $this->hasOne('Campaign'); } ... }

Here is my query in Laravel:

    $query = Child::query();
    $query->select('children.*');
    $query->join('demands', 'demands.children_id', '=', 'children.id')->where('demands.accepted', '=', '1');
    $children = $query->orderBy(DB::raw('RAND()'))->take(4)->get();

In in foreach ($children as $child), I try to call echo $child->campaign->name and I got "Trying to get property of non-object" message. $child->name works fine!

1
Is it possible that you have children in your db, that do not have a campaign?lukasgeiter
Please accept my answer so everybody browsing the question list can see that this issue is resolved. thanks.lukasgeiter
Have you check $children variable is a Array or Object ? If it is Array than use $array->$key; If it is Object than usr $object->$key;Ketav
Try echo @$child->campaign->nameakbansa

1 Answers

1
votes

So as it turned out, not every children had a campaign associated with it. Just add a little check in your foreach loop and you should be fine

foreach($children as $child){
    if($child->campaign == null){
        continue;
    }
    // do stuff
}