在laravel中显示重复的条目警告

时间:2018-01-30 01:54:50

标签: php laravel blade

如何在laravel刀片中向我的视图显示重复输入警告错误。因此,当他们键入相同名称时,警告会在保存时显示。

注意:我已经制作了我的Schema $ table->字符串(' studentname') - > unique();;

控制器

public function store(Request $request)
{
    $this->validate($request, [
        'studentname'=>'required|max:50',
    ]);   
    $students = new Student();
    $students->studentname = $request->studentname;
    $students->address = $request->address;
    $students->religion = $request->religion;
    $students->save();

    return redirect()->route('students.index')
        ->with('flash_message', 'Success.');
}

查看-刀片



<div class="container">
  <h1 class="well">Registration Form</h1>
  <div class="col-lg-12 well">
    <div class="row">
      <form action="{{route('students.store')}}" method="POST">
        {{csrf_field()}}
        <div class="col-sm-12">
          <h3>CHILD'S INFORMATION</h3>
          <hr>
          <div class="row">
            <div class="col-sm-4 form-group">
              <label>FULLNAME</label>
              <input type="text" name="studentname" value="" placeholder="Enter FULLNAME.." class="form-control" required>
            </div>		
            <div class="col-sm-4 form-group">
              <label>RELIGION</label>
              <input type="text" name="religion" value="" placeholder="Enter RELIGION.." class="form-control">
            </div>
            <div class="col-sm-4 form-group">
              <label>ADDRESS</label>
              <input type="text" name="address" value="" placeholder="Enter ADDRESS.." class="form-control">
            </div>
            <div>				
              <button type="submit" class="btn btn-default">SUBMIT</button>
            </div>
          </div>
        </div>
      </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

添加unique验证,如果失败则返回消息。

$this->validate($request, [
    'studentname'=>'required|max:50|unique:table_name,studentname',
]);

然后,在 blade 模板中,执行此操作。

<div class="col-sm-4 form-group {{ $errors->get('studentname') ? 'has-error' : '' }}">
  <label>FULLNAME</label>
  <input type="text" name="studentname" value="" placeholder="Enter FULLNAME.." class="form-control" required>
  @foreach($errors->get('studentname') as $error)
    <span class="help-block">{{ $error }}</span>
  @endforeach
</div>