Model, controller & table naming conventions in Laravel

Published on March 23, 2020

Laravel is the most-loved PHP framework that lets you build web apps rapidly following the best coding and security practices. If you are new to Laravel and want to learn the naming conventions across different Laravel sections, then this post is for you.

Let’s begin with models.

Model naming convention

Your model name should be the singular name of the corresponding item and its first letter should be capitalized. Let’s say you are developing a blog CMS, you should name the post model as Post.

Migration naming convention

For the above Post model, you should create a table named posts. Here is the artisan command that you will have to execute.

You can go and add the corresponding fields to the migrations file and run your migrations.

Controller naming convention

Now for the Post model, there should be a controller that will let you interact with your data over HTTP. You should name your controller PostController. Following artisan command will generate the properly named controller for you:

I’ve used -r flag to create the necessary methods like index, show, update, create and destroy.

Instead of creating the items separately, you can use the below command to create the model, controller, and migration in a single shot. Just provide the valid model name and your controller and migration will be named properly.

Now let’s see the real power of this naming convention.

Say you didn’t follow this naming convention and named the models, migration table and controller randomly, then you could have to define the corresponding table name in the model as a property.

Now when you have properly named your models and migrations, you don’t need to do anything else. Model records can be created right away and Laravel will guess the database table name and all other relations will work flawlessly.

Controller naming would not play a critical role here but still, you should follow this naming convention in order to keep your code readable.

You may ask will this naming convention only eliminate the need for table name specification as a property? Is that the only benefit? And I’d say, no, it isn’t the only benefit. A valid naming convention that follows the framework docs will help you in several places including model relationships and so on.

I encourage you to go and read Laravel documentation thoroughly and follow the standard practices in order to ensure that your code stays clean and readable.

Tagged: laravelphpphp-frameworks

Rehmat Alam

Rehmat Alam

I'm a web developer & an open-source lover from Gilgit-Baltistan, Pakistan. I occasionally write here about what I find to be helpful for the community.

0 Comments

No comments found!

Post a comment