Home > Article > Backend Development > Analysis on Laravel registration refactoring
This article mainly introduces the analysis of Laravel registration reconstruction, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.
Sometimes you need to use laravel to build a background content Management system, but Laravel's default login registration cannot meet the current needs, so this requires Laravel registration reconstruction. Let's follow the editor to see how to perform registration reconstruction.
1. First determine the route for user registration
The registration generated by default when we install laravel is registered by email. And some options are not required, and some need to add some form options
If we register, we cannot register casually, only some super administrators can register
First we use the UserController
created last time for configuration. If not, you can use php artisan make:controller UserController
to create a controller class
and then Create two routes Route::get('register', 'UserController@getRegister')
and Route::post('register', 'UserController@postRegister')<br>
The former is a get
request to display a registration page, followed by a post
request to register an account.
2. Display the registration account page
This uses the getRegister
method. This method only needs to display one The view has no special logic
public function getRegister() { return view('auth.register'); }
3. Request to register an account
This The postRegister
method is used
Registering an account is the same as resetting a password, and it is simpler than registering an account.
When we insert a user record into the database, we can use User::create($data)
to insert.
$data
is an array that stores the key and value of each field
public function postRegister(Request $request) { $rules = [ 'username'=>'required|unique:finance_enewsuser', 'password' => 'required|between:6,20|confirmed' ]; $messages = [ 'required'=>':attribute不能为空', 'unique'=>'用户名已被注册', 'between' => '密码必须是6~20位之间', 'confirmed' => '新密码和确认密码不匹配' ]; $username = $request->input('username'); $password = $request->input('password'); $group = $request->input('group'); $data = $request->all(); $validator = Validator::make($data, $rules, $messages); if ($validator->fails()) { return back()->withErrors($validator); } $data = [ 'username' => $username, 'password' => bcrypt($password), 'groupid' => $group, 'checked' => 0, 'styleid' => 1, 'filelevel' => 0, 'loginnum' => 0, 'lasttime' => time(), 'lastip' => '127.0.0.1', 'truename' => '', 'email' => '', 'pretime' => time(), 'preip' => '127.0.0.1', ]; User::create($data); //插入一条新纪录,并返回保存后的模型实例 //如果注册后还想立即登录的话,可以使用$user = User::create($data); Auth::login($user); 进行认证 return redirect('/'); }
4. Completed example
##UserController
##public function getRegister() { return view('auth.register'); } public function postRegister(Request $request) { $rules = [ 'username'=>'required|unique:finance_enewsuser', 'password' => 'required|between:6,20|confirmed' ]; $messages = [ 'required'=>':attribute不能为空', 'unique'=>'用户名已被注册', 'between' => '密码必须是6~20位之间', 'confirmed' => '新密码和确认密码不匹配' ]; $username = $request->input('username'); $password = $request->input('password'); $group = $request->input('group'); $data = $request->all(); $validator = Validator::make($data, $rules, $messages); if ($validator->fails()) { return back()->withErrors($validator); } $data = [ 'username' => $username, 'password' => bcrypt($password), 'groupid' => $group, 'checked' => 0, 'styleid' => 1, 'filelevel' => 0, 'loginnum' => 0, 'lasttime' => time(), 'lastip' => '127.0.0.1', 'truename' => '', 'email' => '', 'pretime' => time(), 'preip' => '127.0.0.1', ]; User::create($data); //插入一条新纪录,并返回保存后的模型实例 return redirect('/'); }register.blade
<form class="login-form" action="" method="post"> {!! csrf_field() !!} <h3 class="font-green">Sign Up</h3> @if(count($errors) > 0) <p class="alert alert-danger display-hide" style="display: block;"> <button class="close" data-close="alert"></button> <span> </span> </p> @endif <p class="form-group"> <label class="control-label visible-ie8 visible-ie9">用户名</label> <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username"> </p> <p class="form-group"> <label class="control-label visible-ie8 visible-ie9">密码</label> <input class="form-control placeholder-no-fix" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password"> </p> <p class="form-group"> <label class="control-label visible-ie8 visible-ie9">重复密码</label> <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Repeat password" name="password_confirmation"> </p> <p class="form-group"> <label class="control-label visible-ie8 visible-ie9">用户组</label> <select name="group" class="form-control"> <option value="1"> 超级管理员 </option> <option value="2"> 管理员 </option> <option value="3"> 编辑 </option> </select> </p> <p class="form-actions"> <button type="submit" id="register-submit-btn" class="btn btn-success uppercase pull-right">注册</button> </p> </form>
5. Middleware – User must be logged in Now that the registration is complete, we only need the user’s judgment. It is required to register an account only with an account with super administrator privileges.
In this case, our general procedure is to directly find out the user's information in the postRegister method, and then check whether the user meets this permission. If not, jump to other pages.
This method is okay, but since we have the permissions of super administrator and administrator, it must be used in more than one place, and it will also be used in other places.
Then someone will think of writing a method in
, which can be called directly if necessary in the future.
This method is also possible, but we recommend using the middleware function provided by laravel. This function is very powerful and easy to use. Now we will use the middleware function.
Because we are a backend content management system, we first create a middleware. The function is that all pages must be logged in before entering, otherwise they will jump to the login page.
Check the manual and find that you can use the
command to create a middleware. Of course, copy a similar file and change it the same way.
Then a
middleware file will be created in the app/Http/Middleware/
directory, with only one handle()# in it. ##Method, we directly add our functions inside
<?php namespace App\Http\Middleware; use Closure; use Auth; class CheckLoginMiddleware { public function handle($request, Closure $next) { //使用Auth方法,需要引入use Auth;方法 //$request->is('login')表示请求的URL是否是登录页 //因为我们打算使用全局的,所以,需要把登录页排除,不然会无限重定向 //如果你的登录页不是/login,而是/auth/login的话,就写$request->is('auth/login') //并且我们要在请求处理后执行其任务,因为我们需要获取到用户的登录信息 $response = $next($request); if (!Auth::check() && !$request->is('login')) { return redirect('/login'); } return $response; } }The function of this middleware is that if a route is generated, first use
Auth: :check()
Determine whether the user is logged in. If not, jump to the login page.The method is written, but it cannot be used yet. We need to register this middleware and tell the framework that the middleware is written and can be used, and what is the scope of use.
There is a
Kernel.php
app/Http/ directory to register this middleware, which tells the framework that we have written it this middleware.
There are two array attributes in the
Kernel.php
$middleware represents global use, and the other
$routeMiddleware represents Can be used optionally.
Global use means that no matter which page you request, this middleware will be executed first.
Choose to use to indicate which HTTP request is required and where the middleware is required to be executed.
If every page here requires login, you can register a global one and add a
to the $middleware
array attribute.
\App\Http\Middleware\CheckLoginMiddleware::classRegister and you can use it
>注意:请记住,如果定义全局的要格外小心,比如上面我们要排除登录页,不然因为用户没有登录,所以在哪个页面都会重定向到登录页,当然也包括登陆页
6. 中间件–特殊页面需要验证用户组
现在是进行用户权限页面的限制,同样我们也要重新创建一个中间件
使用php artisan make:middleware CheckGroupMiddleware
创建一个新的中间件,用来判断这个用户是否满足这个权限
<?php namespace App\Http\Middleware; use Closure; use Auth; class CheckGroupMiddleware { public function handle($request, Closure $next) { $user = Auth::user(); if ($user->groupid != 1) { return redirect('/'); } return $next($request); } }
这里我们还是通过Auth::user()
来获取到用户的信息,然后判断用户的组,不属于超级管理员就跳到首页。
然后我们在到app/Http/
目录下有个Kernel.php
文件是注册这个中间件的,这次我们注册为可以选择的中间件。
这个中间件因为是可以选择的,所以我们还需要给它起个别名,在$routeMiddleware
数组属性里加如一条
'user.group' => \App\Http\Middleware\CheckGroupMiddleware::class
创建一个可以使用usergroup
这个名字使用的中间件。
创建好后,我们可以选择在哪里使用,一个是在router.php
的路由文件里加入,一个是在controller
里使用
在router.php文件里使用
Route::get('/', ['middleware' => ['user.group'], function () { // }]);
在控制器内使用
$this->middleware('user.group');
这里我们选择在路由里添加中间件。让注册页面只能是超级管理员才可以注册
Route::get('register', 'UserController@getRegister')->middleware('user.group'); Route::post('register', 'UserController@postRegister')->middleware('user.group');
我们目前只有两个路由要判断权限,所以使用了链式的写法,当然你也可以按照手册里上使用组的方式,组的方式更为优雅。
当然如果你的整个控制器内的方法都需要中间件进行验证过滤的话,你也可以创建组的形式,也可以直接在控制器内使用__construct
方法,让每次请求这个控制器时,先执行中间件
class MyController extends Controller { public function __construct() { $this->middleware('user.group'); } public function index() { return view('my.index'); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Analysis on Laravel registration refactoring. For more information, please follow other related articles on the PHP Chinese website!