在laravel 5.4中将空值转换为空字符串

在laravel 5.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;
}

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;
}

    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);
    }
}

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.