Laravel – Database, Table and Column Naming Conventions?

Laravel has its own naming convention. For example, if your model name is User.php then Laravel expects class ‘User’ to be inside that file. It also expects users table for User model. However, you can override this convention by defining a table property on your model like,

    class User extends Eloquent implements UserInterface, RemindableInterface {
        protected $table="user";
    }

From Laravel official documentation:

Note that we did not tell Eloquent which table to use for our User model.
The lower-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 User model stores records in the users table. You may specify a
custom table by defining a $table property on your model

If you will use user table id in another table as a foreign key then, it should be snake-case like user_id so that it can be used automatically in case of relation. Again, you can override this convention by specifying additional arguments in relationship function. For example,

    class User extends Eloquent implements UserInterface, RemindableInterface {
        public function post(){
            return $this->hasMany('Post', 'userId', 'id');
        }
    }

    class Post extends Eloquent{
        public function user(){
            return $this->belongsTo('User', 'userId', 'id');
        }   
    }

Docs for Laravel eloquent relationship

For other columns in table, you can name them as you like.

I suggest you to go through documentation once.

Leave a Comment