1
0

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】Ajaxバリデーション

1
Posted at

流れ

JavaScript(fetch)
↓ POST
Laravel

$request->validate()

バリデーション失敗

422 Unprocessable Entity
+エラー内容をJSONで返却

JavaScriptで受信

画面に表示

Laravel側のコード

public function store(Request $request)
{
    $validated = $request->validate([
        'item_cd' => ['required', 'max:10'],
        'item_name' => ['required'],
    ]);

    // 登録処理

    return response()->json([
        'message' => '登録完了'
    ]);
}

Laravelが返すJSON

{
  "message": "The item cd field is required.",
  "errors": {
    "item_cd": [
      "商品コードは必須です。"
    ]
  }
}

JavaScript側の受け取り方

fetch('/items', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': csrfToken
  },
  body: JSON.stringify({
    item_cd: '',
    item_name: 'テスト'
  })
})
.then(async response => {

  if (response.status === 422) {

    const data = await response.json();

    console.log(data.errors);

    return;
  }

  const data = await response.json();

  console.log(data.message);
});

各入力欄に表示する例

<input id="item_cd">

<div id="item_cd_error"></div>
if (response.status === 422) {

  const data = await response.json();

  document.getElementById('item_cd_error').textContent =
    data.errors.item_cd?.[0] ?? '';

  return;
}

?.[0]は、「item_cdのエラーが存在するなら1件目を取得する」という意味です。

Fetchメソッドの中身について

body: JSON.stringify({
  item_cd: '',
  item_name: 'テスト'
})

これは次のJSON文字列を作っています。

Content-Type: application/json

ボディの中身はJSON形式ですよ、とサーバーに伝えるためのヘッダです。
これがないと、Laravelはボディを正しく解釈できない場合があります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?