2
2

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でjsに値を渡すヘルパー関数を作成

2
Posted at

概要

ヘルパー関数を作りたかったのとJavaScriptで表示制御を行う場合、PHPからパラメーターをJavaScriptに渡したい。
そのため、受け渡し用の関数を作成してみたのでメモを残します。

ヘルパー関数の作成

ヘルパー関数を記述するファイルがなかったので追加し、関数を定義する。
※ json_encodeのオプションについては、参考サイトで紹介されているものを指定

app/helpers.php
<?php

/**
 * JavaScriptの変数に変換する
 *
 * <JSONのエスケープ>
 * http://blog.ohgaki.net/json-escape
 *
 */
function jsVariable($data) {
    return json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
}

作ったファイルの読み込み

composerで管理しているので、そちらで読み込むようにする。

composer.jsonに追記

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

        
        
        

    },

composerを更新する

ターミナル
$ php composer.phar self-update
$ php composer.phar dump-auto

以上

参考サイト

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?