【问题标题】:How to increment a model attribute count?如何增加模型属性计数?
【发布时间】:2020-02-09 10:08:36
【问题描述】:

我正在尝试使用 Laravel 和 Ajax 制作一个非常简单的博客,每篇博文都有点赞,所以我想通过在控制台中单击和更新数据库来增加点赞数。

这是我的架构:

Schema::create('blogs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->longText('blogContent');
            $table->timestamps();
            $table->integer('likes')->default(8);
        });

这是我的刀片模板和脚本:


@section('content')
  <div class="myFeedContainer col-lg-9 col-md-12 col-sm-12">
      @foreach ($blogs as $blog)
      <div class='blogContainer'>
            <h5 class='blogTitle'>{{$blog->title}}</h5>
            <h6 class='blogDate'>{{$blog->created_at}}</h6>
            <p class='blogContent1' >{{$blog->blogContent}}</p>
            <hr>
            <h6 class='blogLikes' class="clickforlikes" data-id='{{$blog->id}}'>
              {{$blog->likes}} 
              <ion-icon name="heart" ></ion-icon>
            </h6>      

            <br>
        </div>
      @endforeach

      <div id='pagina'>{{ $blogs->render() }}</div>

      <script>
        $('.clickforlikes').on("click", function(){
          $.ajax({
            url:'updateLikes',
            type: 'POST',
            data: {
              blog_id: $(this).attr('data-id')
            },
            success: function (data){
              console.log(data);
            },
            error: function(request, stqtus, error){
              console.log('code: ' + request.status + '\n' + 'msg: '+request.responseText+'\n'+'error: ' + error);
            }
          });
        });

    </script>
  </div>    
@endsection

这是我控制器的功能


  public function updateLikes()
  {
    $blog_Id = $_POST['blog_id'];
    $blog = Blog::find($blog_Id)->increment('likes');
    $blog->save();
  }

这是路由器:

Route::post('/updateLikes', 'BlogsController@updateLikes');

【问题讨论】:

  • 实际错误是什么?
  • $blog_Id = $_POST['blog_id']; 你应该使用请求验证laravel.com/docs/6.x/…
  • 旁注:您不需要调用saveincrement 运行查询来更新记录并同步属性

标签: ajax laravel


【解决方案1】:

您正在尝试以 PHP 方式完成此操作。由于您使用的是框架,因此您应该利用其很酷的功能。在 Laravel 中,你必须这样做:

路由器:

Route::put('updateLikes/{id}', 'BlogsController@updateLikes');

控制器:

public function updateLikes($id) { $blog = Blog::find($id)->increment('likes'); $blog->save(); }

Ajax 调用:

<script> $('.clickforlikes').on("click", function(){ $.ajax({ url:'updateLikes/'+$(this).attr('data-id'), type: 'PUT', success: function (data){ console.log(data); }, error: function(request, stqtus, error){ console.log('code: ' + request.status + '\n' + 'msg: '+request.responseText+'\n'+'error: ' + error); } }); }); </script>

HTTP 方法不同,因为 POST 请求旨在用于在数据库中创建新资源。另一方面,PUT 用于更新资源。您的 ajax 请求将调用附加了博客 id 的路由,控制器将获取 id 作为参数并执行更新。

【讨论】:

  • 我已经完成了你所说的一切,但我从 Ajax 收到了这个错误:PUT 127.0.0.1:8000/updateLikes/undefined 500 (Internal Server Error),我还添加了 和 ajaxSetup
  • 问题可能是$(this).attr('data-id') 没有持有帖子的ID。你确定你得到了正确的价值吗?此外,请确保在您的路线中使用 PUT 而不是 POST
  • 我修复了 500 错误现在我得到了这个 jquery.min.js:2 PUT http://127.0.0.1:8000/updateLikes/7 404 (Not Found) 我什至将 $(this).attr('data-id') 更改为 $(this).data('id') 仍然得到同样的错误
  • 太棒了!所以你现在得到了正确传递的 id 。该 404 错误可能意味着找不到您的路线,因此您可能在定义路线时遇到问题。我认为问题可能是您的路线定义中的额外“/”。尝试修改:Route::put('updateLikes/{id}', 'BlogsController@updateLikes');
  • 太棒了,现在一切正常!关于如何重新加载博客文章以便在不重新加载整个页面的情况下获得更新的任何建议?非常感谢
【解决方案2】:

您正在使用 POST 方法。您可以通过请求服务容器在updateLikes() 方法中接收这些数据。

public function updateLikes(Request $request)
{
    $blog_Id = $request->get('blog_id');
    $blog = Blog::find($blog_Id)->increment('likes');
    // other codes if needed
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多