doushun1870 2018-04-17 22:35
浏览 53
已采纳

Laravel:MethodNotAllowedHttpException错误尝试喜欢帖子

On my website users are allowed to create posts and like posts. I had a previous error relating to the like system before this and I managed to get that resolved. However with this error I can't figure out what it is. When a user clicks like they are presented with the following error:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

This is my post controller method for the like:

public function postLikePost($post_id){
    $loggedin_user = Auth::user()->id;
    $like_user = Like::where(['user_id' => $loggedin_user, 'post_id' => $post_id])->first();
    if(empty($like_user->user_id)){
        $user_id = Auth::user()->id;
        $post_id = $post_id;

        $like = new Like;

        $like->user_id = $user_id;
        $like->post_id = $post_id;
        $like->save();
        return  redirect()->route('events');

    }else{
        return  redirect()->route('events');
    }

}

This is my Like model:

class Like extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function post(){
        return $this->belongsTo('App\Post');
    }
}

This is my likes migration:

    Schema::create('likes', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id');
        $table->integer('user_id');
        $table->timestamps();
    });

This is my route for the like:

Route::post('/like/{post_id}', 'PostController@postLikePost')->name('like');

This my view for the post:

<section class="row posts">
    @foreach($posts as $post)
        <div class="col-md-2 col-md-offset-3">
            <article class="post">
                <p>{{ $post->body }}</p>
                <div class="info">Posted by {{ $post->user->first_name }} {{ $post->user->last_name }} on {{ $post->created_at }}</div>
                <p>This post has {{ $post->likes()->count() }} likes </p> 
                <a href="{{ route('like', ['post_id' => $post->id]) }}" class="post-item">Like</a>|
            </article>
        </div>
    @endforeach
</section>
  • 写回答

3条回答 默认 最新

  • duandaishi9268 2018-04-17 22:44
    关注

    Either convert the like button to a form with POST request or submit the request via Ajax as a POST request.

    Alternatively, update your route to a GET request (if you want to keep the current blade template as it is):

    Route::get('/like/{post_id}', 'PostController@postLikePost')->name('like');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等