Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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', ...
like image 904
renathy Avatar asked Nov 27 '25 21:11

renathy


1 Answers

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.

like image 137
Thomas Kim Avatar answered Nov 29 '25 12:11

Thomas Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!