I am curious about how eloquent knows in which table it should save the records we give it by running $ php artisan tinker
. I do not actually remember setting
Actually if you not set the $table
property, Eloquent will automatically look the snake case and plural name of the class name. For example if class name is User
, it will users
.
Here the code taken from Illuminate/Database/Eloquent/Model.php
public function getTable()
{
if (isset($this->table)) {
return $this->table;
}
return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
}
In Laravel
when using Eloquent
you should assign a table name using the property $table
for example:
protected $table = 'some_thing';
Otherwise it assumes that the table name is the plural form of the model name and in this case for User
model the table name should be users
. Follwing paragraph is taken from Laravel
website:
Table Names
Note that we did not tell Eloquent which table to use for our Flight model. The "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
// You may use this instead:
class Flight extends Model
{
// Explicit table name example
protected $table = 'my_flights';
}
So, if you don't follw this convention when creating/naming your database tables that Laravel
expects then you have to tell Laravel
the name of the table for a model using a protected $table
property in your model.
Read the documentation here.
Model name is mapped to the plural of table name, like User model maps to users table and so.
When you do
User::all()
laravel knows that you want the records from users table.
To specify the table name explicitly you use protected $table ='name'
field on model.
Actually, Eloquent in its default way, is an Active Record System just like Ruby On Rails has. Here Eloquent is extended by a model. Those model name can be anything starts with capital letter. Like for example User
or Stock
but the funny thing is this active record system will imagine that if no other name of custom table is specified within the class model then the table name should be the small cased plural form of the Model name. In these cases users
and stocks
.
But by keeping aside theses names you can extensively can provide your own table name within the model. As in Laravel protected $table= 'customTableName'
Or, in a more descriptive way,
class Stock extends Eloquent{
// Custom Table Name
protected $table = 'custom_tables';
}
I hope this will solve your curious mind.