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

学習108日目

Last updated at Posted at 2025-09-19

テーマ

jsで取得したデータをdb保存する

前提

  • laravelで開発中
  • 該当部分以外の記述は省略

内容

流れは下記。

  1. JavaScript (フロント側) からフォームデータや値を取得
  2. Ajax (fetch / axios / jQuery.ajax など) を使って Laravel のルートへリクエストを送信
  3. Laravel (バックエンド側) でリクエストを受け取り、DBに保存
  4. 保存結果をJSONで返す
  5. JavaScript でレスポンスを受け取って画面に反映

ルーティング

routes/web.php

use App\Http\Controllers\PostsController;

Route::post('/posts', [PostsController::class, 'store'])->name('posts.store');

コントローラ

app/Http/Controllers/PostsController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostsController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'body'  => 'required|string',
        ]);

        $post = Post::create($validated);

        return response()->json([
            'success' => true,
            'post' => $post,
        ]);
    }
}

モデル

app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'body'];
}

ビュー

create.blade.php

<input type="text" id="title" placeholder="タイトル">
<textarea id="body" placeholder="本文"></textarea>
<button id="saveBtn">保存</button>

<script>
document.getElementById('saveBtn').addEventListener('click', async () => {
    const title = document.getElementById('title').value;
    const body = document.getElementById('body').value;

    const response = await fetch('/posts', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value;
        },
        body: JSON.stringify({ title, body })
    });

    const data = await response.json();
    console.log(data);
    if (data.success) {
        alert('保存しました!');
    }
});
</script>

コメント

  • 流れはrailsの時と同じ
  • 細かい部分の記述について調べる
0
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
0
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?