Laravel,从 JSON 中删除空的 Eloquent 对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25690999/
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
Laravel, remove null Eloquent object attributes from JSON
提问by daviestar
Is there an elegant way to remove NULL values from an Eloquent Object? My object is nested with relationships. This particular call can be 1000s of lines long, so my main reason for trying this is to save bandwidth for the user, but server performance is also a consideration.
有没有一种优雅的方法可以从 Eloquent 对象中删除 NULL 值?我的对象嵌套有关系。这个特殊的调用可能有 1000 条线长,所以我尝试这样做的主要原因是为用户节省带宽,但服务器性能也是一个考虑因素。
My code:
我的代码:
$data['locations'] = Location::with('address')->where('user_id', '1')->get();
return Response::json($data);
I experimented with Mutators, but unless I'm mistaken Mutators don't have power over the object key, just the value.
我用 Mutators 进行了试验,但除非我弄错了,Mutators 对对象键没有权力,只有值。
I also tried and failed to use array_filter like these:
我也尝试过但未能像这样使用 array_filter:
Any PHP function that will strip properties of an object that are null?
How to remove empty associative array entries
EDIT As requested,
编辑根据要求,
{
"status": "ok",
"locations": [
{
"id": "1",
"latitude": "12.239107980271",
"longitude": "109.19479025725",
"user_time": "",
"transport": "Bus",
"title1": "",
"title2": "",
"address": {
"town": "Nha Trang",
"country": "Vietnam",
"address": "36-44 Hùng V??ng, L?c Th?, Nha Trang, Khanh Hoa Province, Vietnam"
},
"altitude": {
"altitude": "10.006237983704"
},
"timezone": {
"offset": "25200"
},
"forecast": {
"icon": "",
"high_temp": "",
"low_temp": ""
}
},
{
"id": "2",
Desired response:
期望的回应:
{
"status": "ok",
"locations": [
{
"id": "1",
"latitude": "12.239107980271",
"longitude": "109.19479025725",
"transport": "Bus",
"address": {
"town": "Nha Trang",
"country": "Vietnam",
"address": "36-44 Hùng V??ng, L?c Th?, Nha Trang, Khanh Hoa Province, Vietnam"
},
"altitude": {
"altitude": "10.006237983704"
},
"timezone": {
"offset": "25200"
}
},
{
"id": "2",
As you can see, I could simply loop through the whole lot and remove any keys - or keys of keys - without values. I was hoping Laravel might provide a neat/fast way of doing the same.
如您所见,我可以简单地遍历整个批次并删除任何键 - 或键的键 - 没有值。我希望 Laravel 可以提供一种简洁/快速的方法来做同样的事情。
I should add that technically only the latitude and longitude are required fields!
我应该补充一点,从技术上讲,只有纬度和经度是必填字段!
回答by passioncoder
3 possibilities:
3 种可能性:
- Write a response macrowhich cleans up your json data: http://laravel.com/docs/responses#response-macros
- Extend the
Response
classand implement your cleanup routine there. See this great tutorial for details how to do this: http://fideloper.com/extend-request-response-laravel - Implement the jsonSerializemethodin your model which will be automatically called when your model is converted to json and place your cleanup routines there. You can even go a step further and write your own
Collection
for yourLocation
model. Depending on your data structure this can make things a little bit easier. A nice tutorial for this purpose can be found here: http://heera.it/extend-laravel-eloquent-collection-object
- 编写一个响应宏来清理你的 json 数据:http: //laravel.com/docs/responses#response-macros
- 扩展
Response
该类并在那里实现您的清理例程。有关如何执行此操作的详细信息,请参阅这个很棒的教程:http: //fideloper.com/extend-request-response-laravel - 在您的模型中实现jsonSerialize方法,当您的模型转换为 json 并将您的清理例程放在那里时,该方法将自动调用。您甚至可以更进一步,
Collection
为您的Location
模型编写自己的模型。根据您的数据结构,这可以使事情变得更容易一些。一个很好的教程可以在这里找到:http: //heera.it/extend-laravel-eloquent-collection-object
I personally would prefer option 3.) because the data modifications happens where it should happen - in your model.
我个人更喜欢选项 3。) 因为数据修改发生在它应该发生的地方 - 在你的模型中。
But bottom line it really depends which solutions fits best to your project.
但底线实际上取决于哪种解决方案最适合您的项目。
回答by Shibbir Ahmed
First make a trait and add your custom validation then use in your each resource where you need
首先创建一个特征并添加您的自定义验证,然后在您需要的每个资源中使用
trait ResourceHelpers
{
/**
* Remove null values from Eloquent api resource
* @param array $data
* @return array
*/
public function removeNullValues(array $data)
{
$filtered_data = [];
foreach ($data as $key => $value) {
$filtered_data[$key] = $this->when($value !== null, $value);
}
return $filtered_data;
}
}
Then use it in your resource
然后在您的资源中使用它
class UserResource extends JsonResource
{
use ResourceHelpers;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return $this->removeNullValues([
"id" => $this->id,
"first_name" => $this->first_name,
"last_name" => $this->last_name,
"phone" => $this->phone,
"email" => $this->email,
"balance" => $this->balance,
'address' => $this->address,
'city' => $this->city,
'state' => $this->state,
'zip_code' => $this->zip_code,
'country' => CountryResource::make($this->whenLoaded('country')),
"joined_at" => $this->created_at,
"updated_at" => $this->updated_at,
]);
}
}