Search code examples
phplaravelormlaravel-4eloquent

Laravels Eloquent ORM: setting datatypes of the model


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

Solution

  • 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.