6
5

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 5 years have passed since last update.

Laravelのhelper関数を自作する

Last updated at Posted at 2018-03-14

Laravelのhelper関数

Laravelにはグローバルで使えるヘルパー関数が幾つかあります。
asset、old、url、view辺りはよく使ってます。
特にview回りはコンテナからクラスを取ってくるのが非常に面倒なので、グローバルのヘルパー関数を使うと楽だと思います。
これらの関数はlaravel/framework/src/Illuminate/Foundation/helpers.phpのファイルにあり、laravel/framework/composer.jsonの設定によって読み込まれています。

helper関数の自作

helpersファイルを作る

自作のhelpersファイルを作っていきます。

helpers.php
<?php

if (!function_exists('custom_function')) {
    /**
     * 自作関数
     */
    function custom_function($hoge)
    {
        //
    }
}

helper関数を読み込む

composer.jsonのautoloadにfilesというkeyの配列を追加し、ファイル名を入れます。
filesの説明はこちら https://getcomposer.org/doc/04-schema.md#files

composer.json
---  ---
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/",
            "Domain\\": "domain/",
            "Infra\\": "infra/",
            "Model\\": "model/"
        },
        "files": [
            "helpers.php"
        ]
    },
---  ---
6
5
1

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?