Laravel, remove null attributes of an Eloquent object from JSON

Is there an elegant way to remove NULL values ​​from a pronounced object? My object is nested in a relationship. This particular call may be 1000 lines long, so my main reason for this is to conserve bandwidth for the user, but server performance is also considered.

My code is:

$data['locations'] = Location::with('address')->where('user_id', '1')->get();

return Response::json($data);

I experimented with Mutators, but if I am not mistaken, Mutators do not have authority over the object key, just the value.

I also tried and could not use array_filter as follows:

Any PHP function that strips object properties 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 answer:

{
    "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",

, - - . , Laravel / .

, !

+4

All Articles