kirkbushell / eloquence

A drop-in library for certain database functionality in Laravel, that allows for extra features that may never make it into the main project.
MIT License
543 stars 58 forks source link

Relationship accessors not returned in camelCase #5

Closed ncskrypt closed 10 years ago

ncskrypt commented 10 years ago

When grabbing a relationship on a model (not a database column/attribute), it is set in snake_case rather than camelCase. Would be nice to have this added to Eloquence.

Example:

class User extends Eloquent {

    public function myItems() {
        return $this->hasMany('MyItem');
    }

}

Accessing the Model/Relationship (2 different approaches):

$user = User::find(1);
$user->myItems;         // Shorthand for $user->myItems()->get();

return $user;

OR:

$user = User::with('myItems')->find(1);

return $user;

Output:

{
    id: 1,
    fullName: 'John Smith',
    my_items: [...]
}

The attributes from the database come out as expected in camelCase. Unfortunately the relationship accessor does not. I'll look into possible solutions and let you know if I find anything.

ncskrypt commented 10 years ago

Got it (put in a pull request for yah)

If we overload the relationsToArray() function exactly as you do for attributesToArray() it works perfect

    /**
     * Get the model's relationships, converting field casing if necessary.
     *
     * @return array
     */
    public function relationsToArray()
    {
        $attributes = parent::relationsToArray();
        $convertedAttributes = [];

        foreach ($attributes as $key => $value) {
            if ($this->enforceCamelCase) {
                $key = camel_case($key);
            }

            $convertedAttributes[$key] = $value;
        }

        return $convertedAttributes;
    }