douzhang7728 2017-10-03 03:47
浏览 83

在laravel5中点击jquery和validate不起作用

First, I apologize for the bad English. I am now using laravel(version 5.4.24) to create a voting button for site posts.

If I just use <button> in my code, it does not work when I click the vote button on the screen. So, as an alternative, I passed the value using form, but this method does not seem to pass the value of json properly in validation.

The problem occurs in the "here" part, If I delete the "here" part of ArticleController.php and click the button, it doesn't have the up or down value. If I delete "part" and run it, the laravel will show the following error:

SQLSTATE [42S22]: Column not found: 1054 Unknown column '' in 'field list' (SQL: SELECT sum (` `) as aggregate from` votes` where `votes`.`article_id` = 107 and` votes`. `article_id` is not null)

I've been looking for a way for a few days, but I have not found the answer.

Thank you for your help. Thank you.

show.blade.php

//<form ...> </ form> is code that was not in the example, but if I click on 
<button> without it, there is no response on the screen.(No redirects)
<div class="action__article">
<form action="{{ route('videos.vote', $article->id) }}" method="post">
@if ($currentUser)
{!! csrf_field() !!}
<button class="btn__vote__article" data-vote="up" title="{{ trans('forum.comments.like') }}" {{ $voted }}>
<i class="fa fa-heart"></i>
<span>{{ $article->up_count }}</span>
</button>
@endif
</form>
</div>

*index.blade.php

@section('script')
@parent
<script type="text/javascript" charset="utf-8">
$.ajaxSetup({
  headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('vote')
 }
});

$('.btn__vote__article').on('click', function(e) {
  var self = $(this),
    articleId = $article['id'];
  $.ajax({
    type: 'POST',
    url: '/video/' + articleId + '/votes',
    data: {
      vote: self.data('vote')
    }
  }).then(function (data) {
    self.find('span').html(data.value).fadeIn();
    self.attr('disabled', 'disabled');
    self.siblings().attr('disabled', 'disabled');
  });
});
</script>
@endsection

*ArticleController.php

public function vote(Request $request, \App\Article $article)
{
   //"here" - The value received from the form will not pass here and will be redirected to the previous page.
    $this->validate($request, [
        'vote' => 'required|in:up,down',
    ]);

    if ($article->votes()->whereUserId($request->user()->id)->exists()) {
        return response()->json(['error' => 'already_voted'], 409);
    }

    $up = $request->input('vote') == 'up' ? true : false;

    $article->votes()->create([
        'user_id'  => $request->user()->id,
        'up'       => $up,
        'down'     => ! $up,
        'voted_at' => \Carbon\Carbon::now()->toDateTimeString(),
    ]);

    return response()->json([
        'voted' => $request->input('vote'),
        'value' => $article->votes()->sum($request->input('vote')),
    ], 201, [], JSON_PRETTY_PRINT);
}

$article=new App\Article; $request= new App\Http\Requests\ArticlesRequest;

*model

class Vote extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'up',
        'down',
        'voted_at',
    ];

    /**
     * The attributes that should be visible in arrays.
     *
     * @var array
     */
    protected $visible = [
        'user_id',
        'up',
        'down',
    ];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'voted_at',
    ];

    /* Relationships */

    public function articles()
    {
        return $this->belongsTo(Article::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /* Mutators */

    public function setUpAttribute($value)
    {
        $this->attributes['up'] = $value ? 1 : null;
    }

    public function setDownAttribute($value)
    {
        $this->attributes['down'] = $value ? 1 : null;
    }
}

*database

MariaDB [mmdance]> desc votes
    -> ;
+------------+------------------+------+-----+-------------------+----------------------------               -+
| Field      | Type             | Null | Key | Default           | Extra                                      |
+------------+------------------+------+-----+-------------------+----------------------------               -+
| id         | int(10) unsigned | NO   | PRI | NULL              | auto_increment                             |
| user_id    | int(10) unsigned | NO   | MUL | NULL              |                                            |
| article_id | int(10) unsigned | NO   | MUL | NULL              |                                            |
| up         | tinyint(4)       | YES  |     | NULL              |                                            |
| down       | tinyint(4)       | YES  |     | NULL              |                                            |
| voted_at   | timestamp        | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP                |
+------------+------------------+------+-----+-------------------+----------------------------               -+
6 rows in set (0.00 sec)
  • 写回答

2条回答 默认 最新

  • dongnuoyi8833 2017-10-03 04:43
    关注

    It is because you may not have field in database table or you had not added any field in model like below.

    protected $fillable = [
        'user_id',
        'up',
        'down',
        'voted_at',
    ];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题