Confused between array and objects in Laravel

前端 未结 2 443
名媛妹妹
名媛妹妹 2020-12-28 20:28

I\'m learning Laravel and it uses OOPS concepts. Now I\'m finding it hard to understand the real difference between array and objects. I actually know what an array and obje

2条回答
  •  旧时难觅i
    2020-12-28 21:10

    I think I know the source of your problem, as I've been having to work around it. If you are using the arrow notation on a model object and there is no record in the relationship, then you'll get the "non-object" error. For example, if you have the line

    $student->school->school_name
    

    and a given $student doesn't have a school object, you'll get the non-object error. I typically add checks for empty($student->school) or empty($student->school_id) or the like to avoid this when I run into it (or heaven forbid forsee the problem when doing my initial coding pass).

    EDIT: So, to clarify, Laravel doesn't say "oh, there's a relationship there, so school is an object which happens to be empty, so I'll return null for school_name", it says "there's no school, so ->school_name is an invalid call to an object property"

提交回复
热议问题