Tuesday, March 27, 2018

Laravel Trying to get property of non-object

Trying to get property of non-object

Laravel Trying to get property of non-object is a data error or no data in our database, in this case the error is usually on the relation. see example below:

Error Example:
public function example($id){
   $data = TABLE::find($id);
   $data2 = TABLE2::find($data->id_relation)->name;
   return $data2;
}

see variable $data2 on TABLE2 there is no data id with field name equal to $data->id_relation so return will be Trying to get property of non-object. see example below:

Correct Example:
public function example($id){
   $data = TABLE::find($id);
   if(!empty($data)):
     $data2 = TABLE2::find($data->id_relation)->name;
   else:
     $data = 'empty data';
   endif;
   return $data2;
}

Simple solution just add if else for make sure your data is there or not.
Keep Working, Have a nice day...
Disqus Comments