在 laravel 中显示重复条目警告

Show duplicate entry warning in laravel

如何在 laravel blade 中向我的视图显示重复输入警告错误。所以当他们输入相同的名字时,当他们保存时会出现警告。

注意:我已经制作了我的架构 $table->string('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.');
}

View-Blade

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

添加 unique 验证,如果失败 returns 则显示一条消息。

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