如果字段为空,如何提示消息,Laravel

时间:2018-02-10 09:00:18

标签: php laravel

所以我有搜索和图像字段的这个字段,在搜索表单中我有一个按钮提交它有效但是当我点击它并且在输入字段中没有输入它显示错误而在图像字段中如果我不添加图像显示错误...我是否通过提示消息解决此问题?让用户知道该字段为空。这是我的搜索代码

building.blade.php

 {!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
        <div class="input-group col-xs-4 col-md-6" >
          <input type="text" name="search" class="form-control" placeholder="Search...">
         <span class="input-group-btn">
           <button type="submit" class="btn btn-info btn-md"><span class="glyphicon glyphicon-search"></span> Search
           </button>
          </span>
            </div>    
             {!! Form::close()!!}

OfficeController.php

 public function index()
{ 
  $search = \Request::get('search');
    $offices = Office::where('name','LIKE','%'.$search.'%')->get(); 
    return view('search',compact('offices','search'));                  
  }

createbuilding.blade.php

{!! Form::label('Building Photo') !!}
  {!! Form::file('buildingpics',array('onchange'=>'previewFile()')) !!}
  <img src="../assets/imageholder.png" id="previewImg" style="height:300px; width:300px;" alt="">
</div>


<div class="form-group">
    <button type="submit" class="btn btn-default btn-md">
          <span class="glyphicon glyphicon-plus"></span> Add Building 
        </button>

  <!--  {!! Form::submit('Create Building',
      array('class'=>'btn btn-primary')) !!} -->

      <a href="{{route('index')}}" class="btn btn-default btn-md"><span class="glyphicon glyphicon-arrow-left"></span> Back</a>
</div>
</div>
{!! Form::close() !!}


<script type="text/javascript">

function previewFile() {
var preview = document.querySelector('#previewImg');
var file    = document.querySelector('input[type=file]').files[0];
var reader  = new FileReader();

reader.addEventListener("load", function () {
  preview.src = reader.result;
}, false);

if (file) {
reader.readAsDataURL(file);
}
}
</script>
@endsection
@section('scripts')
@endsection

2 个答案:

答案 0 :(得分:2)

您可以在控制器中使用laravel validate方法对其进行验证,只需将验证码放入控制器即

$this->validate($request, [
                        'field_name1' => 'required',
                        'field_name2' => 'required',                        
                    ]);

并在您的视图中只弹出错误消息,因此如果用户未填写该字段或该字段为空,则会在请求提交时显示错误消息,以便用户可以轻松了解所需内容。  

   @if ($errors->any())
          <div class="alert alert-danger">
                    <ul>
                    @foreach ($errors->all() as $error)
                     <li>{{ $error }}</li>
                @endforeach
             </ul>
             </div>
             @endif
        <!--error ends-->

希望此代码可以帮助您缩短所需内容。

答案 1 :(得分:0)

你可以使用HTML5这样的必需属性

<input type="text" name="search" class="form-control" placeholder="Search..." required>

您可以使用Laravel的表单请求验证

https://laravel.com/docs/5.5/validation#form-request-validation