Skip to content
关注公众号,获取新课通知

增加会员


控制器 app/controller/admin/User.php

php
public function save(Request $request)
{
	$param = $request->param();
    $user = $this->M->checkUnique('username','用户名');
    if(!array_key_exists('password',$param)){
    	return ApiException('密码不能为空');
    }
	$this->M->checkUnique('phone','手机');
	$this->M->checkUnique('email','邮箱');
    return showSuccess($this->M->save($request->param()));
}

模型 app/model/User.php

php
// 获取当前用户的资料信息
   public function userInfo(){
       return $this->hasOne('UserInfo');
   }

// 密码自动加密
   public function setPasswordAttr($value,$data){
       return password_hash($value,PASSWORD_DEFAULT);
   }

// 验证唯一性
public function checkUnique($key,$msg){
	$data = request()->param($key);
   	// 唯一性验证
   	$user = $this->where($key,$data)->find();
   	if($user){
   		ApiException( $msg.'已经存在');
   	}
	return $user;
}

// 创建之后
   public static function onAfterInsert($user){
       // 创建会员资料
       UserInfo::create([
           'user_id'=>$user->id
       ]);
   }

验证器 app/validate/admin/User.php

php
	// 验证规则
	protected $rule = [
        'status'=>'require|in:0,1',
        'username'=>'require|NotEmpty|length:4,25',
        'password'=>'NotEmpty|min:6',
        'avatar'=>'url',
        'nickname'=>'chsDash',
		'phone'=>'mobile',
		'email'=>'email',
		'user_level_id|会员等级'=>'require|integer|>=:0|isExist:UserLevel,false',
    ];

protected $scene = [
    // ...
    'save'=>['username','password','nickname','phone','email','user_level_id','avatar'],
];

路由 router/admin.php

php
Route::post('user','admin.User/save');