Rohan
Rohan

Reputation: 13811

How to get back lower case column names in Eloquent?

I am working with a database which has all uppercase snakecase column names and when I fetch them with eloquent I do something like:

    foreach($data as $key => $item){
        $data[$key] = array_change_key_case($item);
    }

This makes the keys ie the column names to lower case, but it soon becomes inefficient since I need to nested arrays too like so:

    foreach($tasks as $key => $task){
        foreach($task['users'] as $innerKey => $user){
            $task['users'][$innerKey] = array_change_key_case($user);
        }
        $tasks[$key] = array_change_key_case($task);
    }

And I can't change the database. Is there a way I can make eloquent give me back the column names in lower case?

Upvotes: 2

Views: 5331

Answers (2)

bishop
bishop

Reputation: 39444

You can transform column names at the driver level using PDO attributes. To do so, set your Laravel connection options (in app/config/database.php) like so:

return array(
    'connections' => array(
        'mysql' => array(
            'options'   => array(
                PDO::ATTR_CASE => PDO::CASE_LOWER,
            ),
        ),
     )
)

The default is PDO::CASE_NATURAL, which is why your code sees them as the database has them stored.


Update: If you are using MySQL, you might consider setting lower_case_table_names = 2, which tells the server:

If set to 2, table names are stored as given but compared in lowercase. This option also applies to database names and table aliases.

Upvotes: 8

Eric Tucker
Eric Tucker

Reputation: 6345

If override the getAttribute() method on your model you can transform the key before the call:

public function getAttribute($key)
{
    $databaseColumn = implode('_', array_map('ucfirst', explode('_', $key)));

    return parent::getAttribute($databaseColumn);
}

This will allow you to do $model->get_model_param and it will access $model->Get_Model_Param on the model.

Upvotes: 0

Related Questions