convert null values into empty string in laravel 5.4

折月煮酒 提交于 2020-12-04 03:15:34

问题


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

回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/44038644/convert-null-values-into-empty-string-in-laravel-5-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!