0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel JavaScript Jsonでのデータ受け渡し

0
Last updated at Posted at 2026-06-11

1. Laravelから連想配列をJSONにして送る方法

Route::get('/api/user', function () {

    $user = [
        'name' => '田中',
        'age' => 25,
    ];

    return response()->json($user);

});

Laravelは内部で

json_encode($user);

を行い

{
    "name":"田中",
    "age":25
}

というJSON文字列をHTTPレスポンスのボディに入れて返します。

さらにレスポンスヘッダに

Content-Type: application/json

も付与されます。

2. JavaScriptが受け取ったJSONを扱う方法

fetch('/api/user')
    .then(response => response.json())
    .then(data => {

        console.log(data);

        console.log(data.name);
        console.log(data.age);

    });
response.json()


JSON文字列

JavaScriptオブジェクト
に変換している

3. LaravelからJSONに変換されずに送られてきたものをJavaScript側でJSONにする方法

例えばLaravel側が

$user = [
    'name' => '田中',
    'age' => 25,
];

return json_encode($user);

を返したとします。

この場合、

Content-Type: text/html

になる可能性があります。
JavaScript側では

fetch('/api/user')
    .then(response => response.text())
    .then(text => {

        const data = JSON.parse(text);

        console.log(data.name);

    });

となります。

JSON.parseとは

const jsonText =
'{"name":"田中","age":25}';

const obj = JSON.parse(jsonText);

すると

{
    name: '田中',
    age: 25
}

になります。
逆に

JSON.stringify(obj);

{"name":"田中","age":25}

へ戻せます。



Bladeへ渡す場合

return view('sample')
    ->with('user', $user);
const user = @json($user);

Ajax(fetch)で渡す場合

return response()->json($user);
fetch(...)
    .then(res => res.json())

まずはこの2パターンを確実に理解できれば、LaravelとJavaScriptのデータ受け渡しで困ることはかなり減ります。特に @json() は Blade と JavaScript を繋ぐための超重要な仕組みです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?