Laravel - Database, Table and Column Naming Conventions? - php

I'm using laravel eloquent data objects to access my data, what is the best way to name my tables, columns, foreign/primary keys etc?
I found, there are lots of naming conventions out there. I'm just wondering which one best suits for laravel eloquent models.
I'm thinking of following naming convention:
Singular table names (ex: Post)
Singular column names (ex: userId - user id in the post table)
Camel casing for multiple words in table names (ex: PostComment, PostReview, PostPhoto)
Camel casing for multiple words in column names (ex: firstName, postCategoryId, postPhotoId)
So with this, I could use similar syntax in the controller.
$result = Post::where('postCategoryId', '4')->get();
Are there any recommended Laravel guidelines for this? Can I proceed with these naming conventions?
If someone has better suggestions, I will be very happy to hear them.Thanks a lot!

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.

I don't agree in general with these examples you both have shown right on here.
It is clean if you take a look at the official Laravel documentation, especially in the Eloquent's relationship session (http://laravel.com/docs/4.2/eloquent#relationships).
Table names should be in plural, i.e. 'users' table for User model.
And column names don't need to be in Camel Case, but Snake Case. See it is already answered: Database/model field-name convention in Laravel?
It is too usual you can see it is like the RedBeanORM: the Snake Case for columns, even if you try other one. And it is adviced to avoid repeating the table names with column ones due to the method you can call from the Model object to access their relationships.

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

The default table naming conventions can easily cause conflicts with the installation of multiple packages who may have incidentally the same class names. A solution would be to name tables as: [vendor].[package].[class], which is in line with how namespacing in Laravel is applied.
Edited: Using dots in table names is not recommended though. Would there be an alternative convention to use to ensure developers of a modular built application do not need to worry about existing table names.

Related

How laravel defines a related table to a model that will be executed to get some data? [duplicate]

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 so an option.
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.
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))));
}
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.

Connecting database fields and model attributes in Laravel

I'm just getting going with Laravel, and have used Eloquent to define my Campaign table. I have a Campaign model which is currently empty.
I'm not sure how to add attributes to this model to represent the fields in the db - or even if I should. The Laravel documentation seems thin on models and searches keep leading me to accessors and mutators.
If I have a database field called platform_type in my campaigns table, how do I link the PlatformType model attribute to this field?
To clarify:
This is not a question about relationships - there is only one entity in my solution thus far.
platform_type is a field in my campaigns table because it is an attribute of a campaign - I'm asking how to represent this in my model.
The model has an internal array which stores the attributes of a given row (it's called $attributes and replicated by $original if you look for them in the source code). The reason it's replicated is so when you call save() it will only do a save if you actually changed them from the originals.
You can access said attributes via $modelInstance->getAttribute("platform_type") or $modelInstance->platform_type which will call the magic __get method that in turn calls the getAttribute
So in your case you can have:
$campaign = Campaign::find($id);
echo $campaign->platform_type;
The ORM will automatically create the relevant SQL query and fill the model instance with the attributes of the row it finds.
You need to define relationships. In the PlatformType model:
public function campaigns()
{
return $this->hasMany(Campaign::class, 'platform_type');
}
And in the Campaign model:
public function platformType()
{
return $this->belongsTo(PlatformType::class, 'platform_type');
}
You also need to rename the campaign table to campaigns. Or you should add this to the model to be able to use a custom name:
protected $table = 'campaign';
At this point, these tables will be connected and relationships will work. However, it is recommended to add foreign key constraints.

Laravel sounds like magic

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,
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.
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';
}
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

What is the right Laravel class name for a given table name?

If I have database table suggestions_votes, what would be the correct name of Laravel (5.1) Class (SuggestionsVote or SuggestionVote)?
Table was created by migration, using
Schema::create('suggestions_votes', ...
Laravel recommends certain conventions, but they also provide you with options to override them.
If your model is "SuggestionVote", then the table associated with that model will be the snake case plural name of the class. In other words, it would look for the table "suggestion_votes". If you want to override the associated table name, you can add this property to your model:
protected $table = 'suggestions_votes';
If you are actually creating a pivot table for the models "Suggestion" and "Vote", then Laravel will by convention join the two related model names in alphabetical order. In other words, it will look for the pivot table "suggestion_vote". You can override this though when you define the relationship. For example:
return $this->belongsToMany('App\Suggestion', 'suggestions_votes');
Where 'App\Suggestion' would be fully namespaced path to your Suggestion class.
It depends. You can make any name work.
If you have no control of the database, the model 'should' be SuggestionsVote
If you do have control over the database, I would rename the table to suggestion_votes and the model name would be SuggestionVote

Laravel schema builder converts tablename to lowercase

I'm just wondering why the schema builder in laravel automatically convert all camel case to lower case in table naming
E.g
Schema::create('myTable', function(Blueprint $table)
{
....
});
It creates tablename: mytable
Why is that? Is that a convention of laravel? I don't see it in the laravel docs Schema Builder page.
Thanks
It's a common practice to use snake case in table names and field names as well and it's not only related to laravel but most people follow this convention. In Laravel's old (4x) documentation, it's been mentioned that:
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:
class User extends Eloquent {
protected $table = 'my_users';
}
So, yes, Laravel uses strtolower function in many places and probably this is better to follow the common convention and it's (my_table) known as snake case.

Categories