Request::intersect (...) 一个可以让你初步远离意大利面条的函数
不想抛弃意大利面条式编程的程序员肯定没有好的苍老师
假设让你更新一条数据的部分数据的时候
PATCH /records/{id}
{
"title": "新的标题",
"label": "新的标签"
}
Before
以前你可能是这样的这样
$record = Record::findOrFail($id);
if ($request->has('title')) {
$record->title = $request->title;
}
if ($request->has('label')) {
$record->label = $request->label;
}
if ($request->has('year')) {
$record->year = $request->year;
}
if ($request->has('type')) {
$record->type = $request->type;
}
$record->save();
After
现在你可以尝试一下这样。
这里用到了 request
中的 intersect
方法
$record = Record::findOrFail($id);
$record->update($request->intersect([
'title',
'label',
'year',
'type'
]));
所以借用 Adam 的一张图,最后效果就是这样
原理
实际上,上面的例子用到了 request
中的 intersect
方法,而这个方法已经对数据进行了一次 array_filter
筛选。
/**
* Intersect an array of items with the input data.
*
* @param array|mixed $keys
* @return array
*/
public function intersect($keys)
{
return array_filter($this->only(is_array($keys) ? $keys : func_get_args()));
}
Tips: 在 Laravel 5.4,Taylor 重新梳理了代码结构,把一些方法放到了
Illuminate/Http/Concerns
中。例如这里的intersect
方法是在Illuminate/Http/Concerns/InteractsWithInput.php
。所以 Laravel 真的是越读越有意思。
推荐文章: