Null object pattern with Eloquent relations

后端 未结 3 1393
囚心锁ツ
囚心锁ツ 2020-12-06 20:08

There is often the case where an certain eloquent model\'s relation is unset (i.e. in a books table, author_id is null) and thus calling something like $model->

3条回答
  •  余生分开走
    2020-12-06 20:51

    I had the same problem in my project. In my views there's some rows that are accesing to dinamics properties from null relationships, but instead of returning an empty field, the app was thrwoing and exception.

    I just added a foreach loop in my controller as a temporal solution that verifies in every value of the collection if the relationship is null. If this case is true, it assigns a new instance of the desire model to that value.

        foreach ($shifts as $shift)
        {
            if (is_null($shift->productivity)) {
                $shift->productivity = new Productivity();
            }
        }
    

    This way when I access to $this->productivity->something in my view when the relationship is unset, I get a empty value instead of an exception without putting any logic in my views nor overriding methods.

    Waiting for a better solution to do this automatically.

提交回复
热议问题