【问题标题】:user is not able to post a comment in laravel用户无法在 laravel 中发表评论
【发布时间】:2018-10-08 14:59:57
【问题描述】:

路线

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 完整性约束 违规异常

【问题讨论】:

    标签: laravel migration postman


    【解决方案1】:

    你应该试试这个:

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

    【讨论】:

      【解决方案2】:

      我已经在我的系统上测试了这段代码,只是有一个小错误

      $post = DB::table('posts')->where(['id'=>$postid])->first();
      

      应该是

      $post = DB::table('posts')->where(['id'=>$postid,'hide'=>0])->first();
      

      【讨论】:

      • 您忘记添加隐藏栏
      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 2019-08-26
      • 2013-07-10
      相关资源
      最近更新 更多