Kannan Ramamoorthy
Kannan Ramamoorthy

Reputation: 4180

Mapping of Eloquent models to tables?

We are able to create Eloquent models for tables. But how Laravel knows to which table to associate a model with? Do we have something similar to hbm.xml(mapping file we use for Hibernate) which says this model means this table.

Upvotes: 6

Views: 5152

Answers (2)

florin.prisecariu
florin.prisecariu

Reputation: 422

The table name is a protected property:

class User extends Eloquent {
    protected $table = 'my_users';
 }

Laravel Docs

Upvotes: 4

Kylie
Kylie

Reputation: 11749

You can manually override the table name as the above answer states. Its just a protected member of the Model.php class.

  class User extends Eloquent {
      protected $table = 'my_users';
  }

Otherwise, a lowercase, plural format is automatically used, based on the classname of the Model. (class_basename($this))

As shown here... (Illuminate/Database/Eloquent/Model.php)

 /**
 * Get the table associated with the model.
 *
 * @return string
 */
public function getTable()
{
    if (isset($this->table)) {
        return $this->table;
    }

    return str_replace('\\', '',    Str::snake(Str::plural(class_basename($this))));
}

Upvotes: 3

Related Questions