我是 Laravel 的新手,我正在从 Laracast 学习它。 这是我的问题,我正在创建一个评论表单,它的 php 代码如下所示:
<section class="col-span-8 col-start-5 mt-10 space-y-6">
<!-- Post form -->
<form method="POST" action="/post/{{ $post->slug }}/comments" class="border border-gray-200 p-6 rounded-xl">
@csrf
<header class="flex items-center">
<img src="https://i.pravatar.cc/100?id={{ auth()->id() }}" alt="" width="40" height="40" class="rounded-full">
<h2 class="ml-3 ">Want to participate?</h2>
</header>
<div class="mt-6">
<textarea class="w-full text-sm focus:outline-none focus:ring"
name="body"
cols="30" rows="10"
placeholder="Quick,think of something to say!" ></textarea>
</div>
<div>
<button type="submit" class="bg-blue-500 text-white uppercase font-semi-bold text-xs py-2 px-10 rounded-2xl hover:bg-blue-600">Post</button>
</div>
这是对应的路线:
Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store']);
控制器:,我怀疑这里可能有问题 'user_id'=> request()->user()->id,我尝试了多种方法来实现这种方法,例如 auth()-> id, Auth::user()->id
<?php
namespace AppHttpControllers;
use AppModelsPost;
class PostCommentsController extends Controller
{
public function store(Post $post){
request()->validate([
'body'=>'required'
]);
$post->comments()->create([
'user_id'=> request()->user()->id,
'body' => request('body')
]);
return back();
}
}
这是评论的迁移表
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->timestamps();
帖子迁移表:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id');
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->timestamp('published_at')->nullable();
});
如果我点击发布按钮,我会收到上述错误,我已尽力解决此问题,但我无法解决。有人可以帮助我我的代码有什么问题吗?我的问题可能看起来很天真,因为我是 stackoverflow 社区的新手
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
将此代码用于控制器
class PostCommentsController extends Controller { public function store(Post $post){ request()->validate([ 'body'=>'required' ]); $post->comments()->create([ 'user_id'=> optional(auth()->user())->id, 'body' => request('body') ]); return back(); } }用户必须登录