duancan1900 2018-04-20 08:59
浏览 110
已采纳

Laravel optional()如何工作?

When creating new models, I am trying to use the optional() helper to assign values when they are set. However, when the user object isn't set in this context, I receive this error: "Undefined property: stdClass::$user"

$this->events()->create([
    'category_a' => optional($event)->categoryA,
    'category_b' => optional($event)->categoryB,
    'user' => optional($event->user)->accountId,
]);

To clarify, the $event is always set, however it can contain different values. Sometimes category_a is set, sometimes category_b is set. The optional helper seems to do the trick here. But, when the object is deeper than one level, it throws an error.

So how do I work with the optional helper correctly using deeper than one level objects?

  • 写回答

1条回答 默认 最新

  • drasv0904 2018-04-20 09:38
    关注

    The optional() helper normally is used to avoid errors generated by accesing propeties or methods on null objects, for example:

    Fatal error: Call to a member function foo() on null

    As the documentation specifies:

    The optional function accepts any argument and allows you to access properties or call methods on that object.If the given object is null, properties and methods will return null instead of causing an error.

    A practical example

    In your code you are accesing a relation called address from your user model:

    return $user->address->street;
    

    If by any chance your $user->address is null and you try to check the street, this will return a fatal error, here is where optional() comes into play, by using the helper you can explicitly say $user->address might be null, so don't show me an error if that's the case:

    return optional($user->address)->street;
    

    By doing this you will get null instead of the fatal error.

    In my opinion this makes the code more readable, a equivalent could be $user->address ? $user->address->street : null, but as you can see is by far more verbose.

    In your case, as the comments said an option is to nest optional() helpers, but this is not maintanable if you have multiple levels. I'd recommend you to make a function that internally will chain the helpers so your syntax would look like n_optional($event, ['user'])->accountId.

    Hope this helps you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法