Correction status:Uncorrected
Teacher's comments:
为了让查询数据库出来的数据直接以数组的方式返回
类里面use了Macroable,就可以扩展
在app\providers目录下建立文件
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder as QueryBuilder;
class DBServiceProvider extends ServiceProvider
{
public function boot()
{
QueryBuilder::macro('item',function(){
$res = $this->first();
return $res == null?false:(array)$res;
});
QueryBuilder:: macro('lists',function(){
$res = $this->get()->all();
foreach ($res as $key => $value){
$res[$key] = (array)$value;
}
return $res;
});
}
}
在config目录下的app文件内的providers下
//注册DBServiceProvider
App\Providers\DBServiceProvider::class,
{{}} 支持转义 一段html代码只是被当成普通的字符串输出
{!! !!} 不支持转移 一段html代码可以被正常的解析
使用2次查询,相互调用
<td>{{isset($groups[$admin['group_id']])? $groups[$admin['group_id']]['title']:''}}</td>
使数组下标和gid对应上
$groups = DB::table('xpcms_admin_group')->lists();
$result = [];
foreach ($groups as $key => $value) {
$result[$value['gid']] = $value;
}
在add.blade.php页面使用ajax的post方法提交数据到控制器中的save方法
在表中查重
在控制器admin.php中使用save方法接收数据,插入数据库,返回json结果
<script type="text/javascript">
function admin_save(){
var data = new Object();
data.username = $.trim($('#username').val());
data.group_id = $.trim($('#group_id').val());
data.pwd = $.trim($('#pwd').val());
data.real_name = $.trim($('#real_name').val());
data.status = $('#status').is(':checked')?1:0;
data._token = $('input[name="_token"]').val();
if(username==''){
return layer.alert('用户名不能为空',{icon:2});
}
$.post('/admins/admin/save',data,function(res){
if(res.code>0){
return layer.alert(res.msg,{icon:2});
}
layer.msg(res.msg,{icon:1});
setTimeout(function(){parent.window.location.reload();},1000);
},'json');
}
</script>
public function save(Request $req){
$data['username'] = trim($req->username);
$data['password'] = trim($req->pwd);
$data['group_id'] = (int)$req->group_id;
$data['real_name'] = trim($req->real_name);
$data['status'] = (int)$req->status;
$data['add_time'] = time();
//查重
$admin = DB::table('xpcms_admin')->where('username',$data['username'])->item();
if ($admin) {
return json_encode(array('code'=>1,'msg'=>'该用户已经存在'))
}
DB::table('xpcms_admin')->insert($data);
return json_encode(array('code'=>0,'msg'=>'保存成功'));
}