首页 > 解决方案 > 用户无法在 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 完整性约束违规异常

标签: laravelmigrationpostman

解决方案


你应该试试这个:

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');
    }
}

推荐阅读