Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

So given the following schema:

users
    id (int)
    some_group_id (int)
    some_field (string)
some_group
    id (int)

I'd have the following relationship method in my User model:

public function someGroup()
{
    return $this->belongsTo('SomeGroup');
}

Normally I'd therefore access the various fields like this:

$user = user::find(1);
echo $user->some_field; // echoes the value of some_field
echo $user->someGroup->id; // echoes the value of the id field on the related SomeGroup

That's all well and good, but I found out today that I can access the relation using snake case:

echo $user->some_group->id; // works!

This is good for me because it means that my view code can now have more continuity. Instead of the disparity between $user->some_field and $user->someGroup I can use $user->some_field and $user->some_group.

Interestingly, the same doesn't work the other way - so I can't use $user->someField.

My question is can I rely on this behaviour? Is it defined somewhere? If I start to use it, can I rely on it to not change (with reasonable confidence of course, I'm aware even defined behaviour can change)?

Last updated 2 years ago.
0

Probably it won't change any soon and it is working for relations (while not for the attributes) because of Model's getAttribute method. There anything not being an attribute, mutated prop, or already loaded relation (in that order) is supposed to be a call to the relation, and it's processed by camel_case method and called.

Last updated 2 years ago.
0

Cheers, that sounds reasonable to me. Looks like it's not defined behaviour (i.e. "it should work like this") but it's as-good-as by the implementation and it's unlikely to change by the way everything else works, which possibly is defined behaviour.

Last updated 2 years ago.
0

Since I've upgraded to Laravel 5, all of my model->snake_case relationship calls are breaking. I've had to go back and change them all to camelCase. Has anyone noticed this behavior or can anyone point to documentation or anything that verifies this?

0

There are inconsistencies in laravel 4.2 as well. Specifically, accessing relations via snake_case circumvents eager loading. If you do a search for snake_case on the Laravel GitHub issue tracker you'll see that supporting both camel and snake case has been difficult and fraught with trade-offs.

There was a 4.2 request to remove the ability to use snake_case relationships because they misbehave. However, Taylor's response was to not fix it and the change was pushed to 5.0.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.