开发常用的辅助函数
1.optional()
允许你来获取对象的属性或者调用方法。如果该对象为 null,那么属性或者方法也会返回 null 而不是引起一个错误
// User 1 exists, with account
$user1 = User::find(1);
$accountId = $user1->account->id; // 123
// User 2 exists, without account
$user2 = User::find(2);
$accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
// Fix without optional()
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null
// Fix with optional()
$accountId = optional($user2->account)->id; // null
2.replicate()
使用 replicate () 克隆一个模型。它将复制一个模型的副本到一个新的、不存在的实例中。
$user = App\User::find(1);
$newUser = $user->replicate();
$newUser->save();
3.blank()
判断给定的值是否为空,与之相反的函数为lled()`
blank('');
blank(' ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
blank(['']);
empty(collect());//这里与blank(collect())结果相反
// false
4.filled()
判断给定的值是否不为「空」
filled(0);
filled(true);
filled(false);
// true
filled('');
filled(' ');
filled(null);
filled(collect());
// false
5.pluck
从数组中检索给定键的所有值
$parents = [
['parent' => ['id' => 1, 'name' => 'James']],
['parent' => ['id' => 8, 'name' => 'Lisa']],
];
Arr::pluck($parents, 'parent.name'); // ['James', 'Lisa']
本作品采用《CC 协议》,转载必须注明作者和本文链接
实用
blank filled 也很好