0

I'm using Postman to test my APIs and I get the following response:

{
 "Message": "Drinks loaded successfully.",
 "Status": true,
 "InnerData": [
     {
         "id": 1,
         "place_id": "25",
         "drink_type": "1",
         "drink_amount": "2",
         "device_id": "1",
         "created_at": "2018-03-09 14:22:27",
         "updated_at": "2018-03-09 14:22:27"
     }
 ]
}

In my datbase the drink_type, place_id, drink_amount, device_id are all integers but I receive them as strings, what is wrong with them?

Here is my code used to return this data:

public function loadDrinks(Request $request){
    $place_id = $request->place_id;
    $device_id = $request->device_id;

    $drinks = \App\DrinksOrdered::where(['place_id' => $place_id, 'device_id' => $device_id])->get();
    $resp = new \App\Http\Helpers\ServiceResponse;
    $resp->Message = "Drinks loaded successfully.";
    $resp->Status = true;
    $resp->InnerData = $drinks;
    return response()->json($resp, 200);
}
5
  • i edited it, thank you Commented Mar 9, 2018 at 14:56
  • Did you set them as an integer on your model? Commented Mar 9, 2018 at 14:58
  • Can you show me the \App\DrinksOrdered file, please? Commented Mar 9, 2018 at 14:59
  • <?php namespace App; use Illuminate\Database\Eloquent\Model; class DrinksOrdered extends Model { protected $fillable = ['place_id','device_id','drink_type','drink_amount']; } Commented Mar 9, 2018 at 15:00
  • Check out this laravel.com/docs/5.6/eloquent-mutators#attribute-casting Commented Mar 9, 2018 at 15:00

2 Answers 2

2

https://laravel.com/docs/5.6/eloquent-mutators#attribute-casting

Add this to your model to specify the data type:

 protected $casts = [
     'drink_type' => 'int',
     'place_id' => 'int'
 ];
Sign up to request clarification or add additional context in comments.

Comments

1

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.

This is from the offical documentation, try something like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DrinksOrdered extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'drink_type' => 'int',
        'place_id' => 'int',
    ];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.