Mervyn Yet
Mervyn Yet

Reputation: 383

Laravel assumes the database table is the plural form of the model name

By default, Laravel is assuming that the database table is the plural form of the model name. But what if my table name is "news" and i still want to use this feature? should i change it to "newses" or should i use "new" for the model name?

Upvotes: 28

Views: 34881

Answers (4)

Vijayanand Premnath
Vijayanand Premnath

Reputation: 3605

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Ref:https://laravel.com/docs/5.1/eloquent

Upvotes: 38

Justin Origin Broadband
Justin Origin Broadband

Reputation: 1520

Laravel uses a "standard set" rule that defines:

  • A Model is a single instance of a record
  • A Collection is one or more records

Therefore it assumes that a table is a collection of records.

The nomenclature has a problem when it clashes with various features / gotchas of human languages. For example, what if I have a Model called Sheep? That does mean my Database Table should be called "Sheeps"?

It's up to the developer to avoid "Gollum/Smeagol" syntax. Indeed, you wouldn't want a table called "Newses" as much I'd like to end up with a table called "Sheeps".

Ultimately, I construct Migrations with:

sudo php artisan make:migration create_sheep_table --create=sheep

As for Models, you'll notice in the documentation that they have a different table name for "Flights" called "my_flights"

https://laravel.com/docs/master/eloquent#defining-models

Again, it's up to the developer / DB manager to make decisions on naming conventions that make sense in an application context.

Upvotes: 5

Koeno
Koeno

Reputation: 1573

If you have a model ending with the letter 's', it will keep the table name the same. In your case, your model will name your table news by default.

If you want to use another name though, you can use:

protected $table = 'tablename';

inside of your model.

EDIT: I tested this in my application. I made a model named News. Then I made a new instance of News and retrieved the table name:

$news = new News();
dd($news->getTable());

It returns: news

Upvotes: 16

KuKeC
KuKeC

Reputation: 4610

Inside your eloquent model you have to define table name. For example if my model is named user and table in database is named user_of_application then i do it this way

class user extends Model
{
    protected $table = 'user_of_application';
}

Upvotes: 12

Related Questions