推荐Laravel中又一个好用的helper

Laravel 中的又一个辅助函数 optional() 可以允许你访问给定对象的属性或者方法。如果给定的对象是 null,属性或方法将会返回 null 代替返回 error

下面举例来看下。

// app/Models/User.php
class User extends Model
{
    //...
    
    public function account()
    {
        //...
    }

    //...
}

// user1 存在,account 对象也存在
$user1 = User::find(1);
$accountId = $user1->account->id; // 123

// user2 存在,但是 account 对象不存在
$user2 = User::find(2);
$accountId = $user2->account->id; //这时会报: PHP Error: Trying to get property of non-object

// 如果不用 optional(), 你可能会这么判断
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null

// 用 optional(),简单搞定,是不看起来很优雅呢
$accountId = optional($user2->account)->id; // null

当使用不可用的对象或调用不可用的Eloquent关系中的嵌套数据时,optional() 助手是理想选择。

不妨你也试试吧 ^_^

更多PHP知识,可前往 PHPCasts
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值