
Thêm tính năng Ban/Suspend thành viên cho Laravel
Laravel Auth có rất nhiều tính năng, nhưng nó không bao gồm tính năng Ban/Suspend người dùng. Trong bài viết này mình sẽ hướng dẫn các bạn làm thêm tính năng này bằng cách sử dụng Middleware của Laravel
Bước 1: Tạo thêm column banned_until vào table user
Các bạn chạy lệnh sau:
php artisan make:migration add_banned_until_to_users_table
Sửa nội dung file migration mới được tạo ra thành như sau:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('banned_until')->nullable();
});
}
Tiếp theo các bạn chạy lệnh sau để tạo column
php artisan migrate
- Mở file app/User.php và sửa lại giống như sau:
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password', 'banned_until'
];
protected $dates = [
'banned_until'
];
}
Bước 2: Tạo Middleware CheckBanned
Để tạo Middleware các bạn chạy lệnh sau:
php artisan make:middleware CheckBanned
Sửa file app/Http/Middleware/CheckBanned.php:
class CheckBanned
{
public function handle($request, Closure $next)
{
if (auth()->check() && auth()->user()->banned_until && now()->lessThan(auth()->user()->banned_until)) {
$banned_days = now()->diffInDays(auth()->user()->banned_until);
auth()->logout();
if ($banned_days > 14) {
$message = 'Your account has been suspended. Please contact administrator.';
} else {
$message = 'Your account has been suspended for '.$banned_days.' '.str_plural('day', $banned_days).'. Please contact administrator.';
}
return redirect()->route('login')->withMessage($message);
}
return $next($request);
}
}
Bước 3: Sử dụng Middleware và hiển thị thông báo
Thêm vào file app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
// ... other middleware classes
\App\Http\Middleware\CheckBanned::class,
],
Mở file resources/views/auth/login.blade.php và thêm code hiển thị thông báo
<div class="card-body">
@if (session('message'))
<div class="alert alert-danger">{{ session('message') }}</div>
@endif
<form method="POST" action="{{ route('login') }}">
Và đây là kết quả
Các bạn copy bài viết sang website khác, vui lòng ghi nguồn VietLaravel.com. Xin cảm ơn.
Post Comment