Ở bài trước, chúng ta đã tìm hiểu cách đăng nhập (Login) hoạt động trong Laravel.
Trong bài này, chúng ta sẽ tìm hiểu Register – chức năng tạo tài khoản mới cho người dùng.
Laravel Breeze đã tạo sẵn toàn bộ quy trình đăng ký, nhưng hiểu cách nó hoạt động sẽ giúp bạn dễ dàng tùy biến theo yêu cầu của từng dự án.
Register là gì?
Register là quá trình tạo một tài khoản mới.
Thông thường người dùng sẽ nhập:
Họ tên
Email
Mật khẩu
Xác nhận mật khẩu
Sau khi đăng ký thành công, Laravel sẽ:
Kiểm tra dữ liệu.
Mã hóa mật khẩu.
Lưu User vào Database.
Đăng nhập tự động.
Chuyển tới Dashboard.
Quy trình Register
Người dùng
│
▼
Điền Form Register
│
▼
Validation
│
▼
Kiểm tra Email
│
▼
Hash Password
│
▼
Lưu User
│
▼
Đăng nhập tự động
│
▼
Dashboard
Đây là quy trình mặc định của Laravel Breeze.
Form Register
Laravel Breeze đã tạo sẵn Form:
//resources/views/auth/register.blade.php
<form
method="POST"
action="{{ route('register') }}">
@csrf
<input
type="text"
name="name">
<input
type="email"
name="email">
<input
type="password"
name="password">
<input
type="password"
name="password_confirmation">
<button>
Đăng ký
</button>
</form>
Validation
Laravel kiểm tra dữ liệu trước khi tạo User.
Ví dụ:
//app/Http/Controllers/Auth/RegisteredUserController.php
$request->validate([
'name' =>
'required|string|max:255',
'email' =>
'required|email|unique:users,email',
'password' =>
'required|confirmed|min:8',
]);
Ý nghĩa:
required: bắt buộc nhập.unique: Email không được trùng.confirmed: phải có trườngpassword_confirmationvà hai giá trị phải giống nhau.min:8: mật khẩu tối thiểu 8 ký tự.
Tạo User
Sau khi Validation thành công:
//app/Http/Controllers/Auth/RegisteredUserController.php
//store function
use Illuminate\Support\Facades\Hash;
$user = User::create([
'name' =>
$request->name,
'email' =>
$request->email,
'country_id' =>
$request->country_id,
'password' =>
Hash::make(
$request->password
),
]);
Hash::make() sẽ băm mật khẩu trước khi lưu vào cơ sở dữ liệu.
Đăng nhập tự động
Ngay sau khi tạo User:
Auth::login($user);
Người dùng không cần nhập lại Email và Password.
Laravel sẽ tạo Session và chuyển sang trang tiếp theo.
Tạo Profile tự động
Ở các bài trước, chúng ta đã tạo bảng profiles và quan hệ One To One với users.
Cho phép ghi 02 trường phone và address trong bảng profiles
class Profile extends Model
{
protected $fillable = [
'phone',
'address',
];
...
Sau khi tạo User, có thể tạo luôn Profile:
//đặt trước dòng event(new Registered($user));
$user->profile()->create([
'phone' => $request->phone,
'address' => $request->address,
]);
Khi đó, mỗi User mới đều có sẵn một Profile để cập nhật sau này.
Chèn thêm Phone và Address sau phần Email (hoặc trước Password). Mã theo đúng style của Breeze:
<!-- Phone --> <div class="mt-4"> <x-input-label for="phone" :value="__('Phone')" /> <x-text-input id="phone" class="block mt-1 w-full" type="text" name="phone" :value="old('phone')" required autocomplete="tel" /> <x-input-error :messages="$errors->get('phone')" class="mt-2" /> </div> <!-- Address --> <div class="mt-4"> <x-input-label for="address" :value="__('Address')" /> <x-text-input id="address" class="block mt-1 w-full" type="text" name="address" :value="old('address')" required autocomplete="street-address" /> <x-input-error :messages="$errors->get('address')" class="mt-2" /> </div>
Validation:
'phone' => ['required', 'string', 'max:20'],
'address' => ['required', 'string', 'max:255'],Gán Country mặc định
Giả sử bảng countries đã có dữ liệu từ Seeder.
Có thể gán quốc gia mặc định:
$user->update([
'country_id' => 1,
]);
Hoặc lấy theo dữ liệu người dùng chọn từ Form:
'country_id' =>
$request->country_id
Việc này giúp mở rộng chức năng đăng ký cho các dự án đa quốc gia.
Chọn Country khi Register
Blade:
<!-- Country -->
<div class="mt-4">
<x-input-label for="country_id" :value="__('Country')" />
<select
id="country_id"
name="country_id"
class="block mt-1 w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
required>
<option value="">-- Select Country --</option>
@foreach($countries as $country)
<option
value="{{ $country->id }}"
{{ old('country_id') == $country->id ? 'selected' : '' }}>
{{ $country->name }}
</option>
@endforeach
</select>
<x-input-error :messages="$errors->get('country_id')" class="mt-2" />
</div>
Validation:
'country_id' =>
'required|exists:countries,id'
Nhờ đó người dùng chỉ có thể chọn Country hợp lệ.
trong RegisteredUserController cần truyền biến.
Ví dụ:
use App\Models\Country; public function create(): View { $countries = Country::all(); return view('auth.register', compact('countries')); }
Kiểm tra Email trùng
Laravel sẽ tự động báo lỗi nếu:
Email đã tồn tại.
Do Rule:
unique:users,email
giúp ngăn tạo nhiều tài khoản với cùng một Email.
Hiển thị lỗi
Blade:
<input
type="email"
name="email"
value="{{ old('email') }}">
Thông báo:
@error('email')
<div class="text-danger">
{{ $message }}
</div>
@enderror
Nếu Validation thất bại, dữ liệu đã nhập vẫn được giữ lại nhờ old().
Sau khi Register
Người dùng có thể:
Tạo Post.
Cập nhật Profile.
Upload ảnh.
Quản lý bài viết của mình.
Nhờ auth()->id(), mọi dữ liệu sẽ gắn đúng với tài khoản vừa đăng ký.
Quy trình mở rộng
Trong dự án thực tế, sau khi Register có thể tự động:
Tạo User
│
▼
Tạo Profile
│
▼
Gán Country
│
▼
Đăng nhập
│
▼
Dashboard
Đây là cách triển khai phổ biến trong các hệ thống quản lý hiện đại.
Tổng kết
Trong bài này chúng ta đã học:
Register là gì.
Quy trình tạo tài khoản.
Validation.
Hash::make().Auth::login().Tạo Profile tự động.
Gán Country.
Kiểm tra Email trùng.
Hiển thị lỗi Validation.
Đăng ký tài khoản là bước khởi đầu để người dùng tham gia và sử dụng đầy đủ các chức năng của ứng dụng Laravel.
Bài tập
Đăng ký một tài khoản mới.
Kiểm tra Email không được trùng.
Kiểm tra Password tối thiểu 8 ký tự.
Tạo Profile tự động sau khi Register.
Thêm trường chọn Country vào Form Register.
Gán
country_idcho User.Kiểm tra User và Profile đã được tạo trong cơ sở dữ liệu.
Bài tiếp theo
Ở Bài 24, chúng ta sẽ tìm hiểu Middleware, cơ chế giúp bảo vệ các Route và chỉ cho phép người dùng đã đăng nhập truy cập vào những khu vực như Dashboard, quản lý bài viết hoặc trang quản trị.
x1




Không có nhận xét nào:
Đăng nhận xét