5
6

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 1 year has passed since last update.

【Laravel8.x ~ 】 @jsonディレクティブの改良版、@jsディレクティブが誕生していた

Last updated at Posted at 2022-05-10

@jsonディレクティブ

javaScript内でphpの変数をjson形式で渡したい場合、今までこう書いてたと思います

$data = ['name' => 'hoge','age' => 99 ];
console.log(@json($data));

image.png

JS::from()

そのまま展開出来るようになります。

use Illuminate\Support\Js;

$data = ['name' => 'hoge','age' => 99 ];
$data = Js::from($data);
console.log({{$data}});

image.png

JS::from()の後に出来た@Jsディレクティブ

$data = ['name' => 'hoge','age' => 99 ];
console.log(@js($data));

image.png

@jsonと変わんねえじゃねえかよ!と思うかもしれません。
何やら@jsonはBladeComponentに引き渡した場合にコンパイルされないという問題があったらしく、
その問題点を改良したのが@jsディレクティブだそうです。

なのでLaravel8.x ~ の人は@jsJS::from()使いましょう

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?