Quay lại

Làm chức năng đăng nhập trong Laravel Chuyên mục PHP và Laravel    2023-02-08    6 Lượt xem    3 Lượt thích    comment-3 Created with Sketch Beta. 0 Bình luận

Bước 1: Tạo cơ sở dữ liệu và migration

Trước tiên, hãy chắc chắn rằng bạn đã cấu hình kết nối cơ sở dữ liệu trong file .env. Sau đó, tạo migration cho bảng users nếu bạn chưa có:
php artisan make:migration create_users_table
Trong file migration (database/migrations/YYYY_MM_DD_create_users_table.php):
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->unsignedTinyInteger('role_id')->default(2); // 1 for admin, 2 for regular user
        $table->timestamps();
    });
}

Bước 2: Tạo model User

Trong file app/Models/User.php:
namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function isAdmin()
    {
        return $this->role_id === 1;
    }
}

Bước 3: Tạo Auth Controller

Tạo controller cho việc xử lý đăng nhập:
php artisan make:controller AuthController
Trong file app/Http/Controllers/AuthController.php:
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            if ($user->isAdmin()) {
                return redirect()->route('admin.dashboard');
            } else {
                Auth::logout();
                return redirect()->route('login')->withErrors(['email' => 'You do not have admin access.']);
            }
        }

        return redirect()->route('login')->withErrors(['email' => 'Invalid credentials.']);
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->route('login');
    }
}

Bước 4: Tạo view đăng nhập

Tạo thư mục auth trong resources/views và tạo file login.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login</title>
</head>
<body>
    <form method="POST" action="{{ route('login') }}">
        @csrf
        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>
        @if ($errors->any())
            <div>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        <div>
            <button type="submit">Login</button>
        </div>
    </form>
</body>
</html>​

Bước 5: Cấu hình routes

Thêm routes cho các hành động đăng nhập và đăng xuất trong file routes/web.php:
use App\Http\Controllers\AuthController;

Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

// Route protected by admin middleware
Route::middleware(['auth', 'admin'])->group(function () {
    Route::get('/admin/dashboard', function () {
        return view('admin.dashboard');
    })->name('admin.dashboard');
});

Bước 6: Tạo middleware cho admin

Tạo middleware để kiểm tra quyền admin:
php artisan make:middleware AdminMiddleware
Trong file app/Http/Middleware/AdminMiddleware.php:
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && Auth::user()->isAdmin()) {
            return $next($request);
        }

        return redirect()->route('login')->withErrors(['email' => 'You do not have admin access.']);
    }
}

Đăng ký middleware trong file app/Http/Kernel.php:

protected $routeMiddleware = [
    // ...
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

Bước 7: Tạo view cho admin dashboard

Tạo thư mục admin trong resources/views và tạo file dashboard.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
</head>
<body>
    <h1>Welcome to Admin Dashboard</h1>
    <form method="POST" action="{{ route('logout') }}">
        @csrf
        <button type="submit">Logout</button>
    </form>
</body>
</html>

Bước 8: Chạy migration và seed user

Chạy migration:
php artisan migrate
Tạo một user admin trong database bằng cách sử dụng tinker hoặc seed:
php artisan tinker
// Trong tinker
User::create([
    'name' => 'Admin User',
    'email' => 'admin@example.com',
    'password' => Hash::make('password'),
    'role_id' => 1,
]);
Với các bước trên, bạn đã tạo thành công chức năng đăng nhập với quyền là admin trong Laravel.

Bình luận (0)

Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough

Bài viết liên quan

Learning English Everyday