解決したいこと
アプリ作成初心者です。
Laravel10で簡単な投稿機能を実装しています。
投稿に対してコメント機能を実装したのですが、jQueryを用いてajax化したいです。
ただ、どのように実装していけば良いか検討もついていない状態です。
ヒントをいただけると嬉しいです。
ソースコード
- views/book/show.blade.php
<!-- コメント機能 start --> <div class="bg-white rounded-lg shadow-md mb-4 p-4"> <form method="post" action="{{ route('comment.store') }}"> @csrf <input type="hidden" name="book_id" value="{{ $book->id }}"> <div class="mb-4"> <textarea name="body" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring focus:ring-indigo-200" rows="5" placeholder="コメントを入力する">{{ old('body') }}</textarea> </div> <div class="text-right"> <button type="submit" class="px-4 py-2 bg-indigo-500 text-white font-semibold rounded-md hover:bg-indigo-600">コメントする</button> </div> </form> </div> @if($book->comments->count() > 0) <div id="comment-data"></div> @foreach($comments as $comment) <div class="bg-white rounded-lg shadow-md mb-4 p-4"> <div class="flex items-center mb-2"> <span class="text-gray-700 font-semibold">{{ $comment->user->name ?? '削除されたユーザー' }}</span> </div> <div class="text-gray-800 mb-4"> {{ $comment->body }} </div> <div class="text-gray-500 text-sm text-right"> 投稿日時 {{ $comment->created_at->diffForHumans() }} </div> </div> @endforeach @else <div class="bg-white rounded-lg shadow-md p-4"> <p class="text-gray-700">コメントはまだありません。</p> </div> @endif <!-- コメント機能 end -->
- BookController.php
public function show(Book $book) { $user = auth()->user(); $bookmark = Bookmark::where('book_id', $book->id)->where('user_id', auth()->user()->id)->first(); $comments = Comment::where('book_id', $book->id)->orderBy('created_at', 'desc')->get(); return view('book.show', compact('book', 'user', 'bookmark', 'comments')); }
- CommentController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Comment; class CommentController extends Controller { public function store(Request $request) { $inputs = request()->validate([ 'body' => 'required|max:255' ]); $comment = Comment::create([ 'body' => $inputs['body'], 'user_id' => auth()->user()->id, 'book_id' => $request->book_id ]); return back(); } }
- Comment.js
$(function(){ $('.addcomment').click(function(e) { e.preventDefault(); $.ajax({ headers: { "X-CSRF-TOKEN": formData._token }, url: "/book/comment/store", type: "POST", }) .done(function () { //成功時の処理 }) .fail(function() { //失敗時の処理 }) }); });
- web.php
Route::post('/book/comment/store', [App\Http\Controllers\CommentController::class, 'store'])->name('comment.store');
試したこと
私が考えている処理の流れとしては、
show.blade.php
のコメント送信ボタンのclassにaddcomment
を記述し、イベントを発火させる- Comment.jsで記述したurlを読みに行く
- web.phpで記述している該当のルートを通って、コントローラを読みに行く
- コントローラからデータを取得する
- jsに値をレスポンスで返す
- show.blade.phpの表示が変わる
の以上です。
おそらく処理の流れは正しいと思いますし、理解はできているのですがどんなComment.jsでどんなデータを渡して、どのような処理を実装すればいいか悩んでいます。