Search code examples
phpjqueryjsonajaxlaravel

Laravel response ids change when response is json but when dumping the data the ids are there


i am trying to use ajax request in Laravel which searches records based on select2 input. Now i am transforming that data once i've fetched it, just to encrypt the ids. Here's how i get the records and transform their ids to encrypt.

    public function autocompletePedigree($subdomain, $type = null)
    {

        $q = request()->get('q');

        $sex = NULL;
        if (!is_null($type)) {
            $sex = $this->sexesRepository->make()->where('name', $type)->first(['id'])->id;
        }

        $results = $this->dogsRepository->search($q, $sex);

        $results->getCollection()->transform(function ($value) {
            $value->id = encrypt($value->id);
            return $value;
        });

        return $results;
    }

Now the results contain a dog name and id and when i use dd($results) the ids are transformed and correct here's an example

#attributes: array:2 [▼
  "id" => "eyJpdiI6IlN5YXdzT3hReEc2bnczRGM5YzV1eGc9PSIsInZhbHVlIjoiZ0NpaTRGWjNmS1ZEQjVZcGFZeWJRdz09IiwibWFjIjoiMThmNmQ5YmE5ZDI1MDg4OTZhMmExMTlmNzM0ZGU3ZDRhNzg0OGFhNzM2OTViYzVkN2QxZTUzMzMwMWY4ZDdhYiJ9"
  "text" => "Dog name"
]

But when i switch to JSON using return response()->json($results) it returns this

"data":[
  {
    "id":0,
    "text":"Dog name"
  },
  {
    "id":0,
    "text":"Doggy name"
  }

I cant understand why its turning ids into 0. Is this some kind of a JSON sanitization process? Can someone please help me to keep the encrypted ids in JSON response?


Solution

  • After a little bit of digging i found out that its been automatically casted into integer which caused a little bit of stir. So i fixed the issue by adding public $incrementing = false; to Dogs Model