39

I am using Laravel 5 and have changed the name of a database table from "domain_related_settings" to "DomainRelatedSettings" by rolling back all migrations, changing the specific migration, and running them again. The new table name is reflected in the database.

But when i use the corresponding model DomainRelatedSetting in a statement like this:

$domainSettings = DomainRelatedSetting::where('hostname', 'foo')->first();

it gives the following error:

SQLSTATE[42S02]: Base table or view not found:
1146 Table 'databasename.domain_related_settings' doesn't exist
(SQL: select * from `domain_related_settings` where `hostname` = foo limit 1)

So it is still using the old table name. How can I ensure the new table name is used?

miken32
  • 42,008
  • 16
  • 111
  • 154
user5512902
  • 473
  • 1
  • 4
  • 12
  • after defining table property on model class `protected $table = 'DomainRelatedSettings';` it still giving the error? – StealthTrails Dec 25 '15 at 11:39
  • no, when i add this row the error is gone. – user5512902 Dec 25 '15 at 11:42
  • Check the `Table Names` section: https://laravel.com/docs/5.1/eloquent#defining-models – Pantelis Peslis Dec 25 '15 at 12:07
  • I thought i should use the singular form in my model and the plural form in the table. But it seems that when my model is name "SomeExample". It not only looks for the plural version but also for "some_example". Thanks. Sometimes i don't understand why they don't add a more a more comprehensive example in the (already very good) docs. – user5512902 Dec 25 '15 at 12:14

4 Answers4

81

If you don't want to use the default table name (the "snake case", plural name of the class), you should specify it to the model:

protected $table = 'DomainRelatedSettings';

Check the documentation at the Table Names section.

Pantelis Peslis
  • 14,930
  • 5
  • 44
  • 45
39

You may specify a custom table by defining a table property on your model:

class theModel extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'name_of_table';
}

In case it doesn't work, try typing this command inside from your root folder: composer dump-autoload -o

Swift
  • 3,250
  • 1
  • 19
  • 35
22

You need to specify the table name inside the each Laravel model by using

protected $table = 'name_of_table';

so in your case

protected $table = 'DomainRelatedSettings';
Vojko
  • 604
  • 3
  • 12
2

If you specify the real name of the tables in your models but still the same problem, try:

composer dump-autoload
Fernando Kosh
  • 3,426
  • 1
  • 34
  • 31