Search code examples
mysqllaraveleloquentlaravel-4

How can I use my own column names while working with Laravel 4's Eloquent ORM?


Suppose I have the following MySQL table:

CREATE TABLE backend_users(
id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(30) UNIQUE NOT NULL,
password VARCHAR(40) NOT NULL,
salt VARCHAR(16) NOT NULL,
needsNewPassword TINYINT(1) UNSIGNED NOT NULL,
forgotPasswordKey VARCHAR(8) NULL,
fullName VARCHAR(50) NOT NULL,
email VARCHAR(255) NOT NULL,
roleType INT NOT NULL,
enabled TINYINT(1) UNSIGNED NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
PRIMARY KEY (id)
) CHARACTER SET utf8 COLLATE utf8_general_ci;

How can I use an Eloquent Model to record new rows to the table using the column names above? If I try it as explained in the docs:

$user = User::create(
array(
'userName' => 'emmanuel',
'password' => $encryptedPassword,
'salt' => $salt,
'needsNewPassword' => 0,
'fullName' => 'Emmanuel Figuerola',
'email' => 'somemail@gmail.com',
'roleType' => 0,
'enabled' => 1
)
);

I get the following error:

Exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_name' in 'field list' (SQL: insert into backend_users (user_name, password, salt, needs_new_password, full_name, email, role_type, enabled, updated_at, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) (Bindings: array ( 0 => 'emmanuel', 1 => '70b104a42c4ac5e79ca7c150bf872b383e0eedca', 2 => '5514512bffb33f4a', 3 => 0, 4 => 'Emmanuel Figuerola', 5 => 'somemail@gmail.com', 6 => 0, 7 => 1, 8 => DateTime::__set_state(array( 'date' => '2013-02-26 00:20:03', 'timezone_type' => 3, 'timezone' => 'UTC', )), 9 => DateTime::__set_state(array( 'date' => '2013-02-26 00:20:03', 'timezone_type' => 3, 'timezone' => 'UTC', )), ))

Which, if you don't wanna read all of that, simply means Eloquent is using whatever column names it desires, and not MY column names, even when I clearly specified the name and value for each one of them.

What should I do? If possible, please don't say "rename your columns" because it would mean renaming a LOT OF COLUMNS (I have many tables). Besides, I didn't read anywhere about a specific naming convention for column names.


Solution

  • Laravel assumes column names use the snake_case convention. This is built into Eloquent itself. Laravel doesn't actually know your column and table names ahead of time.

    It would be possible to extend Eloquent and override any methods the dynamically create table and column names. Since Laravel 4 is still in beta, you'd need to keep your extended version up to date with any upstream changes. It would probably be less time to update your DB's schema then venture down this path.