0

i just want how can we convert null into empty string while getting result from db. For example

User::first();

In user table, roll number is null value. i want it to convert into empty string.

3
  • do you need all response NULL to "" for android or iphone developer ? Commented Mar 8, 2021 at 11:38
  • Yes for iphone developer Commented Mar 8, 2021 at 12:43
  • then use middleware and apply to all route so you will not miss any where Commented Mar 8, 2021 at 14:25

2 Answers 2

3

i had same task i solved this by Middleware

created NullToBlank.php Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class NullToBlank
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $output = $next($request);
        if ($output) {

            $json = $output->content();
            $modelAsArray = json_decode($json, true);

            if (is_array($modelAsArray)) {
                array_walk_recursive($modelAsArray, function (&$item, $key) {
                    $item = $item === null ? '' : $item;
                });
                return response($modelAsArray);
            } else {
                return $next($request);
            }
        }
    }
}

then apply this middleware whenever you need to replace NULL to ""

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, you can do this in boot method with retrieved observer like this.

 self::retrieved(function ($model) {
        $keys = $model->fillable;
        foreach ($keys as $key => $value) {
            $model->attributes[$value] = @$model->attributes[$value] == null ?  '' : $model->attributes[$value];
        }
    });

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.