LoginSignup
31
17

More than 3 years have passed since last update.

Laravel 自作のヘルパ関数を追加する

Last updated at Posted at 2020-05-04

概要

Laravel では様々なグローバルヘルパ関数が用意されています。
https://readouble.com/laravel/7.x/ja/helpers.html

今回は自作のヘルパ関数を作る方法をご紹介します。

環境

  • PHP 7.4.5
  • Laravel 7.9.2

やり方

自作のヘルパファイルを作成して、オートローダーに読み込んでもらいます。

自作のヘルパファイルを作成する

app/helpers.php を作成します。
(場所はどこでも良いです)

app/helpers.php
<?php declare(strict_types=1);

if (! function_exists('hello')) {
    /**
     * @return string
     */
    function hello(): string
    {
        return 'Hello World.';
    }
}

ヘルパファイルをオートローダーで読み込む

composer.jsonautoload.files を下記のように変更します。

composer.json
    "autoload": {
        "files": [
            "app/helpers.php"
        ],
        // ...
    },

オートローダーの更新

$ composer dump-autoload

これで composer.json の変更が反映されます。

お試し

$ php artisan tinker

>>> hello()
=> "Hello World."

自作したヘルパ関数を実行できました!

関連記事

31
17
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
31
17