I just recently started experimenting with laravel, lovely. One thing l dont understand though is how laravel knows my table l just added a model and the model isnt the exact table name, but just how does it manage to get my table,
Laravel follows a Naming convention for Eloquent Classes and Tables.
From Laravel Website | Eloquent: Getting Started
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.
Eg.
Class User
will by default refers to Mysql Table users
(Camel Case to Snake Case and Plural).
Class NotificationsLog
will by default refers to Mysql Table notifications_logs
(Camel Case to Snake Case and Plural).
But if you don't want to follow the convention then you can Mention the table name explicitly
Eg. If I want my Class Plane
should refers to flights
table in Database then following code will work
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Plane extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'flights';
}
Reference to Eloquent Model Conventions:
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.
Internally, Laravel does something like this.
$table = $table ?: Str::plural($name);
So it will automatically try to look for the plural of your model name if no $table
property is being set.
Actually the when you make a model it automatically make a table with it's plural you could change this by added the following code in the model
protected $table= 'table_name';
Please also check the name in the migration it should be same as the name you mentioned in the model class because it might show error while using eloquent class functions due to different table names