I have been having issues with my user signup code of my API I am working on.
I have a UserController that takes the posted data and validates the fields. Then it will send the data to the SignUpUser method in my UserService class that makes a user model and fill in all the given data and send it to the UserRepository that sends it to my DB.
When I dd()
my $password
it's filled but when I dd()
my filled in $user
the field return null... I have no idea why it has not filled it in yet.
Screenshots of my code:
UserController
public function signUpUser(Request $request)
{
$this->validate($request,[
'username' => 'required|regex:/^[(a-zA-Z\s)(0-9\s)]+$/u|min:3',
'email' => 'required|email',
'password' => 'required|min:8',
'displayname' => 'required|regex:/^[(a-zA-Z\s)(0-9\s)]+$/u|min:3',
], [
'min' => 'The :attribute must at least be :min characters long.',
]);
$user = $this->userService->signUpUser(
$request->get('username'),
$request->get('email'),
$request->get('password'),
$request->get('displayname')
);
if($user)
{
//alright! user has been made
$response = ['status' => 'OK', 'message' => "User {$user->username} has successfully been created"];
}
else
{
//something went wrong
$response = ['status' => 'FAIL', 'message' => "Something went wrong or user already exists in DB"];
}
return response()->json($response, 201);
}
UserService
public function signUpUser($userName, $email, $password, $displayName)
{
$password = password_hash($password, PASSWORD_DEFAULT);
$user = $this->userRepository->signUpNewUser($userName, strtolower($email), $password, $displayName);
$user = $this->userRepository->get($user->pk);
//TODO: send user signup mail soon
return $user;
}
UserRepository
public function signUpNewUser($username, $email, $password, $displayName)
{
$user = $this->getModel();
$user->fill(
[
'username' => $username,
'email' => $email,
'password' => $password,
'displayname' => $displayName,
]);
dd($user::all());
$user->save();
return $user;
}
UserModel
class UserModel extends BaseModel
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'displayname'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
}
Add it to $fillable
:
protected $fillable = ['username', 'email', 'displayname', 'password'];
Also, do not keep unencrypted password in the DB, use bcrypt()
:
'password' => bcrypt($password),