Home > PHP Framework > Laravel > body text

Appoint an administrator and elevate privileges to ordinary Laravel users

藏色散人
Release: 2020-10-29 14:48:12
forward
2637 people have browsed it

The following tutorial column of Laravel will introduce to you how to elevate the rights of ordinary Laravel users. I hope it will be helpful to friends who need it!

Appoint an administrator and elevate privileges to ordinary Laravel users

Introduction

The User table is used in the system to record user attributes, and each maintains the user's own associated data. Some front-end pages also need to display different levels of content based on identity.

In this issue, we will talk about elevating the rights of ordinary users to administrator.

Data preparation

We hope to specify the user's identity in the users table, such as being appointed as an administrator, so that more data resources can be displayed.

We append a field in the users table is_admin to mark the user’s administrator identity. Use the command to create a migration file:

php artisan make:migration add_is_admin_to_user_table --table=users复制代码
Copy after login

First fill in up Method used for the logic of migration execution:

public function up(){
    Schema::table('users', function(Blueprint $table)    {
    	$table->boolean('is_admin')->default(false);
    });
}
Copy after login

If the migration fails, the down method used for rollback:

public function down() 
{
    Schema::table('users', function(Blueprint $table)    {
    	$table->dropColumn('is_admin');
    }
}
Copy after login

Save after completing the editing, and execute the migration Instructions:

php artisan migrate复制代码
Copy after login

For testing, we use the mysql client to connect directly to the database and manually specify an administrator, using the following SQL statement:

update users set is_admin = true where email = 'admin@admin.com';
Copy after login

Routing

For the sake of distinction For the front-end page for ordinary users, we use the new namespace Admin to place administrator-related code. First create the controller:

php artisan make:controller Admin/UsersController复制代码
Copy after login

Then add the route, edit the routes/web.php file and add the following content:

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function(){
	Route::resource('user', 'UsersController');
});
Copy after login

Note that we use two key parameters ,

  • prefix: that is, all routing addresses in the group, use prefix as the prefix
  • namespace: namespace, specifying that all controllers in the group are located in this name under space.

Controller

In the routing in the previous section, we defined resource routing, using restful style declarations. Create the app/Http/Controllers/admin/UsersController.php file below and implement the index method. The code content is as follows:

public function index(){
    $users = User::orderBy('created_at', 'desc')->get();    return view('admin.users.index')->withUsers($users);
}
Copy after login

We also need a view file to carry the above data. Create the directory resources/views/admin/users/index.blade.php and simply create a template:

<h1>Registered Users</h1>
<ul>
    @forelse ($users as $user)
    	<li>{{ $user->name }} ({{ $user->email }})</li>
    @empty
    	<li>No registered users</li>
    @endforelse
</ul>
Copy after login

展示的是所有用户的信息。这显然必须拥有较高的权限。所以我们在给数据之前,要识别用户是否管理员:

if (Auth::user()->is_admin != true) {	return redirect()->route('home')->withMessage('Access denied!');
}
Copy after login

如果不是就路由到首页。这样的判断,如果页面多了起来之后,每次都要在控制器内敲写,着实麻烦。所以,必须使用更靠前的验证,也就是 中间件

中间件

中间件可以注册给路由文件,在命中路由后,调用中间件进行身份识别,这是不错的选择。

使用命令行创建中间件文件:

php artisan make:middleware AdminAuthentication复制代码
Copy after login

生成的文件位于 app/Http/Middleware/ 目录下,编辑 AdminAuthentication 文件,并实现代码逻辑:

namespace App\Http\Middleware;use Closure;use Illuminate\Contracts\Auth\Guard;use Illuminate\Http\RedirectResponse;class AdminAuthentication {    public function handle($request, Closure $next)    {    	if ($request->user())
    	{    		if ($request->user()->is_admin == true)
    		{    			return $next($request);
    		}
    	}        // 验证不通过
        return new RedirectResponse(url('/'));
    }
}
Copy after login

然后在 app/Http/Kernel.php 文件内注册该中间件,并命名:

protected $routeMiddleware = [	'admin' => \App\Http\Middleware\AdminAuthentication::class,
];复制代码
Copy after login

修改 路由 一节中声明的路由组,引入中间件:

Route::group(
[    'prefix' => 'admin',    'namespace' => 'admin',    'middleware' => 'admin'], function(){
	Route::resource('users', 'UsersController');
});
Copy after login

写在最后

本文又是一个功能齐全却又mini小巧的短文,详细阐述了如何为users表添加管理员功能。

通过注册路由到中间件的使用,又一次体验了laravel各个组件协同作用的能力!


The above is the detailed content of Appoint an administrator and elevate privileges to ordinary Laravel users. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template