Currently I have a simple table with two rows: id
and key
.
Whenever I try to get my data from the database with City::get()
the response contains id
columns in the string format.
Is there a simple way/package how I can define the data formats for each of my columns? E.g. - id
in this example should have been an integer.
Model:
<?php
class City extends Eloquent {
protected $table = 'cities';
protected $primaryKey = 'Id';
}
Controller:
class CityController extends \BaseController {
public function index()
{
var_export(is_integer(City::get()->first()->Id));
var_export(is_string(City::get()->first()->Id));
die;
}
}
Output:
false
true
Every field from a record that comes out of the database is going to be a string.
This is just how many db extensions in PHP seem to work.
Ruby on Rails keeps a constant map of the schema to know that tableA.field1 is an integer, so it can convert anything to an int when it fetches the database. This obviously has some overhead to it, but it can be a useful feature. Laravel opted to not do this in the interest of performance over convenience.
You can use accessors and mutators to manually replicate this functionality.
Are you sure that the data type in the database is an integer (INT) as well? Else you could, maybe, convert the string to an integer. For example:
Eloquent Models have a property
casts
that can be used to hint at the type for each model attribute.This was my case using eloquent for a legacy application locked to PHP 5.4. For some random reason i didn't try to figure out, every attribute was retrieved as a string from the database and the default PHP casting was causing me problems.
Your code would be: