When I'm trying to eager load my Model with relation like that:
$plants = Plant::with('history')
->get()
->where('user_id', auth()->id());
I want to modify those extracted dates with my function like that:
foreach ($plants as $plant) {
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
$plant->fertilized_at = self::getDateForHumans($plant->history->fertilized_at);
}
I get this kind of error:
ErrorException Trying to get property 'watered_at' of non-object
but if I try to debug it by dd() function i get a positive result
dd(self::getDateForHumans($plant->history->watered_at));
Does anybody know how to fix it or what is the workaround?
CodePudding user response:
seems your history has no watered_at
member, so it comes to this error.
Check first if you can access this member with
if(isset($plant->history->watered_at)){
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
}