Vahn Marty Cagalawan
Vahn Marty Cagalawan

Reputation: 589

Laravel - selectRaw( count(*) ) is returning as string and not integer?

I don't know how this happened. Because in my localhost, it is properly working, but after in my shared-hosting, then I noticed it. The reason I'm going to convert to int is because of the highcharts. https://www.highcharts.com/errors/14

code:

public function assistance()
    {
        $programs = DB::table('assistances')->selectRaw('services.name, count(*) as y')
        ->join('services', 'assistances.service_id', '=', 'services.id')
        ->groupBy('service_id')->get();

        return $programs;
    }

The JSON output is this:

[
   {
      name: "BMAP", 
      y: "1"
   }
]

it should be y: 1 without the quote.

What is missing? Is this a server issue?

Upvotes: 2

Views: 6841

Answers (2)

ghn
ghn

Reputation: 119

I'm using MySql and had success converting the result in the query. It's a little less smelly than the json_decode and json_encode solution.

    ->selectRaw('services.name, CAST(count(*) AS UNSIGNED) as y')

Upvotes: 3

Vahn Marty Cagalawan
Vahn Marty Cagalawan

Reputation: 589

I found an answer using JSON_NUMERIC_CHECK reference from the comment of @Deep3015.

Solution : json_encode() and json_decode();

public function assistance()
    {
        $programs = DB::table('assistances')
        ->join('services', 'assistances.service_id', '=', 'services.id')
        ->selectRaw('services.name, count(*) as y')
        ->groupBy('assistances.service_id')->get();

        return Response::json(json_decode(json_encode($programs, JSON_NUMERIC_CHECK)));
    }

Upvotes: 2

Related Questions