4

I want to convert all null with empty string I have used array_walk_recursive but I haven't got what I want please help me to figure it out what I have done wrong here.

protected function setData($key, $value)
{
    $this->data[$key] = $value;
    array_walk_recursive($this->data, function (&$item, $key) {
        $item = null === $item ? '' : $item;
    });
    return $this->data;
}
3
  • Try $item = !is_null($item) ? $item : ''; Commented May 18, 2017 at 4:42
  • not working that too.. Commented May 18, 2017 at 4:43
  • if($item === NULL){ $item = ''; } Commented May 18, 2017 at 5:01

3 Answers 3

2

well, that's just a lamp mistake in eloquent we always get result in eloquent object and here I'm passing eloquent object inside array_walk_recursive so before passing I need to convert into array from eloquent object using ->toArray() method in laravel like this.

inside User Controller

$this->setData("friendList", $loadFriends->friends->toArray());

then array_walk_recursive will work.

protected function setData($key, $value)
{
    array_walk_recursive($value, function (&$item, $key) {
        $item = null === $item ? '' : $item;
    });
    $this->data[$key] = $value;
    return $this->data;
}
Sign up to request clarification or add additional context in comments.

1 Comment

my pleasure. :)
1

Your array_walk_recursive() method should be modified as follows.

array_walk_recursive($input, function($i) use (&$output) {
    $output[] = is_null($i)? '': $i;
});
var_dump($output);

$output contains the result you wanted. You can return it or do whatever you want to do with it.

Note: you can instead use array_walk() if $input not an associative array.

Comments

0
    class InputCleanup
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->input();

        array_walk_recursive($input, function(&$value) {

            if (is_string($value)) {
                $value = StringHelper::trimNull($value);
            }
        });

        $request->replace($input);

        return $next($request);
    }
}

Comments

Your Answer

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