前提
laravel でデータベースのデータを更新しようとこころみているのですがデータが更新されません。(PostControlloerのchecked method)
チェックボックスをおすとチェックがデータとして登録されるようにしたいです。
ですがチェックボックス以前に、テキストすら更新することができません。
419error がでるのですが、@csrfはきちんと書いています。
私のコードのどこが間違っているのでしょうか?
おそらくweb.phpのpatchに誤りがあるのではないかと予想しております。
web.php
1<?php 2 3use Illuminate\Support\Facades\Route; 4use App\Http\Controllers\PostController; 5 6Route::get('/', [PostController::class, 'index']) 7 ->name('posts.index'); 8 9Route::get('/posts/{post}', [PostController::class, 'show']) 10 ->name('posts.show') 11 ->where('post', '[0-9]+'); 12 13Route::patch('/posts/{post}/checked', [PostController::class, 'checked']) 14 ->name('posts.checked') 15 ->where('post', '[0-9]+'); 16
PostController.php
1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Models\Post; 7use App\Http\Requests\PostRequest; 8 9class PostController extends Controller 10{ 11 12 public function index() 13 { 14 $posts = Post::latest()->get(); 15 16 return view('index') 17 ->with(['posts' => $posts]); 18 } 19 20 public function show(Post $post) 21 { 22 return view('posts.show') 23 ->with(['post' => $post]); 24 } 25 26 public function create() 27 { 28 return view('posts.create'); 29 } 30 31 public function store(PostRequest $request) 32 { 33 $post = new Post(); 34 35 $post->title = $request->title; 36 37 $post->body = $request->body; 38 39 $post->save(); 40 41 return redirect() 42 ->route('posts.index'); 43 44 } 45 46 public function checked(Post $post) 47 { 48 49 // $post->is_done = !$post->is_done; 50 $post->title = 'hogehoge'; 51 52 $post->save(); 53 54 return redirect() 55 ->route('posts.index'); 56 57 } 58}
index.blade.php
1 <ul> 2 @forelse ($posts as $post) 3 <li class="li-ex" data-id="{{ $post->id }}"> 4 <div class="title-container"> 5 <form method="post" action="{{ route('posts.checked', $post) }}"> 6 @method('PATCH') 7 @csrf 8 <input type="checkbox" {{ $post->is_done ? 'checked' : ''; }}> 9 </form> 10 <a href="{{ route('posts.show', $post) }}" class="{{ $post->is_done ? 'done' : ''; }}"> 11 <span>{{ $post->title }}</span> 12 </a> 13 </div> 14 <form method="post" action="{{ route('posts.destroy', $post) }}"> 15 @method('DELETE') 16 @csrf 17 <span class="delete">[x]</span> 18 </form> 19 </li> 20 @empty 21 <li>No posts yet!</li> 22 @endforelse 23 </ul>
public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('body'); $table->boolean('is_done')->default(false); $table->timestamps(); // created_at, updated_at }); }
laravel8
linuxのdocker で開発しています。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/10/14 21:24
2022/10/14 21:39