简体   繁体   中英

Laravel validation with unique fields

I have been trying unique validation in laravel 5.7. Below is my code for validation.

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

And the html is below:

<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>

Unique validation for 'name' is working fine but it is not working for 'slug'. It's really weird i can't get it. Please provide suggestions to fix this issue. Any help would be great.

You need to specify column name from database table in unique validation rule

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

for example your column name for slug is : column_slug

$this->validate($request, [
    'name' => 'required|unique:permissions,name',
    'slug' => 'required|unique:permissions,column_slug',   // column_slug  may be different in your case
]);

And ensure that you have set unique key for that column in database table

Hope it helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM