Laravel 5 Controller Sending JSON Integer as String

Laravel 5 controller sending JSON integer as string

Make sure to use MySQL Native Driver which will support native data types.

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

MySQL Client Library will return all fields as strings.

Another solution would be to use json_encode options with JSON_NUMERIC_CHECK.

For example:

return response()->json(["foo" => "bar"], 200, [], JSON_NUMERIC_CHECK);

Issue with Laravel casting Int to string when fetching from server?

You can use casting Attribute Casting in your model

protected $casts = [ 
'field_name1' => 'integer',
];

Response::json() - Laravel 5.1

use the helper function in laravel 5.1 instead:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){

return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

How to define the data type before returning JSON data for api backend in laravel

You can cast the property to integer with the Eloquent mutators like this:

class Club extends Model
{
protected $casts = [
'user_id' => 'integer',
];
}

Numbers are formatted as string after scout:import Laravel

Numbers are rendered as the string in JSON response by default.
You could either use instructions from this https://stackoverflow.com/questions/31527050/laravel-5-controller-sending-json-integer-as-string or you could use casts attributes in the model so every time model is serialized it will cast respective columns as specified.

E.g. In model, you can define something like this:

protected $casts = [
'something' => 'float'
];

Best way to store and load JSON from database in Laravel

Database

In your database migrations add:

$table->json('data'); // Recommended. Supported in MySQL since version 5.7.8

or

$table->text('data');

The JSON column type is recommended as it allows you to do SQL queries on JSON data. See MySQL JSON Data Type

Model: Casting the Attribute

The next issue is that you need to be able to cast your data into a PHP array.

This is done by modifying the casts attribute in the model:

class Paste extends Model {
protected $casts = [
'data' => 'array'
];
}

See Array and JSON Casting for more information.

Now you can save data onto the attribute as a PHP array, and also assign it a PHP array.

 $paste = Paste::first();
dump($paste); // Returns a PHP array

$paste->data = ['some-data' => 20, 'score' => 500];
$paste->save();

Internally, when it saves the data, it automatically would convert it into a JSON string and save it in the database in the correct format.

Store Method

When taking in input as JSON, it highly depends in how you want to pass the data,

1. Sending form data with JSON content type (recommended)

My recommendation is to send the entire data as JSON in the POST body like so:

Content-Type: application/json
Body:
{
"data": {
"name": "John",
"age": 31,
"city": "New York"
},
"someOtherField": "Hello!"
}

Your store() method should now be (I've also added validation code):

public function store()
{
$this->validate($request, [
'data' => ['required', 'array'],
'data.*.name' => ['required', 'string'],
'data.*.age' => ['required', 'int'],
'data.*.city' => ['required', 'string'],
]);

$paste = new Paste();
$paste->uuid = Str::uuid()->toString();
$paste->data = $request->post('data'); // No need to decode as it's already an array
$paste->save();

return Redirect::to("/paste/{$paste->uuid}")
->with('success', 'Created');
}

2. Sending form data with form params

If however you insist in sending data through query params or form params, note these can only send strings. Therefore you need to send an encoded version of the JSON string to persists data types, as follows:

Form Params:
- data: '{"name": "John", "age": 31, "city": "New York"}'
- someOtherField: "Hello!"

The store method will now look like this:

    $this->validate($request, [
'data' => ['required', 'json'], // I'm unsure if data is required
]);

$data = json_decode($request->post('data'), true, JSON_THROW_ON_ERROR); // Needs to be decoded

// validate $data is correct
Validator::make($data, [
'name' => ['required', 'string'],
'age' => ['required', 'int'],
'city' => ['required', 'string'],
])->validate();


$paste = new Paste();
$paste->uuid = Str::uuid()->toString();
$paste->data = $data;
$paste->save();

return Redirect::to("/paste/{$paste->uuid}")
->with('success', 'Created');

Show Method

Your show method needs no changes:

public function show($uuid)
{
$paste = Paste::where('uuid', $uuid)->first();
return response()->json($paste->data);
}


Related Topics



Leave a reply



Submit