laravel-query-detector icon indicating copy to clipboard operation
laravel-query-detector copied to clipboard

Empty Object will be converted to empty array

Open tsaiyihua opened this issue 3 years ago • 0 comments

Hello,

I discover that while my object is empty, and with the N+1 report for JsonResponse, my empty object will be converted to empty array. In my production with debug is false will not be converted, this will be ok. but in my development with debug is true, empty object will be converted to empty array, it's a problem.

example:

    public function index()
    {
        $chapters = Chapter::where('book_id',1)->get();
        $data = [];
        $chapters->each(function (Chapter $chapter) use (&$data) {
            $data['book_name'] = (string) $chapter->book->name;
            $data['empty_object'] = (object) [];
        });
        return response()->json($data);
    }

my expectation output is

{"book_name":"Sunt sit.","empty_object":{},"warning_queries":[...]}

but output is

{"book_name":"Sunt sit.","empty_object":[],"warning_queries":[...]}

In Json.php with namespace BeyondCode\QueryDetector\Outputs

    public function output(Collection $detectedQueries, Response $response)
    {
        if ($response instanceof JsonResponse) {
            $data = $response->getData(true);
            if (! is_array($data)){
                $data = [ $data ];
            }

            $data['warning_queries'] = $detectedQueries;
            $response->setData($data);
        }
    }

change to

    public function output(Collection $detectedQueries, Response $response)
    {
        if ($response instanceof JsonResponse) {
            $data = $response->getData();
            if (! is_array($data)){
                $data = [$data];
            }

            $data['warning_queries'] = $detectedQueries;
            $response->setData($data);
        }
    }

will get my expectation output.

tsaiyihua avatar Nov 09 '21 03:11 tsaiyihua