Roi
Roi

Reputation: 565

How Laravel Eloquent references the right table

I'm currently watching the Laravel Tutorial Episode 7

https://laracasts.com/series/laravel-from-scratch-2017/episodes/7

I created the database and populated its data on the previous episode,

it is only this time, the tutorial introduces model, upon creating the model name "Task" via php artisan make:model Task, it automatically connects to my table "tasks" without any clue how it happened.

So how did a freshly out of the box model knows it?

Upvotes: 0

Views: 1989

Answers (2)

gd_silva
gd_silva

Reputation: 1025

It's a convention Laravel follows. Laravel will search for a table that is the snake cased Model's name in plural unless you indicate another table.

If you generate the model with the migration flag (e.g. php artisan make:model Task --migration), it will also create a table with the model's name in plural automatically (in this case, Tasks).

You can check more about it in the documentation.

Table Names

Note that we did not tell Eloquent which table to use for our Flight model. By convention, 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 specify a custom table by defining a table property on your model (...)

Upvotes: 0

Sagar Gautam
Sagar Gautam

Reputation: 9389

It's general definition standard.

If you create a table with plural name and create model for this table as singular, then model automatically connects corresponding table, otherwise you should define table name in model like:

protected $table = 'task_table';

Upvotes: 3

Related Questions