skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. For everyone else who’s curious (like me) on why that is happening:

    He is changing the type of his model’s primary key. When he (or in this case the JsonResponse) calls toJson() on the model, it tries to cast that primary key (which was manually changed to string) back to it’s original value (int) and since (int) "eyJpdiI6IlN ..." equals 0 his key is 0 too.

    That happens because the primary key is actually added to the $casts property of the model:

    public function getCasts()
    {
        if ($this->getIncrementing()) {
            return array_merge([$this->getKeyName() => $this->getKeyType()], $this->casts);
        }
    
        return $this->casts;
    }
    

    … and the properties are casted when the model gets serialised to an array (and later on to JSON).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search