上次我介紹了登入功能,這次我想介紹如何註冊使用者。註冊要注意的地方在於使用者輸入的帳號密碼格式,格式端看你要定的多嚴謹。laravel有很簡單的驗證格式功能Validation,這東西我會再另出一篇文章講解。
以下是我Todolist專案的原始碼:
public function register(Request $request)
{
$username = $request->username;
$password = $request->password;
$email = $request->email;
# validation check username and password formt
$rules = [
'username' => 'required|max:16|alpha_dash',
'password' => 'required|regex:/[0-9a-zA-Z]{8}/',
'email' => 'required|email',
];
$messages = [
'username.required' => 'username can not null. ',
'username.max' => 'username can not over 16 characters. ',
'username.alpha_dash' => 'username only have alpha-numeric characters, as well as dashes and underscores . ',
'password.regex' => 'password should over 8 characters and only 0-9,a-z,A-Z. ',
'password.required' => 'password should over 8 characters and only 0-9,a-z,A-Z. ',
'email.email' => 'The email must be a valid email address. ',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
$error = $validator->errors()->first();
return response()->json(['status' => false, 'error' => $error], 400);
}
#尋找是否有相同帳號名
$User = Users::where('username', $username)->first();
if (isset($User)) {
return response()->json(['status' => false, 'error' => 'This account already exists'], 400);
}
#尋找是否有相同email
$SameEmail = Users::where('email', $email)->first();
if (isset($SameEmail)) {
return response()->json(['status' => false, 'error' => 'This email already exists'], 400);
}
#密碼加密後加入資料庫
$hash = password_hash($password, PASSWORD_DEFAULT);
$User = Users::create([
'username' => $username, 'password' => $hash,
'remember_token' => 'new user',
'email' => $email,
]);
return response()->json(['status' => true], 201);
}
看起來好像很長,不過6~24行是Validation驗證的部份,可以先跳過,明天我會再出文章講解。
說明:
今天就講到這邊,這次的code看起來雖長,Validation驗證佔一半,驗證後就是簡單的新增user資料而已。明天將會介紹Validation功能,下次見。