Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Izonnn's avatar

Easiest way to return camelCase instead snakeCase in laravel response

Hey, I'm trying to return response from my API wrote with laravel. Trying to get my data in client side with camelCase.

meaning : [{ customer_id: 12 , first_name: 'test' , last_name: 'testme' }];

Will be : [{ customerId: 12 , firstName: 'test' , lastName: 'testme' }]

I wrote a service provider that's working and changing my response()->json() to camcelCase but it's needed to change in my controller from :

return Customer::orderBy('name')->get(); to : return response()->Json(Customer::orderBy('name')->get());

Any easy solution for that? Tnx.

0 likes
7 replies
Izonnn's avatar

There is no mention of what I asked or i'm missing something ?

1 like
tykus's avatar

Whenever you use Eloquent API Resources, you define the structure of the resulting JSON. So, you set the keys.

For what it's worth, returning this Customer::orderBy('name')->get() is a somewhat lazy approach; yes, it works, but your API will change whenever you modify the underlying table; almost (depending on what is hidden, or appended) every column in the table becomes a key/value pair in the response JSON. You lose control over the response.

1 like
Izonnn's avatar

The best practice for that it's to make resource for each model/controller? And with this approach i can prepare my data to client side as i wish and not using hidden property or i should use it both resource & hidden together ?

tykus's avatar

No need for hidden properties on the model, your Resource will define the JSON representation of the Model so long as you return the Resource from the Controller.

1 like
Izonnn's avatar

Understood, if it's the best practice to work with i will create resource each model. Thanks guys !

evocraig's avatar

I wanted the same thing and ended up writing a custom resource which I then passed models/queries to.

<?php

namespace App\Http\Resources;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Resources\Json\JsonResource;

abstract class BaseInertiaResource extends JsonResource
{
    public static $wrap = null;

    private function recursivelyMapKeysToCamelCase($arr)
    {
        return Arr::mapWithKeys($arr, function ($item, $key) {
            if (is_array($item) && Arr::isAssoc($item)) {
                $item = $this->recursivelyMapKeysToCamelCase($item);
            }
            return [Str::camel($key) => $item];
        });
    }

    public function resolve($request = null)
    {
        $resolved = parent::resolve($request);
        return $this->recursivelyMapKeysToCamelCase($resolved);
    }
}

Please or to participate in this conversation.