camelCase variables and snake_case database columns
Laravel suggests camelCase for all variables inside and outside of classes/methods/functions.
Laravel suggests snake_case for all columns in the database.
When it comes time to $Model->fill() | Model::create(), I find instead I'm writing lines and lines of:
Some cursory searching didn't reveal any good answers, some talk about using the Str::snake() helper but I'm not that excited about creating something that iterates over arrays and ${Str::snake($key)} = $value.
Alternatively break standards and snake_case it all. What is the community's thought/solutions on tackling this minor problem?
The variable in this case is $data; the key is camelCase1 etc. And you're not using fill or create whenever you assign to the individual properties like that. If you're that worried about case, why is it $Model and not $model?
If you're that worried about case, why is it $Model and not $model?
This was a typo on my part.
I'm not sure I understand what you're explaining with the example $data array. In my case, $data is returned by a service, but yes, I could go in and modify the service to return $data with key names that are snake_case if that is what you mean.
I was in the camelCase mindset and was writing $data['camelCase'] = $camelCase; in the service without thinking about it.
in database column or table names are case-insensitive. hence having camel-case/all uppercase/all lowercase words won't matter. all are considered same thing. so to differentiate between user provided values (columns names & table names) & (database related keywords). the convention of snake case was adopted to make things look simpler.
on the other hand, in PHP variable names are case-sensitive, which means camelcase & other things matter. hence the suggestion.
edit: I meant all strings(any column names, table names, or keywords) are case-insensitive in most database.
@rajeshtva The database isn't always case sensitive when it comes to column names, at least not the Oracle database, it all depends on how you define the column name. If I remember correctly it goes like this.
Column_Name (case insensitive)
'Column_Name' (case insensitive)
"Column_Name" (Case sensitive)
I suggest that you should always use lowercase and snake case when defining columns.
@rajeshtva A MySQL rdbms and an Oracle RDBMS are two different things, but I guess you know that, but just wanting to make it clear for any future visitors.
I know I't probably not the best approach (or at least it could be written more eloquent, or less robust), but in my case, using Livewire 3 Form (but this doesn't effect the scenario a lot), I have this solution. This in my case, collects all the fillables from a model, and returns all it's representatives from a form it it's present