Create Authentication In Laravel 5.8

Chào mọi người này mình chia sẻ với mọi người cách xây dựng Authentication trong Laravel 5.8 nhé. Trong bài hướng dẫn này mình sẽ tạo như sau, khi mình đăng nhập vào với quyền là user thì sẽ chuyển hướng sang trang người dùng, còn là admin thì vào quản lý website
Đầu tiên mình sẽ cài đặt project laravel 5.8 các bạn lưu lý để cài được laravel 5.8 đồi hỏi PHP >= 7.1.3 nhé

composer global require laravel/installer
laravel new blog

Sau khi tải xong các bạn chạy câu lệnh sau:

php artisan key:generate

Laravle sẽ tạo một key trong file .env (APP_KEY=YOUR_GENERATED_KEY),các bạn muốn xem key vừa tạo thì bạn chạy câu lệnh như sau:

php artisan key:generate --show

Tiếp tục bạn cần thiết lặp database trong file .env để chạy câu lệnh migrate sinh ra các table cần thiết cho laravel, Chú ý ở phần này khi chạy câu lệnh

php artisan migrate

Các bạn sẽ thấy lỗi như thế này:
Illuminate\Database\QueryException] SQLSTATE[42000] và không thể khởi tạo table mặc định trong laravel được, các bạn làm điều này cho mình, đầu tiên vào đường dân:App\Providers\AppServiceProvider.php lên và chỉnh lại như sau:

use Illuminate\Support\Facades\Schema;
public function boot()
{
    Schema::defaultStringLength(191);
}

Sau khi chỉnh xong bạn chạy lại câu lệnh: php artisan migrate

Vậy là xong chúng ta đã tạo thành công một project laravel, giờ là bước chúng ta cài đặt Authentication trong laravel,
laravel đã hỗ trợ cho ta phần login và register sau ta không tận dụng nó để triển khai ứng dụng của mình nào, bắt đầu chạy câu lệnh như sau:

php artisan make:auth

Bạn sẽ nhìn thấy trong thư mục View xuất hiện thư mục auth và chứa các file login,register, password đã tạo sẵn cho ta, bên cạnh đó bạn sẽ nhìn thấy một file HomeController trong thư mục App\Http\Controller

Tiếp theo mình sẽ tạo một mô hình người dùng như sau: php artisan make:model Role -m

Sau khi bạn chạy câu lệnh trên laravel sẽ tạo cho bạn một file model là Role.php và file migration trong thư mục database\migrations bạn mở file vừa tạo lên và chỉnh sửa lại như sau:

class CreateRolesTable extends Migration
    {
        public function up()
        {
            Schema::create('roles', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('description');
                $table->timestamps();
            });
        }

        public function down()
        {
            Schema::dropIfExists('roles');
        }
    }

Sau khi tạo xong bạn tiến hành chạy: php artisan migrate để tạo ra một table roles trong database project của mình
Các bạn cũng đã biết User có nhiều vai trò trong hệ thống, mà một vai trò thì lại có nhiều User, ý mình muốn nói đến ở đây là mối quan hệ giữa User và Role, chính vì thế mà ta phải tiến hành tạo mối quan hệ relationship của hai Table(Users,Roles)

Mở file model User.php cập nhật như sau:
// File: ./app/User.php
    public function roles() 
    {
        return $this->belongsToMany(Role::class);
    }
Mở file model Roler.php cập nhật lại như sau:
    // File: ./app/Role.php
    public function users() 
    {
        return $this->belongsToMany(User::class);
    }

Chúng ta cũng cần tạo một table chứa quan hệ thân thiết của hai table này nửa nhé, quan hệ là phải thân thiết với nhau rồi, cho chúng gần nhau xíu mà cũng không sau đâu nhé

php artisan make:migration create_role_user_table create=role_user 

Tiếp tục vào folder database/migrations tìm file vừa tạo và cập nhật lại, chắc là nó phải chứa 2 cái khóa ngoại rồi chắc luôn ::)

// File: ./database/migrations/*_create_role_user_table.php
    <?php 

    // [...]

    class CreateRoleUserTable extends Migration
    {

        public function up()
        {
            Schema::create('role_user', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('role_id')->unsigned();
                $table->integer('user_id')->unsigned();
            });
        }

        public function down()
        {
            Schema::dropIfExists('role_user');
        }
    }

Sau khi cập nhật xong thì chúng ta cũng phải chạy: php artisan migrate để sinh ra một table role_user trong database project của chúng ta

Ôi mệt thiệt, thế là xong, à quên, để tạo dữ liệu mẫu, ta cần tạo vài dữ liệu để check hệ thống chứ nào. Bạn tạo 2 cái seeder cho mình nhé

php artisan make:seeder RoleTableSeeder
php artisan make:seeder UserTableSeeder

Trong database/seeds và mở file vừa tạo cập nhật lại như sau:

// File: ./database/seeds/RoleTableSeeder.php
    <?php 

    use App\Role;
    use Illuminate\Database\Seeder;

    class RoleTableSeeder extends Seeder
    {
        public function run()
        {
            $role_regular_user = new Role;
            $role_regular_user->name = 'user';
            $role_regular_user->description = 'A regular user';
            $role_regular_user->save();

            $role_admin_user = new Role;
            $role_admin_user->name = 'admin';
            $role_admin_user->description = 'An admin user';
            $role_admin_user->save();
        }
    }

    // File: ./database/seeds/UserTableSeeder.php
    <?php 

    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\Hash;
    use App\User;
    use App\Role;

    class UserTableSeeder extends Seeder
    {

        public function run()
        {
            $user = new User;
            $user->name = 'Skipperhoa';
            $user->email = 'skipperhoa@hoanguyenit.com';
            $user->password = bcrypt('12345678');
            $user->save();
            $user->roles()->attach(Role::where('name', 'user')->first());

            $admin = new User;
            $admin->name = 'hoa123';
            $admin->email = 'hoa123@hoanguyenit.com';
            $admin->password = bcrypt('hoa12345678');
            $admin->save();
            $admin->roles()->attach(Role::where('name', 'admin')->first());
        }
    }
 // File: ./database/seeds/DatabaseSeeder.php
    <?php 

    // [...]

    class DatabaseSeeder extends Seeder
    {
        public function run()
        {
            $this->call([
                RoleTableSeeder::class, 
                UserTableSeeder::class,
            ]);
        }
    }

Sau khi cập nhật xong bạn chạy câu lệnh sau để tiến hành thêm dữ liệu vào database nhé:

php artisan db:seed

Giờ chúng ta đã có dữ liệu rồi đó là lúc chúng ta có thể login thử, chắc là login được mình phải tự tin chứ. Mà điều chúng ta cần là làm thế nào để khi ta đăng nhập với quyền hạn là User thì nó sẽ chuyển hướng sang trang khác và admin thì trang khác đó là điều ta cần làm như sau:

// File: ./app/User.php
    public function checkRoles($roles) 
    {
        if ( ! is_array($roles)) {
            $roles = [$roles];    
        }

        if ( ! $this->hasAnyRole($roles)) {
            auth()->logout();
            abort(404);
        }
    }

    public function hasAnyRole($roles): bool
    {
        return (bool) $this->roles()->whereIn('name', $roles)->first();
    }

    public function hasRole($role): bool
    {
        return (bool) $this->roles()->where('name', $role)->first();
    }

Bạn vào file model User.php và thêm đoạn mã trên cho mình: Đoạn mã trên có nhiệm vụ check vai trò khi ta login vào hệ thống, và sử dụng nó như sau:
Mở file HomeController.php lên

public function __construct()
{
    $this->middleware('auth');
}
public function index()
{
    if ($request->user()->hasRole('user')) {
        return view('home');
    }

    if ($request->user()->hasRole('admin')) {
        return redirect('/admin/home');
    }
}


//hoặc bạn đừa vào một mãng Roler(vai trò như sau)
if ($request->user()->hasRole(['user','admin')) {
    return view('home');
}

Nói chung tuy theo trong project của mình có bao nhiêu quyền hạn và vai trò, khi ta muốn cho vai trò nào được vào hệ thống nào thì đó là lúc ta sử dụng câu lệnh bên trên
Chúng ta cần chỉnh sửa lại file bên dưới đây, khi ta bấm vào Register để đăng ký một user mới

// File: ./app/Http/Controllers/Auth/RegisterController.php
protected function create(array $data)
{       
    $user = User::create([
        'name'     => $data['name'],
        'email'    => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $user->roles()->attach(\App\Role::where('name', 'user')->first());

    return $user;
}

Vậy là xong giờ chúng ta có thể chạy thử project của mình bằng cách chạy câu lệnh thường chạy như sau:

php artisan serve

Gõ vào trình duyệt http://localhost:8000 hoặc http://128.0.0.1:8000 để thử nghiệm nhé, bài sao mình sẽ Build CMS với Laravel cùng với Vuejs để quản lý trong Admin nhé

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)