beyondcode / laravel-query-detector

Laravel N+1 Query Detector
https://beyondco.de/docs/laravel-query-detector/usage
MIT License
1.99k stars 138 forks source link

Empty Object will be converted to empty array #86

Closed tsaiyihua closed 1 month ago

tsaiyihua commented 3 years ago

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.

mechelon commented 1 month ago

Feel free to create a PR with tests for that issue. (And please note that this package is not made for production purpose.)