Home >Backend Development >PHP Tutorial >Analysis on Laravel registration refactoring

Analysis on Laravel registration refactoring

不言
不言Original
2018-06-13 17:23:511292browse

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(&#39;auth.register&#39;);
}

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 = [
  &#39;username&#39;=>&#39;required|unique:finance_enewsuser&#39;,
  &#39;password&#39; => &#39;required|between:6,20|confirmed&#39;
 ];
 $messages = [
  &#39;required&#39;=>&#39;:attribute不能为空&#39;,
  &#39;unique&#39;=>&#39;用户名已被注册&#39;,
  &#39;between&#39; => &#39;密码必须是6~20位之间&#39;,
  &#39;confirmed&#39; => &#39;新密码和确认密码不匹配&#39;
 ];
 $username = $request->input(&#39;username&#39;);
 $password = $request->input(&#39;password&#39;);
 $group = $request->input(&#39;group&#39;);
 $data = $request->all();
 $validator = Validator::make($data, $rules, $messages);
 if ($validator->fails()) {
  return back()->withErrors($validator);
 }
 $data = [
  &#39;username&#39; => $username,
  &#39;password&#39; => bcrypt($password),
  &#39;groupid&#39; => $group,
  &#39;checked&#39; => 0,
  &#39;styleid&#39; => 1,
  &#39;filelevel&#39; => 0,
  &#39;loginnum&#39; => 0,
  &#39;lasttime&#39; => time(),
  &#39;lastip&#39; => &#39;127.0.0.1&#39;,
  &#39;truename&#39; => &#39;&#39;,
  &#39;email&#39; => &#39;&#39;,
  &#39;pretime&#39; => time(),
  &#39;preip&#39; => &#39;127.0.0.1&#39;,
 ];
 User::create($data); //插入一条新纪录,并返回保存后的模型实例
 //如果注册后还想立即登录的话,可以使用$user = User::create($data); Auth::login($user); 进行认证
 return redirect(&#39;/&#39;);
}

4. Completed example

##UserController

##
public function getRegister()
{
 return view(&#39;auth.register&#39;);
}

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

model

, 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

php artisan make:middleware CheckLoginMiddleware

command to create a middleware. Of course, copy a similar file and change it the same way.
Then a

CheckLoginMiddleware

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(&#39;login&#39;)表示请求的URL是否是登录页
  //因为我们打算使用全局的,所以,需要把登录页排除,不然会无限重定向
  //如果你的登录页不是/login,而是/auth/login的话,就写$request->is(&#39;auth/login&#39;)
  //并且我们要在请求处理后执行其任务,因为我们需要获取到用户的登录信息
  $response = $next($request);
  if (!Auth::check() && !$request->is(&#39;login&#39;)) {
   return redirect(&#39;/login&#39;);
  }
  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

file in the

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

file, one

$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::class

Register 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(&#39;/&#39;);
  }
  return $next($request);
 }
}

这里我们还是通过Auth::user()来获取到用户的信息,然后判断用户的组,不属于超级管理员就跳到首页。

然后我们在到app/Http/目录下有个Kernel.php文件是注册这个中间件的,这次我们注册为可以选择的中间件。

这个中间件因为是可以选择的,所以我们还需要给它起个别名,在$routeMiddleware数组属性里加如一条

&#39;user.group&#39; => \App\Http\Middleware\CheckGroupMiddleware::class

创建一个可以使用usergroup这个名字使用的中间件。

创建好后,我们可以选择在哪里使用,一个是在router.php的路由文件里加入,一个是在controller里使用

在router.php文件里使用

Route::get(&#39;/&#39;, [&#39;middleware&#39; => [&#39;user.group&#39;], function () {
 //
}]);

在控制器内使用

$this->middleware(&#39;user.group&#39;);

这里我们选择在路由里添加中间件。让注册页面只能是超级管理员才可以注册

Route::get(&#39;register&#39;, &#39;UserController@getRegister&#39;)->middleware(&#39;user.group&#39;);
Route::post(&#39;register&#39;, &#39;UserController@postRegister&#39;)->middleware(&#39;user.group&#39;);

我们目前只有两个路由要判断权限,所以使用了链式的写法,当然你也可以按照手册里上使用组的方式,组的方式更为优雅。

当然如果你的整个控制器内的方法都需要中间件进行验证过滤的话,你也可以创建组的形式,也可以直接在控制器内使用__construct方法,让每次请求这个控制器时,先执行中间件

class MyController extends Controller
{
 public function __construct()
 {
  $this->middleware(&#39;user.group&#39;);
 }

 public function index()
 {
  return view('my.index');
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Larave如何实现短信注册

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!

Statement:
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