Laravel "c" replaces variable case for snake case
In my Laravel application, I have a model that defines relationships like:
public function vitalCategories()
{
return $this->belongsToMany(
'App\Models\Diagonals\VitalLabelCategory',
'vitalLabelCategoryMap',
'vitalLabelId',
'vitalLabelCategoryId');
}
When I request an entry like below I expect the relationship to be available with a variable name vitalCategories
$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
return json_encode($vitalLabel);
However, the above query creates a relationship named "vital_categories" as follows:
How can I get laravel to stop changing my variable for a snake case relation?
Just for the fun of it, I've also tried:
$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
$vitalLabel->load('vitalCategories');
$vitalLabel->vitalCategories = $vitalLabel->vitalCategories() ;
return json_encode($vitalLabel);
which couldn't see related models:
then I tried:
$vitalLabel = VitalLabel::where('label', 'confirmation')->with(['subscribers','vitalCategories','vitals'])->first();
$vitalLabel->load('vitalCategories');
$vitalLabel->vitalCategories = $vitalLabel->vital_categories;
return json_encode($vitalLabel);
which also failed to see related models:
source to share
Laravel will automatically convert relationship names from camelCase
to snake_case
when the model is converted to array ( toArray()
) or json ( toJson()
).
So the attribute is on the model actually vitalCategories
, but when you dump it as json it will print as vital_categories
.
If you want to disable this, you can set the property $snakeAttributes
on your model to false.
public static $snakeAttributes = false;
source to share