Laravel 5 controller sending JSON integer as string

后端 未结 3 1526
渐次进展
渐次进展 2020-12-02 23:09

On my development server the JSON response from the Laravel 5 controller shows the data in the correct types.

e.g

imdb_rating: 7.6
imdb_votes: 6271
<         


        
3条回答
  •  余生分开走
    2020-12-02 23:15

    I just ran into this same issue! For those of you looking for a more appropriate solution, you might want to check out the $casts property for Eloquent models.

    The accepted solution will work, but it will also convert fields that you may not want converted. I would recommend adding this to your Eloquent model:

    protected $casts = [ 'imdb_rating' => 'float', 'imdb_votes' => 'integer' ];
    

    This will convert the values directly in your model object, so you won't need to worry about updating multiple endpoints. I hope this helps others as it did me!

提交回复
热议问题