1

In my laravel request I am sending data as given below..

{
    "user_id":13,
    "location":null,
    "about":"This Is About the user",
    "avatar":[],
    "users":[
        {
            "user_name":"John",
            "age":"30",
        },
        {
            "user_name":"Jessy",
            "age":"30",
        }
    ]
}

All the request keys can be null or hold a value (an array or string) so I want to filter only keys which has value.

Expected Output:

{
    "user_id":13,
    "about":"This Is About the user",
    "users":[
        {
            "user_name":"John",
            "age":"30",
        },
        {
            "user_name":"Jessy",
            "age":"30",
        }
    ]
}

I have tried

$userRequestData = $request->only([
    'location','about','avatar','users'
]);

$Data = array_filter($userRequestData, 'strlen');

But it only works if the request has only string values...

How can I filter it even if it's a string or an array?

1
  • do you also want to filter the nested key-values like user_name key inside users? Commented Jul 14, 2021 at 12:53

2 Answers 2

2

If you don't pass the 'strlen' parameter to array_filter, it will filter out falsyvalues:

$request = [
    "user_id"=>13,
    "location"=>null,
    "about"=>"This Is About the user",
    "avatar"=>[],
    "users"=>[
        [
            "user_name"=>"John",
            "age"=>"30",
        ],
         [
            "user_name"=>"Jessy",
            "age"=>"30",
        ]
    ]
];

will become

$request = [
    "user_id"=>13,
    "about"=>"This Is About the user",
    "users"=>[
        [
            "user_name"=>"John",
            "age"=>"30",
        ],
         [
            "user_name"=>"Jessy",
            "age"=>"30",
        ]
    ]
];

Documentation for array_filter

In your example you could do this:

$userRequestData = array_filter($userRequestData);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use collection to filter null values

collect(request()->all())->filter()

or

$result = collect(request()->all())->filter(function ($request){
    return is_string($request)&&!empty($request)||is_array($request)&&count($request);

});

To get array

$result = collect(request()->all())->filter()->toArray()

or for custom

$result = collect(request()->all())->filter(function ($request){
    return is_string($request)&&!empty($request)||is_array($request)&&count($request);
        
})->toArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.