Model:
<?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Type extends Model { protected $table='type'; protected $primaryKey='tid'; protected $fillable=['tid','typename']; public $timestamps = false; }
为了防止MassAssignmentException错误,需要加上$fillable规定可写字段。
如果在数据库中没有update_at这个字段,我们不做记录更新时间的操作,就加上$timetamps这个属性。
定义路由:
Route::any('typeupdate','IndexController@typeupdate');
操作方法:
public function typeupdate(){ $data=request()->except('_token'); $rules=[ 'typename'=>'required|max:8|unique:type,typename' ]; $msg=[ 'typename.required'=>'类型名不能为空', 'typename.max'=>'可输入最大长度为8', 'typename.unique'=>'该类型名已存在' ]; $validator=Validator::make($data,$rules,$msg); if($ss=$validator->fails()) { return back()->withErrors($validator); }else{ $result=Type::updateOrCreate(array('tid' => $data['tid']), array('typename' => $data['typename'])); if ($result) { return redirect('admin/type'); } else { return back()->with('error', '修改失败'); } } }利用unique:表明,列明可以判断表中是否已存在该字段,如果我们做更改用户名处理时,要保证用户名的唯一性就可以这样用
表单校验规则: 传送
如果在修改的时候想传入修改值的原始值可以使用ajax请求(PS:这里是利用弹窗实现):
先注册路由:
Route::any('edit','IndexController@edit');书写方法controller中:
public function edit(){ $tid=Input::get('tid'); $type=Type::find($tid); echo json_encode($type); }
在视图文件中加上js(为下面的弹窗表单填充值):
<script type="text/javascript"> function jsedit(tid){ //从数据库中根据tid获取记录 $.getJSON( "{{url('admin/edit')}}",{"tid":tid},function(json){ $("#tida").val(json.tid); $("#typenamea").val(json.typename); // alert(json.type); }); } </script>删除按钮:
<a href="#" data-toggle="modal" data-target="#update_dialog" onclick="jsedit({{$v->tid}})"><button type="button" class="btn btn-primary">修改</button></a>
bootstrap弹窗:
<div class="modal fade" id="update_dialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">修改类型名</h4> </div> <div class="modal-body"> <form class="form-inline" method="POST" action="{{url('admin/typeupdate')}}" accept-charset="UTF-8"> <div class="form-group"> <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>"> <input type="hidden" name="tid" id="tida"> <label for="exampleInputName2">类型名称</label> <input type="text" class="form-control" placeholder="类别名称" name="typename" id="typenamea"> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> <button type="submit" class="btn btn-default">Submit</button> </div> </form> </div> </div> </div> </div>