LoginSignup
1
0

More than 3 years have passed since last update.

🏰【Laravel6】MariaDBから取得したJSON型の任意の値をBladeで表示する

Last updated at Posted at 2020-01-08

環境

PHP 7.3.10
Laravel 6.5.0
MariaDB

やりたいこと

MariaDBのに下記のようなデータがあり、
その内のcontentカラム(JSON型)のデータからvalueの内容である
「テストの内容です🐾」や「2の内容!!」をBladeテンプレートに直接表示したい

id content del_flg
1 {"data_kind": "1", "value": "テストの内容です🐾"} 0
2 {"data_kind": "2", "value": "2の内容!!"} 0
3 {"data_kind": "1", "value": "削除済データ😭😭😭"} 1

本来であればVue.jsやReactとかで取得データを処理して表示するのが賢い方法だと思うが
それ以前の環境とかで無理やり表示したいことがあった

やったこと

COntrollerでは普通にJSONの文字列としてデータ取得しでViewに渡す
Viewでは受け取ったデータをjson_decode()して表示する

app/Http/Controllers/testController.php
    /**
     * 画面表示
     */
    public function index() {
        // 対象データ取得
        $hogeTalks = DB::table('hoge_talks')
        ->select('*')
        ->where('del_flg', 0)
        ->get();

        // Viewにデータ渡し
        return view('test.index', [
            'talks' => $hogeTalks,
        ]);
    }
resources/views/test/index.blade.php
{{ json_decode($talks->content)->value }}

結果

content内のvalueの値のみがテンプレートに表示されます
同様にアロー演算子の先をdata_kindに変更等、任意のkeyに変更して使用できます

1
0
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
0