在 laravel 中使用 makeHidden 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43436666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
the correct way to use makeHidden in laravel
提问by programmer
I have problem with the pagination .
我的分页有问题。
everything work fine without error but the problem is when i use makeHidden with my code it change the structure of my json pagination result
一切正常,没有错误,但问题是当我将 makeHidden 与我的代码一起使用时,它会更改我的 json 分页结果的结构
this is my code
这是我的代码
$result = Job::where('user_id','=',Auth::id())->paginate(5);
$result= $result->makeHidden(['hasMessage']);
without the second line the result is
没有第二行,结果是
{
total: 1 ,
per_page: 5,
current_page: 1,
last_page: 1,
next_page_url: null,
prev_page_url: null,
from: 1,
to: 1,
data: [
{
id: 4,
sid:125,
hasMessage: true
}
]
}
but when i use
但是当我使用
$result= $result->makeHidden(['hasMessage']);
I got
我有
[
{
id: 4,
sid:125,
}
]
any idea please ? ? ? is it a bug or there is something wrong ? ?
有什么想法吗?? ? 这是一个错误还是有什么问题??
hasMessageis an append field not a real columns
hasMessage是一个附加字段,而不是真正的列
回答by programmer
finally I did it with small programming trick
最后我用小的编程技巧做到了
$paginator = Job::where('user_id','=',Auth::id())->paginate(5);
$data = $paginator->makeHidden(['hasMessage']);
$paginator->data = $data;
return $paginator;
thank you
谢谢你
回答by m.nikzad
if you want to preserve pagination data use getCollection()
and setCollection()
methods:
如果要保留分页数据使用getCollection()
和setCollection()
方法:
$paginator = Job::where('user_id','=',Auth::id())->paginate(5);
$paginator->setCollection($paginator->getCollection()->makeHidden(['hasMessage']));
return $paginator;
回答by PaladiN
You are missing toArray()
in your code. It should be like:
您toArray()
的代码中缺少。它应该是这样的:
$result= $result->makeHidden(['hasMessage'])->toArray();
Have a look at the docs:
看看文档:
https://laravel.com/docs/5.4/eloquent-serialization#hiding-attributes-from-json
https://laravel.com/docs/5.4/eloquent-serialization#hiding-attributes-from-json
Edit:
编辑:
I also have tried to paginate
and it did return the changed array and it is the expected output for the makeHidden()
.
我也尝试过paginate
,它确实返回了更改后的数组,它是makeHidden()
.
You could also have a look at the function:
你也可以看看这个函数:
public function makeHidden($attributes)
{
$attributes = (array) $attributes;
$this->visible = array_diff($this->visible, $attributes);
$this->hidden = array_unique(array_merge($this->hidden, $attributes));
return $this;
}
As it is doing array_merge
it distotes your json response.
因为它正在做array_merge
它distotes你的json响应。