laravel - 用户无法在 laravel 中发表评论
问题描述
路线
Route::group(['middleware'=>['auth:api', \App\Http\Middleware\OnlyRegisteredUsers::class]], function(){
Route::post('commentOnPost','UserController@commentOnPost');
});
创建此迁移后的迁移我运行了 php artisan migrate 命令
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->string('comment');
$table->boolean('hide')->default(0);
$table->timestamps();
});
}
控制器它在控制器中显示错误
public function commentOnPost(Request $request){
$userid = $request->user()->id;
$postid = $request->get('post_id');
$comment = trim($request->get('comment'));
//dump($comment);
$user = User::where(['id'=>$userid, 'hide'=>0])->first();
$post = DB::table('posts')->where(['id'=>$postid])->first();
if($user && $post && $comment){
DB::table('comments')->insert([
'user_id' => $userid,
'post_id' => $postid,
'comment' => $comment,
'hide' => 0,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
return ['message'=>'ok'];
}else{
return abort('403', 'Invalid Request');
}
}
我收到错误 SQL 异常:SQL 完整性约束违规异常
解决方案
你应该试试这个:
public function commentOnPost(Request $request){
$userid = $request->user()->id;
$postid = $request->get('post_id');
$comment = trim($request->get('comment'));
//dump($comment);
$user = User::where(['id'=>$userid, 'hide'=>0])->first();
$post = DB::table('posts')->where(['id'=>$postid,'hide'=>0])->first();
if($user && $post && $comment){
DB::table('comments')->insert([
'user_id' => $user->id,
'post_id' => $post->id,
'comment' => $comment,
'hide' => 0,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
return ['message'=>'ok'];
}else{
return abort('403', 'Invalid Request');
}
}
推荐阅读
- delphi - 检查 Delphi OLE 连接是否仍然存在
- python - 导入自定义模块python时省略子目录
- excel - 在一个表中找到工作编号的坐标,然后在另一个表中找到匹配坐标中的数字并将所有这些加起来
- python - 在 python 上使用 sqlite 创建链接数据库
- python - 如何使用正则表达式从字符串中仅提取三级域?
- flutter - 试图制定一个公式来计算 2 个 dateTimes 之间的时间以在 Flutter 中激活 Dark Theme
- mysql - ZKTime Web 无法连接 MySQL
- google-cloud-platform - 手动安装 GCP VM 模块中的所有内容
- javascript - 无法从 req.session 中检索值
- rest - 我们的微服务设计错了吗?