Skip to content

4. Register

dungda-0794 edited this page Feb 7, 2023 · 11 revisions

Register use service from package.

Note: Validation & logic register inside service

Make the register function the following:

# App\Http\Controllers\AuthController
public function register(Request $request)
{
    $rules = [];
    $fields = $request->only(['username', 'password', 'email']);
    $fields['name'] = $fields['username'];

    $result = $this->service->register($fields, $rules, function ($entity) {
        return $entity->only(['id', 'email', 'username']);
    });

    return response()->json($result);
}

Flow register inside service package as follows:

1. Validator

public function register(array $params = [], array $rules = [], callable $callback = null): array
{
    if (empty($rules)) {
        $rules = [
            'username' => ['required', 'string', "unique:{$table}," . $this->username()],
            'password' => [
                'required',
                'min:6',
                'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!@#$%]).*$/',
            ],
        ];

        if (isset($params['email'])) {
            $rules['email'] = ['required', 'string', "unique:{$table},email"];
        }
    }
    ...
}

2. Hash Password

public function register(array $params = [], array $rules = [], callable $callback = null): array
{
    ...
    $params[$this->passwd()] = Hash::make($params[$this->passwd()]);
}

3. Insert params to database

public function register(array $params = [], array $rules = [], callable $callback = null): array
{
    ...
    $item = $this->repository->create($params);
}

Clone this wiki locally