Trang chủ » Blog » Làm quen với Gate trong Laravel

Làm quen với Gate trong Laravel

bởi CodeGym | 06/12/2023 17:30 | Blog

Bước 1: Tải dự án laravel

composer create-project –prefer-dist laravel/laravel Authorization_Gate

Lưu ý : ở đây mình đang tải laravel bằng composer và tên của dự án là Authorization_Gate.

Bước 2: Cấu hình sử dụng laravel authentication

chạy lệnh php artisan serve và truy cập link : http://127.0.0.1:8000/ để xem thành quả

Bước 3: Migrate và seeder dữ liệu

Thêm trường type trong database/migrations/create_users :

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('type')->default('user')
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Thêm dữ liệu seeder cho bảng UserSeeder (php artisan make:seeder UserSeeder)

public function run()
    {
        DB::table('users')->insert([
            'name' => 'admin',
            'email' => 'admin@gmail.com',
            'type'  => 'admin',
            'password' => Hash::make('123456789'),
        ]);
        DB::table('users')->insert([
            'name' => 'user',
            'email' => 'user@gmail.com',
            'type'  => 'user',
            'password' => Hash::make('123456789'),
        ]);
        DB::table('users')->insert([
            'name' => 'manager',
            'email' => 'manager@gmail.com',
            'type'  => 'manager',
            'password' => Hash::make('123456789'),
        ]);
    }

Khởi chạy bằng lệnh :  php artisan migrate:fresh –seed và xem thành quả :

Bước 4: Sử dụng Gate: để cấp quyền truy cập :

laravel

tại thư mục app/Providers/AuthServiceProvider.php thêm vào phương thức boot :

 Gate::define('permission',function($user){
            return $user->type === 'admin' || $user->type === 'manager' ;
        });

Hàm trên trả về kết quả đúng nếu user đăng nhập vào có kiểu type là admin hoặc manager.
Sử dụng middleware để lọc Gate:

Route::get('/home', 'HomeController@index')->name('home')->middleware(['can:permission']);

Bước 5: Chỉnh sửa views

a. vào views/ home.blade.php  và thêm vào <p>{{ Auth::user()->type}}</p> để biết user đang login vào thuộc kiểu nào;

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>
                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                    <p> {{ Auth::user()->type }} logged in!</p>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

b.tạo views/errors/403.blade.php để xem lỗi

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1 style="text-align: center">Bạn ko đủ quyền</h1>  
    <a class="dropdown-item" href="{{ route('logout') }}"
    onclick="event.preventDefault();
                  document.getElementById('logout-form').submit();">
     {{ __('Logout') }}
    </a>
    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
        @csrf
    </form>
</body>
</html>

Bước 6: Xem thành quả

a . login bằng tài khoản admin:laravel

b. login bằng tài khoản manager:

laravel

c. login bằng tài khoản user:

Author: Phan Thiên Hoàng

Đăng ký nhận bộ tài liệu học Java trên 2 trang giấy tại đây

Xem thêm: Java Coding Bootcamp là gì? Tổng quan về Java Coding Bootcamp

Download - Giáo trình thuật toán

1 + 14 =

Tags:

0 Lời bình

Gửi Lời bình

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

BÀI VIẾT LIÊN QUAN

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY

098 953 44 58

Đăng ký tư vấn lộ trình học lập trình

Đăng ký tư vấn, định hướng lộ trình học và giải đáp các thắc mắc về ngành nghề – Miễn phí – Online.

1 + 1 =

TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM
TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM