4
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】Controllerで返したphpの配列をJavaScriptの配列に変換する

Last updated at Posted at 2019-04-15

##環境
laradock
(PHP - 7.2)
(Laravel - 5.7)

##ポイント
・JSON_UNESCAPED_UNICODEを第2引数に指定してjson_encode()する
・{!! !!}で囲ってechoする

##Controller

GirlsController.php
<?php
namespace App\Http\Controllers;

class GirlsController extends Controller
{
    public function index()
    {
        $name = array('辻野あかり', '砂塚あきら', '夢見りあむ');
        $kana = array('つじのあかり', 'すなづかあきら', 'ゆめみりあむ');
        return view($viewName, compact('name', 'kana'));
    }
}

##route

web.php
Route::resource('girls', 'GirlsController');

##blade

girls.blade.php
<script type="text/javascript">
//Unicode文字列にされるのを防ぐためJSON_UNESCAPED_UNICODEを第2引数にjson_encode()
//ダブルクオーテーションが&quot;に置き換わってしまうのを防ぐため{!! !!}で囲う
const names = {!!json_encode($name, JSON_UNESCAPED_UNICODE)!!}
const kana = {!!json_encode($kana, JSON_UNESCAPED_UNICODE)!!}

####追記
※コメントで教えて頂きましたが、Laravel5.5からは@json()でできるようです。

girls.blade.php
<script type="text/javascript">
const names = @json($name);
const kana = @json($kana);
4
2
2

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
4
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?