lundi 2 août 2021

Laravel converts integer to NULL when returning Model as JSON

This is the weirdest mistake I've ever seen in my life, I don't know how to explain it, but it's happening.

When returning a list of models from the controller:

public function index()
{
     return MyModel::orderBy('name')->get();
}

I'm getting the following feedback in the browser: return with error

Now if I switch to:

public function index()
{
     return MyModel::orderBy('name')->get()->toArray();
}

I get the following feedback in the browser:

expected return

After trying to find a solution so that I don't need to call the toArray() function, I found that by overriding the jsonSerialize() method as in the example below, in the MyModel class, it correctly converts the cost_id to a number.

public function jsonSerialize()
{
    return parent::jsonSerialize();
}

If I put the field as string in the $casts, it works, but converts the numbers to string.

My Model:

enter image description here

My backend:

  • PHP 5.6.40
  • Laravel 5.4
  • Database is DBMaker


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire