user5512902
user5512902

Reputation: 603

How to change Laravel model's table name

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?

Upvotes: 52

Views: 140282

Answers (4)

Fabiano Oliveira
Fabiano Oliveira

Reputation: 601

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

Upvotes: 50

Nino Giovanny
Nino Giovanny

Reputation: 121

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

composer dump-autoload

Upvotes: 3

pespantelis
pespantelis

Reputation: 15382

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.

Upvotes: 102

Vojko
Vojko

Reputation: 804

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';

Upvotes: 26

Related Questions