Laravel验证具有唯一字段

时间:2018-09-07 12:43:41

标签: php laravel

我一直在尝试在laravel 5.7中进行唯一验证。下面是我的验证代码。

$this->validate($request, [
        'name' => 'required|unique:permissions,name',
        'slug' => 'required|unique:permissions,slug', 
    ]);

并且html在下面:

<div class='container'> 
{!! Form::open(array('route' => 'permission.save','method'=>'POST')) !!}
<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12">
        <div class="form-group">
            <strong>Name:</strong>
            {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
        </div>
        <div class="form-group">
            <strong>Slug:</strong>
            {!! Form::text('slug', null, array('placeholder' => 'Slug','class' => 'form-control')) !!}
        </div>
        <div class="form-group">
            <strong>Description:</strong>
            {!! Form::textarea('description', null, array('placeholder' => 'Description','class' => 'form-control')) !!}
        </div>
    </div> 
    <div class="col-xs-12 col-sm-12 col-md-12 text-center">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>
{!! Form::close() !!}
</div>

对“名称”的唯一验证工作正常,但对“子弹”无效。我无法理解这真是很奇怪。请提供解决此问题的建议。任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

您需要在唯一验证规则中从数据库表中指定列名

https://laravel.com/docs/5.6/validation#rule-unique

例如,您的slug的列名是:column_slug

$ ./script
I am called with 2 arguments: e f
I am called with 1 arguments: 1
I am called with 2 arguments: 5 g
I am called with 0 arguments:

并确保您为数据库表中的该列设置了唯一键

希望有帮助!