1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel 独自のヘルパ関数を定義してみる

1
Posted at

概要

  • 独自ヘルパ関数の定義方法を簡単にまとめる。

前提

  • 今回は「すべての階層の配列のキーをスネークケースからキャメルケースに変換する関数」をユーザー定義の独自ヘルパ関数として定義してみる。

方法

  1. app/Helpers/helpers.phpファイルを作成し、下記のように記載する。

    app/Helpers/helpers.php
    <?php
    
    declare(strict_types=1);
    
    use Illuminate\Support\Str;
    
    /**
     * 配列のキーをすべてスネークケースからキャメルケースに変換
     *
     * @param array<mixed> $array
     * @return array<mixed>
     */
    function arrayKeysToCamelCase(array $array): array
    {
        $camelCaseArray = [];
        foreach ($array as $key => $value) {
            $camelCaseKey = Str::camel($key);
        
            // 再帰的に本関数を呼び出し
            if (is_array($value)) {
                $value = arrayKeysToCamelCase($value);
            }
        
            $camelCaseArray[$camelCaseKey] = $value;
        }
    
        return $camelCaseArray;
    }
    
  2. composer.jsonのautoloadfilesを追記してhelpers.phpを指定する。

    composer.json
    "autoload": {
        "files": [
            "app/Helpers/helpers.php"
        ],
    
  3. 下記コマンドを実行してオートロードを行う。

    composer dump-autoload
    
  4. $ php artisan tinkerでtinkerを起動し、arrayKeysToCamelCase()を実行しundefinedにならないことを確認する。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?