Để tạo chức năng
Laravel sẽ tự động thực hiện dùm bạn một số bước ban đầu:
1. Tự động đăng ký các
Danh sách các
2. Tự động tạo các
3. Tự động tạo các
laravel_default_home_auth-1024x774
laravel_default_auth_reset_password-1024x239
laravel_default_auth_login-1024x317
1. Hiệu chỉnh cấu hình sử dụng model
2. Tạo mới file
3. Đăng ký sử dụng
4. Hiệu chỉnh
7. Hiệu chỉnh model NhanVien
Xác thực tài khoản (Đăng nhập/Đăng xuất; Đăng ký) Auth nhanh. Chúng ta sẽ sử dụng các công cụ có sẵn của Laravel.
Step 1: thực thi câu lệnh
shellscript
1php artisan make:auth1. Tự động đăng ký các route dành cho việc Xác thực tài khoản trong file routes\web.php
php
1// Gọi hàm đăng ký các route dành cho Quản lý Xác thực tài khoản (Đăng nhập, Đăng xuất, Đăng ký)2// các route trong file `vendor\laravel\framework\src\Illuminate\Routing\Router.php`, hàm auth()3Auth::routes();route Laravel đã đăng ký dùm bạn
shellscript
1+--------+----------+-------------------------+-----------------------+------------------------------------------------------------------------+--------------+2| Domain | Method | URI | Name | Action | Middleware |3+--------+----------+-------------------------+-----------------------+------------------------------------------------------------------------+--------------+4| | GET|HEAD | / | | Closure | web |5| | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController@showLoginForm | web,guest |6| | POST | login | | App\Http\Controllers\Auth\LoginController@login | web,guest |7| | POST | logout | logout | App\Http\Controllers\Auth\LoginController@logout | web |8| | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail | web,guest |9| | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest |10| | POST | password/reset | | App\Http\Controllers\Auth\ResetPasswordController@reset | web,guest |11| | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController@showResetForm | web,guest |12| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController@showRegistrationForm | web,guest |13| | POST | register | | App\Http\Controllers\Auth\RegisterController@register | web,guest |14+--------+----------+-------------------------+-----------------------+------------------------------------------------------------------------+--------------+2. Tự động tạo các controller để quản lý xử lý logic/nghiệp vụ cho việc Xác thực tài khoản (Auth)
app\Http\Controllers\Auth\ForgotPasswordController.php: quản lý các logic/nghiệp vụ cho việc xử lý Quên mật khẩuapp\Http\Controllers\Auth\LoginController.php: quản lý các logic/nghiệp vụ cho việc Đăng nhậpapp\Http\Controllers\Auth\RegisterController.php: quản lý các logic/nghiệp vụ cho việc Đăng kýapp\Http\Controllers\Auth\ResetPasswordController.php: quản lý các logic/nghiệp vụ cho việc reset Mật khẩu
3. Tự động tạo các view tương ứng với chức năng Xác thực tài khoản (Auth)
resources\views\layouts\app.blade.php: giao diện layout chủ (master) cho các chức năng Xác thực tài khoản (Auth)
resources\views\auth\passwords\email.blade.php: giao diện chức năng Quên mật khẩu (kích hoạt bằng email)resources\views\auth\passwords\reset.blade.php: giao diện chức năng Quên mật khẩu (gởi mật khẩu mới thông qua email)
resources\views\auth\login.blade.php: giao diện chức năng Đăng nhập
resources\views\auth\register.blade.php: giao diện chức năng Đăng ký
laravel_default_auth_register-1024x364 Step 2: tùy chỉnh (customize) chức năng Xác thực tài khoản (Auth) mặc định của Laravel theo ý thích
1. Hiệu chỉnh cấu hình sử dụng model Nhanvien để quản lý việc Xác thực tài khoản
- Hiệu chỉnh file:
config\auth.php - Tìm và thay thế đoạn code sau:
php
1/*2 |--------------------------------------------------------------------------3 | User Providers4 |--------------------------------------------------------------------------5 |6 | All authentication drivers have a user provider. This defines how the7 | users are actually retrieved out of your database or other storage8 | mechanisms used by this application to persist your user's data.9 |10 | If you have multiple user tables or models you may configure multiple11 | sources which represent each model / table. These sources may then12 | be assigned to any extra authentication guards you have defined.13 |14 | Supported: "database", "eloquent"15 |16 */17 18 'providers' => [19 // Không sử dụng model `User` (mặc định của Laravel)20 // 'users' => [21 // 'driver' => 'eloquent',22 // 'model' => App\User::class,23 // ],24 25 // Thay thế việc Xác thực tài khoản bằng model `Nhanvien`26 'users' => [27 'driver' => 'custom',28 'model' => App\Nhanvien::class,29 ],30 31 // 'users' => [32 // 'driver' => 'database',33 // 'table' => 'users',34 // ],35 ],- Sau khi hiệu chỉnh
config, cần chạy câu lệnh để clear cache config, đảm bảo cho việc đang sử dụng config mới nhất
shellscript
1php artisan config:clear2. Tạo mới file app\Http\Controllers\Auth\CustomUserProvider.php để custom việc xác thực tài khoản
- Tạo file
app\Http\Controllers\Auth\CustomUserProvider.php - Nội dung:
php
1<?php2 3namespace App\Auth;4 5use Illuminate\Support\Str;6use Illuminate\Auth\EloquentUserProvider;7use Illuminate\Contracts\Auth\UserProvider as UserProviderContract;8use Illuminate\Contracts\Auth\Authenticatable as UserContract;9 10class CustomUserProvider extends EloquentUserProvider implements UserProviderContract11{12 /**13 * Retrieve a user by their unique identifier.14 *15 * @param mixed $identifier16 * @return \Illuminate\Contracts\Auth\Authenticatable|null17 */18 public function retrieveById($identifier)19 {20 $model = $this->createModel();21 22 return $model->newQuery()23 ->where($model->getAuthIdentifierName(), $identifier)24 ->first();25 }26 27 /**28 * Retrieve a user by their unique identifier and "remember me" token.29 *30 * @param mixed $identifier31 * @param string $token32 * @return \Illuminate\Contracts\Auth\Authenticatable|null33 */34 public function retrieveByToken($identifier, $token)35 {36 $model = $this->createModel();37 38 $model = $model->where($model->getAuthIdentifierName(), $identifier)->first();39 40 if (! $model) {41 return null;42 }43 44 $rememberToken = $model->getRememberToken();45 46 return $rememberToken && hash_equals($rememberToken, $token) ? $model : null;47 }48 49 /**50 * Update the "remember me" token for the given user in storage.51 *52 * @param \Illuminate\Contracts\Auth\Authenticatable $user53 * @param string $token54 * @return void55 */56 public function updateRememberToken(UserContract $user, $token)57 {58 $user->setRememberToken($token);59 60 $timestamps = $user->timestamps;61 62 $user->timestamps = false;63 64 $user->save();65 66 $user->timestamps = $timestamps;67 }68 69 /**70 * Retrieve a user by the given credentials.71 *72 * @param array $credentials73 * @return \Illuminate\Contracts\Auth\Authenticatable|null74 */75 public function retrieveByCredentials(array $credentials)76 {77 if (empty($credentials) ||78 (count($credentials) === 1 &&79 array_key_exists('nv_matKhau', $credentials))) {80 return;81 }82 83 // First we will add each credential element to the query as a where clause.84 // Then we can execute the query and, if we found a user, return it in a85 // Eloquent User "model" that will be utilized by the Guard instances.86 $query = $this->createModel()->newQuery();87 88 89 foreach ($credentials as $key => $value) {90 if (! Str::contains($key, 'nv_matKhau')) {91 $query->where($key, $value);92 }93 }94 95 return $query->first();96 }97 98 /**99 * Validate a user against the given credentials.100 *101 * @param \Illuminate\Contracts\Auth\Authenticatable $user102 * @param array $credentials103 * @return bool104 */105 public function validateCredentials(UserContract $user, array $credentials)106 {107 $plain = $credentials['nv_matKhau'];108 109 return $this->hasher->check($plain, $user->getAuthPassword());110 }111}3. Đăng ký sử dụng CustomUserProvider để đăng nhập
- Hiệu chỉnh file `app\Providers\AuthServiceProvider.php`
php
1<?php2 3namespace App\Providers;4 5use Illuminate\Support\Facades\Gate;6use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;7use App\Auth\CustomUserProvider;8 9class AuthServiceProvider extends ServiceProvider10{11 /**12 * The policy mappings for the application.13 *14 * @var array15 */16 protected $policies = [17 'App\Model' => 'App\Policies\ModelPolicy',18 ];19 20 /**21 * Register any authentication / authorization services.22 *23 * @return void24 */25 public function boot()26 {27 $this->registerPolicies();28 29 // Sử dụng CustomUserProvider để xác thực tài khoản30 $this->app->auth->provider('custom', function ($app, array $config) {31 return new CustomUserProvider($app['hash'], $config['model']);32 });33 }34}4. Hiệu chỉnh LoginController
php
1<?php2 3namespace App\Http\Controllers\Auth;4 5use App\Http\Controllers\Controller;6use Illuminate\Foundation\Auth\AuthenticatesUsers;7use Illuminate\Http\Request;8 9class LoginController extends Controller10{11 /*12 |--------------------------------------------------------------------------13 | Login Controller14 |--------------------------------------------------------------------------15 |16 | This controller handles authenticating users for the application and17 | redirecting them to your home screen. The controller uses a trait18 | to conveniently provide its functionality to your applications.19 |20 */21 22 use AuthenticatesUsers;23 24 /**25 * Where to redirect users after login.26 *27 * @var string28 */29 protected $redirectTo = '/admin'; //Sau khi đăng nhập thành công, sẽ tự động trỏ về trang /admin/30 31 /**32 * Create a new controller instance.33 *34 * @return void35 */36 public function __construct()37 {38 $this->middleware('guest')->except('logout');39 }40 41 /**42 * Hàm trả về tên cột dùng để tìm `Tên đăng nhập`.43 * Thông thường là cột `username` hoặc cột `email`44 */45 public function username(){46 return 'nv_taiKhoan';47 } 48 49 /**50 * Get the needed authorization credentials from the request.51 *52 * @param \Illuminate\Http\Request $request53 * @return array54 */55 protected function credentials(Request $request)56 {57 $cred = $request->only($this->username(), 'nv_matKhau');58 return $cred;59 }60 61 /**62 * Hàm dùng để Kiểm tra tính hợp lệ của dữ liệu (VALIDATE) khi Xác thực tài khoản63 */64 protected function validateLogin(Request $request)65 {66 $this->validate($request, [67 $this->username() => 'required|string', // tên tài khoản bắt buộc nhập68 'nv_matKhau' => 'required|string', // mật khẩu bắt buộc nhập69 ]);70 }71 72 /**73 * Attempt to log the user into the application.74 *75 * @param \Illuminate\Http\Request $request76 * @return bool77 */78 protected function attemptLogin(Request $request)79 {80 return $this->guard()->attempt(81 $this->credentials($request), $request->filled('remember')82 );83 }84}5. Thêm mới cột `nv_ghinhodangnhap` sử dụng migration
- Thực hiện câu lệnh
shellscript
1php artisan make:migration alter_add_column_v1_to_nhanvien_table --table=cusc_nhanvien- Code file `database/migrations/2019_07_05_161859_alter_add_column_v1_to_nhanvien_table.php`
php
1<?php2use Illuminate\Support\Facades\Schema;3use Illuminate\Database\Schema\Blueprint;4use Illuminate\Database\Migrations\Migration;5class AlterAddColumnV1ToNhanvienTable extends Migration6{7 /**8 * Run the migrations.9 *10 * @return void11 */12 public function up()13 {14 Schema::table('cusc_nhanvien', function (Blueprint $table) {15 $table->string('nv_ghinhodangnhap')->nullable();16 });17 }18 /**19 * Reverse the migrations.20 *21 * @return void22 */23 public function down()24 {25 Schema::table('cusc_nhanvien', function (Blueprint $table) {26 $table->string('nv_ghinhodangnhap');27 });28 }29}- Thực thi
php artisan migrateđể cập nhật cấu trúc database mới.
- Hiệu chỉnh file `resources/views/auth/login.blade.php`
php
1@extends('layouts.app')2 3@section('content')4<div class="container">5 <div class="row">6 <div class="col-md-8 col-md-offset-2">7 <div class="panel panel-default">8 <div class="panel-heading">Login</div>9 10 <div class="panel-body">11 <form class="form-horizontal" method="POST" action="{{ route('login') }}">12 {{ csrf_field() }}13 14 <div class="form-group{{ $errors->has('nv_taiKhoan') ? ' has-error' : '' }}">15 <label for="nv_taiKhoan" class="col-md-4 control-label">Tên tài khoản</label>16 17 <div class="col-md-6">18 <input id="nv_taiKhoan" type="text" class="form-control" name="nv_taiKhoan" value="{{ old('nv_taiKhoan') }}" required autofocus>19 20 @if ($errors->has('nv_taiKhoan'))21 <span class="help-block">22 <strong>{{ $errors->first('nv_taiKhoan') }}</strong>23 </span>24 @endif25 </div>26 </div>27 28 <div class="form-group{{ $errors->has('nv_matKhau') ? ' has-error' : '' }}">29 <label for="nv_matKhau" class="col-md-4 control-label">Mật khẩu</label>30 31 <div class="col-md-6">32 <input id="nv_matKhau" type="password" class="form-control" name="nv_matKhau" required>33 34 @if ($errors->has('nv_matKhau'))35 <span class="help-block">36 <strong>{{ $errors->first('nv_matKhau') }}</strong>37 </span>38 @endif39 </div>40 </div>41 42 <div class="form-group">43 <div class="col-md-6 col-md-offset-4">44 <div class="checkbox">45 <label>46 <input type="checkbox" name="nv_ghinhodangnhap" {{ old('nv_ghinhodangnhap') ? 'checked' : '' }}> Ghi nhớ đăng nhập47 </label>48 </div>49 </div>50 </div>51 52 <div class="form-group">53 <div class="col-md-8 col-md-offset-4">54 <button type="submit" class="btn btn-primary">55 Đăng nhập56 </button>57 58 <a class="btn btn-link" href="{{ route('password.request') }}">59 Quên mật khẩu?60 </a>61 </div>62 </div>63 </form>64 </div>65 </div>66 </div>67 </div>68</div>69@endsectionphp
1<?php2namespace App;3use Illuminate\Database\Eloquent\Model;4use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;5class Nhanvien extends Model implements6 AuthenticatableContract7{8 const CREATED_AT = 'nv_taoMoi';9 const UPDATED_AT = 'nv_capNhat';10 protected $table = 'cusc_nhanvien';11 protected $fillable = ['nv_taiKhoan', 'nv_matKhau', 'nv_hoTen', 'nv_gioiTinh', 'nv_email', 'nv_ngaySinh', 'nv_diaChi', 'nv_dienThoai', 'nv_taoMoi', 'nv_capNhat', 'nv_trangThai', 'q_ma'];12 protected $guarded = ['nv_ma'];13 protected $primaryKey = 'nv_ma';14 protected $dates = ['nv_ngaySinh', 'nv_taoMoi', 'nv_capNhat'];15 protected $dateFormat = 'Y-m-d H:i:s';16 /**17 * Tên cột 'Ghi nhớ đăng nhập'18 * The column name of the "remember me" token.19 *20 * @var string21 */22 protected $rememberTokenName = 'nv_ghinhodangnhap';23 /**24 * Get the name of the unique identifier for the user.25 *26 * @return string27 */28 public function getAuthIdentifierName()29 {30 return $this->getKeyName();31 }32 /**33 * Get the unique identifier for the user.34 *35 * @return mixed36 */37 public function getAuthIdentifier()38 {39 return $this->{$this->getAuthIdentifierName()};40 }41 /**42 * Hàm trả về tên cột dùng để tim `Mật khẩu`43 * Get the password for the user.44 *45 * @return string46 */47 public function getAuthPassword()48 {49 return $this->nv_matKhau;50 }51 /**52 * Hàm dùng để trả về giá trị của cột "nv_ghinhodangnhap" session.53 * Get the token value for the "remember me" session.54 *55 * @return string|null56 */57 public function getRememberToken()58 {59 if (! empty($this->getRememberTokenName())) {60 return (string) $this->{$this->getRememberTokenName()};61 }62 }63 /**64 * Hàm dùng để set giá trị cho cột "nv_ghinhodangnhap" session.65 * Set the token value for the "remember me" session.66 *67 * @param string $value68 * @return void69 */70 public function setRememberToken($value)71 {72 if (! empty($this->getRememberTokenName())) {73 $this->{$this->getRememberTokenName()} = $value;74 }75 }76 /**77 * Hàm trả về tên cột dùng để chứa REMEMBER TOKEN78 * Get the column name for the "remember me" token.79 *80 * @return string81 */82 public function getRememberTokenName()83 {84 return $this->rememberTokenName;85 }86 public function setPasswordAttribute($value)87 {88 $this->attributes['nv_matKhau'] = bcrypt($value);89 }90}
