[Laravel practice] How to convert request parameter name to snake case

Aug 30, 2020 PHP Laravel snake case camelCase snake_case

Version

Premise

When developing an API with Laravel, assume that you want to convert request parameter names written as camel cases into snake cases. For example, in SPA development, when sending a request to Laravel’s API by asynchronous communication with React.js or Vue.js, you want to use CamelCase as the front side, but snake case as the backend side. ..

I googled how to easily convert it on the Laravel side, but I have not come up with a best practice method, so I will share it here.

Let’s convert now.

To put it simply, you can achieve it in the following ways:

Receive request parameters with $request->all(), convert/insert into snake case when request parameter name ($key) contains upper case, delete the original property name with offsetUnset() I am doing that.

foreach ($request->all() as $key => $value) {
    if(preg_match('/[A-Z]/', $key)){
        $new_key = Str::snake($key);
        $request->merge([$new_key => $request->$key]);
        $request->offsetUnset($key);
    }
}

For example, let’s consider receiving by the index of TestController. Once you ignore the validation, you should be able to write:


class TestController
{
    public function index(Request $request)
    {
        // Convert to snake case
        foreach ($request->all() as $key => $value) {
            if(preg_match('/[A-Z]/', $key)){
                $new_key = Str::snake($key);
                $request->merge([$new_key => $request->$key]);
                $request->offsetUnset($key);
            }
        }
        // hoge hoge processing
        ...
        return $request;
    }
}

Application: Create class for snake case conversion

I think there are various ways to apply it, but I finally settled in the following way.

// *2
class NormalizedController extends Controller
{
    /**
     * Change request parameter from camel case to snake case
     *
     * @param object $request
     * @return object
     */
    protected function normarize_request(Object $request): object
    {
        foreach ($request->all() as $key => $value) {
            if(preg_match('/[A-Z]/', $key)){
                $new_key = Str::snake($key);
                $request->merge([$new_key => $request->$key]);
                $request->offsetUnset($key);
            }
        }
        return $request;
    }
}
// FormRequest class (*1)
use App\Http\Requests\Test\GetRequest;

class TestController extends NormalizedController
{
    public function index(GetRequest $request)
    {
        // Call (*3)
        $this->normarize_request($request);

        // hoge hoge processing
        ...
        return $request;
    }
}

Reference