每次单击递增按钮后如何存储用户ID

时间:2018-09-08 05:53:51

标签: laravel

我制作了一个简单的按钮递增系统,按钮起作用并递增到产品表中。但我想保持记录谁增加按钮。我有一个点击表,其中包含产品ID和客户ID,每次点击后如何存储ID。

public function postClicks( $id){
    // This works increments
    $click = Product::FindorFail($id);
    $click->increment('clicks');
    $click->update();

    // this doesnt work
    $clicksave = new Click;
    $clicksave = $click;
    $clicksave->customer_id = Auth::guard('customer')->user()->id;
    $clicksave->save();
    // this is from the product table and clicks section

}

AJAX

<script>
$('.cardbutton-page').click(function(e){
    e.preventDefault;
    var product = $(this).closest('#cardproduct');
    var product_id = product.attr('data-product-id');
    registerProductClicked(product_id);
});

function registerProductClicked(product_id){
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });
    $.ajax({
        type: 'post',
        dataType: 'JSON',
        url: '/product/'+ product_id + '/click',
        error: function (xhr, ajaxOptions, thrownError) {
         console.log(xhr.status);
         console.log(JSON.stringify(xhr.responseText));
     }
 });

}

</script>

Route::post('/product/{id}/click', 'ClicksController@postClicks');

1 个答案:

答案 0 :(得分:2)

请确保在您的Click模型上将customer_id设置为可填充。

Click extends Model
{

 protected $fillable = ['customer_id'];

}

并尝试Click::create(['customer_id' => Auth::guard('customer')->user()->id]);